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
10mod courier;
11mod plugin_host;
12pub mod scan;
13pub use plugin_host::{LazyTrigger, PluginHost};
14
15mod operator_pending;
16pub mod status;
17
18pub use operator_pending::{OpState, OperatorPending};
19
20/// What one key meant to the operator-pending object layer.
21enum ObjectKey {
22    /// Swallowed — the key began an object and nothing runs yet.
23    Consumed,
24    /// The object is complete; run this.
25    Compose(Action),
26}
27pub use status::{PromptKind, StatusModel};
28
29use std::collections::HashMap;
30
31use awase::KeyRepeatGate;
32use escriba_buffer::BufferSet;
33use escriba_buffer::TextRev;
34use escriba_command::CommandRegistry;
35use escriba_core::{
36    Action, Anchored, Bound, BufferId, Cursors, Damage, Edit, EditGen, HighlightEffect, JumpList,
37    Mode, Motion, Operator, Position, Range, TextEffect, WindowId,
38};
39use escriba_input::{InputOutcome, translate_app_event};
40use escriba_keymap::{Key, Keymap};
41use escriba_madoguchi::{Negai, Outcome};
42use escriba_mode::ModalState;
43use escriba_search::{Direction as SearchDirection, MatchCount, SearchState};
44use escriba_ui::chrome::{ChromePalette, FleetTheme};
45use escriba_ui::splash::Splash;
46use escriba_ui::{Layout, Viewport, Window};
47use escriba_vm::{EditorSnapshot, EscribaHost, EscribaVm, VmError};
48use madori::AppEvent;
49use std::time::Instant;
50
51/// Full editor state — the single Rust value the binary hands to the
52/// renderer each frame.
53pub struct EditorState {
54    pub buffers: BufferSet,
55    pub modal: ModalState,
56    /// Search session — the committed pattern, its matches, the live `/`
57    /// prompt and history. Owns no buffer or cursor; it answers questions
58    /// about text and this runtime applies the answers.
59    pub search: SearchState,
60    pub keymap: Keymap,
61    pub commands: CommandRegistry,
62    pub layout: Layout,
63    pub active: BufferId,
64    /// The single typed home for cursor state. Phase-1 holds one primary
65    /// [`Position`]; reads go through [`Self::cursor`], writes through
66    /// [`Self::set_cursor`] → [`Cursors::set_primary`]. There is no loose
67    /// `Position` field beside an unused multi-caret type to desync.
68    cursors: Cursors,
69    pub quit_requested: bool,
70    /// Messages surfaced to the user (status line / `:messages`) — the
71    /// sink for the tatara-lisp `(message …)` effect and other feedback.
72    pub messages: Vec<String>,
73    /// Which match the cursor last landed on (0-based) — the `[3/17]`
74    /// numerator, ANCHORED to the text revision it was computed against.
75    ///
76    /// The anchor is what removes the manual invalidation this field used to
77    /// need. An ordinal indexes a match set; when the text changes the set
78    /// changes underneath it and the number silently means something else.
79    /// Reading through `Anchored::get(current_rev)` makes that a `None`, so
80    /// forgetting to clear is no longer a thing that can be forgotten.
81    search_at: Option<Anchored<usize, TextRev>>,
82    /// The last text change, for `.`.
83    ///
84    /// An action plus whatever was typed while it held Insert open. Both
85    /// halves are needed: `cw` alone is not a change, it is the FIRST HALF of
86    /// one — the text that followed is the rest, and replaying without it
87    /// would delete a word and leave the buffer in Insert.
88    last_change: Option<LastChange>,
89    /// True while an insert session belonging to `last_change` is open, so
90    /// typed characters are appended to it. Cleared on leaving Insert.
91    recording_insert: bool,
92
93    /// Where the cursor was before each far jump — `<C-o>` / `<C-i>`.
94    /// Search commits, `n`/`N` and `*`/`#` all record into it, which is what
95    /// makes a search a place you can come back from.
96    pub jumps: JumpList,
97    /// Generic editor option store (name → value). Written by the
98    /// tatara-lisp `(set-option …)` effect and the declarative
99    /// `defoption` apply path; typed accessors layer on top later.
100    pub options: HashMap<String, String>,
101    /// Cached embedded tatara-lisp runtime, built lazily on first
102    /// `run_lisp`. Caching avoids re-installing the ~175-definition full
103    /// stdlib on every call; the interpreter's top-level env also
104    /// persists across calls, giving REPL-like session semantics (an
105    /// earlier `(define …)` is visible to a later `run_lisp`).
106    lisp_vm: Option<EscribaVm>,
107    /// Keys accumulated for an in-progress multi-key sequence — e.g.
108    /// holding `[,, f]` while waiting for the final key of
109    /// `<leader>ff`. Empty when not mid-sequence. Lives on
110    /// `EditorState` (not `ModalState`) so `escriba-mode` needn't
111    /// depend on `escriba-keymap`'s `Key`.
112    pub pending_keys: Vec<Key>,
113    /// Per-key debouncer for OS key-repeat storms. Holding `j`/`l` makes
114    /// the windowing system deliver one `KeyDown` per repeat tick
115    /// (~30-50ms); without a gate those flood the motion path and thrash
116    /// the viewport. The gate lets ONE event per `min_interval` (80ms
117    /// default — ~12 intentional taps/sec still pass) reach the editor in
118    /// the navigation modes. The fleet primitive (`awase::KeyRepeatGate`,
119    /// the same one mado uses) is reused — not reinvented.
120    repeat_gate: KeyRepeatGate<Key>,
121    /// Runtime lazy-activation host for USER plugin caixas (the bundled
122    /// default catalog is applied eagerly at boot, not through here).
123    /// A command / filetype-open / event fires the matching plugins'
124    /// entries through the escriba-lisp apply paths. See [`PluginHost`].
125    pub plugin_host: PluginHost,
126    /// The unnamed register — the home for text an operator yanks or
127    /// deletes (`Operator::leaves_register`). `None` until the first
128    /// register-leaving operator runs. Phase-1 holds the single unnamed
129    /// register; named registers (`"ay`) layer on later.
130    register: Option<String>,
131    /// The operator-pending FSM (`d`/`c`/`y` then a motion → `dw`/`c$`/`y0`),
132    /// standing on the fleet `zenmai` Mealy-machine primitive. Every dispatched
133    /// action passes through it; only an operator-then-motion pair is rewritten
134    /// into an [`Action::ApplyOperator`].
135    op_pending: zenmai::Stateful<OperatorPending>,
136    /// Operator-pending OBJECT selection, held at the KEY layer.
137    ///
138    /// `Some(around)` means `d` + `i`/`a` have been pressed and the NEXT key
139    /// names the object. It lives here rather than in the operator FSM
140    /// because the FSM sees `Action`s and this decision needs the KEY: `a`
141    /// and every bracket are unbound in Normal, so they all arrive as
142    /// `Action::Pending` with the character already discarded. vim has a
143    /// whole operator-pending keymap for the same reason.
144    pending_object: Option<bool>,
145    /// Monotonic refresh-generation stamp — the root of the sealed refresh
146    /// tree (`theory/ESCRIBA.md` §Refresh-Seal). Bumped on every applied
147    /// action + resize; the renderer gates on it so an idle frame does zero
148    /// re-highlight / re-shape, and a stale frame is unreachable.
149    edit_gen: EditGen,
150    /// The accumulated dirty region since the renderer last drained it (M1).
151    /// Only ever widened via [`Damage::join`] at the mutation funnel, so it
152    /// always covers the changed region (`Damage ⊇ changed`); the renderer
153    /// drains it with [`take_damage`](Self::take_damage) to scope its work.
154    damage: Damage,
155    /// The theme every face paints with.
156    ///
157    /// ONE owner. Before this, `(deftheme :preset …)` parsed, validated,
158    /// resolved to a real `FleetTheme` — and then nothing consumed it,
159    /// because each renderer called `ChromePalette::prescribed()` at every
160    /// paint site. The declaration was honoured on paper only. Holding it
161    /// here means a face reads the operator's theme the same way it reads
162    /// the cursor: from the state, per frame.
163    theme: FleetTheme,
164    /// `theme` resolved to concrete colours — cached because it is a plain
165    /// `Copy` struct read many times per frame, and re-derived only in
166    /// [`set_theme`](Self::set_theme), so the two cannot disagree.
167    chrome: ChromePalette,
168    /// How deep the current command dispatch is nested.
169    ///
170    /// `Negai::RunCommand` lets a command invoke a command, which is useful
171    /// and which can also recurse forever. The budget makes the runaway
172    /// bounded and REPORTED rather than a stack overflow — the difference
173    /// between a typed refusal and the editor dying under the operator.
174    dispatch_depth: u8,
175    /// Every live result list — diagnostics, hunks, grep hits, TODOs.
176    ///
177    /// Public so a producer outside the runtime can publish into it once the
178    /// courier lands; today the only producer is the marker scan.
179    pub results: escriba_shirube::ListRegistry,
180    /// The open picker, if any.
181    ///
182    /// `Option<Picker>` on the state, exactly like `splash` — deliberately
183    /// NOT a `Mode` variant. A mode is a state keys are interpreted IN; this
184    /// is a surface that OWNS keys while it is up, which is a different
185    /// thing and composes differently with the keymap.
186    picker: Option<escriba_ui::picker::Picker>,
187    /// The git-index generation. See [`world`](Self::world) — every axis the
188    /// world can move is emitted unconditionally, so a producer anchoring on
189    /// one is not born permanently stale.
190    index_rev: escriba_shirube::IndexRev,
191    /// The language-server generation — bumped when a server restarts.
192    lsp_gen: escriba_shirube::SessionGen,
193    /// The filesystem-scan generation — bumped when a surface a scan feeds
194    /// opens or closes, which is what supersedes an in-flight scan.
195    scan_gen: escriba_shirube::SessionGen,
196    /// Work handed off the editor thread. Inert until the composition root
197    /// hires a crew, so every existing `EditorState::new*` call site is
198    /// unchanged and the editor is fully usable with no runners at all.
199    courier: courier::Courier,
200    /// Which findings list the open picker is a VIEW of, if any —
201    /// `(workspace, list)`. Set when a picker opens over a live producer,
202    /// cleared whenever the picker closes.
203    picker_projects: Option<(bool, Option<String>)>,
204    /// Extension → language facts, populated from `(defmode …)`.
205    ///
206    /// The consumer `:commentstring` never had. Public so the binary's apply
207    /// pass can fill it the way it fills the keymap and the option store.
208    pub filetypes: escriba_core::FiletypeTable,
209    /// The start screen, while it is up.
210    ///
211    /// `Some` only between boot and the first keypress, and only when the
212    /// editor opened with no file. It is deliberately NOT a `Mode`: a mode
213    /// is a state keys are interpreted *in*, and the splash interprets
214    /// exactly one key before it is gone. Modelling it as `Option<Splash>`
215    /// keeps the modal state machine's variant set — and every exhaustive
216    /// match over it — untouched.
217    splash: Option<Splash>,
218}
219
220/// What the start screen did with a keypress.
221///
222/// Total, and matched exhaustively at its one call site, so a future
223/// outcome (a menu that opens a submenu, say) is a compile error rather
224/// than a key that silently falls through to the buffer.
225enum SplashKey {
226    /// No start screen is up — the key is the buffer's.
227    NotShowing,
228    /// The key selected a menu entry; run this.
229    Ran(Action),
230    /// The screen is gone and the key was not a menu key, so it still
231    /// means whatever it normally means. Anything else would make the
232    /// first keystroke after boot vanish.
233    Dismissed,
234}
235
236// ─── The counter, and the one place slips become mutations ───────────────
237
238/// `EditorState` read through the counter.
239///
240/// Borrowed, never copied: building it is free, so a command dispatch does
241/// not pay for a snapshot of the buffers.
242pub struct EditorWindow<'a> {
243    state: &'a EditorState,
244}
245
246impl escriba_madoguchi::CursorView for EditorWindow<'_> {
247    fn position(&self) -> Position {
248        self.state.cursor()
249    }
250    fn mode(&self) -> Mode {
251        self.state.modal.mode()
252    }
253}
254
255impl escriba_madoguchi::SyntaxView for EditorWindow<'_> {
256    fn filetype(&self) -> Option<&escriba_core::Filetype> {
257        let path = self.state.buffers.get(self.state.active)?.path.as_deref()?;
258        self.state.filetypes.resolve(path)
259    }
260}
261
262impl escriba_madoguchi::SearchView for EditorWindow<'_> {
263    fn pattern(&self) -> Option<&str> {
264        self.state.search.committed_pattern()
265    }
266    fn match_count(&self) -> Option<usize> {
267        // `None` means "nothing committed", which is not the same as zero
268        // matches — a distinction the status line already makes and that a
269        // handler must not have to re-derive.
270        self.state
271            .search
272            .committed_pattern()
273            .map(|_| self.state.search.match_count())
274    }
275    fn is_prompting(&self) -> bool {
276        self.state.search.is_prompting()
277    }
278}
279
280impl escriba_madoguchi::Snapshot for EditorWindow<'_> {
281    fn active(&self) -> Option<&dyn escriba_madoguchi::BufferView> {
282        self.buffer(self.state.active)
283    }
284    fn buffer(&self, id: BufferId) -> Option<&dyn escriba_madoguchi::BufferView> {
285        self.state
286            .buffers
287            .get(id)
288            .map(|b| b as &dyn escriba_madoguchi::BufferView)
289    }
290    fn buffer_ids(&self) -> Vec<BufferId> {
291        self.state.buffers.ids()
292    }
293    fn cursor(&self) -> &dyn escriba_madoguchi::CursorView {
294        self
295    }
296    fn option(&self, name: &str) -> Option<&str> {
297        self.state.options.get(name).map(String::as_str)
298    }
299    fn search(&self) -> &dyn escriba_madoguchi::SearchView {
300        self
301    }
302    fn syntax(&self) -> &dyn escriba_madoguchi::SyntaxView {
303        self
304    }
305}
306
307impl EditorState {
308    /// A read-only window onto this editor.
309    #[must_use]
310    pub fn window(&self) -> EditorWindow<'_> {
311        EditorWindow { state: self }
312    }
313
314    /// Honour an [`Outcome`] — the ONLY place slips become mutations.
315    ///
316    /// Every `&mut self` in the dispatch path lives here. A command cannot
317    /// reach editor state, so if the editor ends up in a state nobody
318    /// designed, this function is where it happened; that narrowing is the
319    /// whole return on the seam.
320    ///
321    /// A failed outcome's slips are DROPPED rather than half-applied: a
322    /// handler that reported failure has no business also mutating, and
323    /// applying part of what it asked for is how an editor reaches a state
324    /// nobody designed.
325    pub fn interpret(&mut self, outcome: Outcome) {
326        if let Some(m) = outcome.verdict.message() {
327            self.messages.push(m.to_string());
328            self.damage = self.damage.join(Damage::Viewport);
329            self.bump_gen();
330        }
331        if outcome.verdict.is_failure() {
332            return;
333        }
334        for slip in outcome.slips {
335            self.honour(slip);
336        }
337    }
338
339    /// Lower an [`Action`] to slips, when it has an exact slip equivalent.
340    ///
341    /// `None` means "editor mechanics" — 23 of the 30 variants are prompt
342    /// editing, the operator-pending FSM, motion resolution, the jumplist,
343    /// the dot register. Those are the KEYMAP's vocabulary, not the AUTHORED
344    /// one, and forcing them into `Negai` would put `PromptClearToStart` and
345    /// `SearchPreviewStep` in front of every plugin author and make the
346    /// capability question meaningless (what capability does a caret move
347    /// read?). One type serving two vocabularies is the mistake this avoids.
348    ///
349    /// The plan's M3 predicate was "apply_resolved contains zero `self.`
350    /// mutations", which would have forced exactly that. Amended: the
351    /// invariant worth having is ONE IMPLEMENTATION PER MUTATION, not one
352    /// vocabulary. See docs/backlog-plan.md §V Phase 1.
353    fn lower(action: &Action, active: BufferId) -> Option<Vec<Negai>> {
354        Some(match action {
355            Action::Quit => vec![Negai::Quit],
356            Action::ClearSearchHighlight => vec![Negai::ClearSearchHighlight],
357            Action::Save => vec![Negai::Save { buffer: active }],
358            Action::Undo => vec![Negai::Undo { buffer: active }],
359            Action::Redo => vec![Negai::Redo { buffer: active }],
360            // `apply_edit` was a STUB that did nothing, so this action was a
361            // silent no-op while `Negai::Edit` applied for real. Lowering it
362            // makes keymap-originated edits work for the first time — and
363            // nothing binds it today, so the duplication goes away at zero
364            // risk.
365            Action::Edit(edit) => vec![Negai::Edit {
366                buffer: active,
367                edit: edit.clone(),
368            }],
369            _ => return None,
370        })
371    }
372
373    /// What the world currently is, for freshness.
374    ///
375    /// One text axis per open buffer. A list sealed against this is fresh
376    /// exactly while the buffers it depends on are unchanged — and a buffer
377    /// that has since CLOSED drops out, which makes lists about it stale
378    /// rather than silently kept.
379    #[must_use]
380    pub fn world(&self) -> escriba_shirube::Anchor {
381        let mut a = escriba_shirube::Anchor::new();
382        for id in self.buffers.ids() {
383            if let Some(b) = self.buffers.get(id) {
384                a = a.on(escriba_shirube::Axis::Text(id, b.text_rev()));
385            }
386        }
387        // Every axis the world can move, ALWAYS present — not only the ones
388        // some producer happens to use today.
389        //
390        // `Anchor::is_fresh` treats an ABSENT axis as stale, deliberately:
391        // unknowable is not unchanged. The consequence, unnoticed until a
392        // recon pass went looking, is that a list anchored on an axis this
393        // function never emits is born PERMANENTLY stale — `]c` would answer
394        // "that list is out of date" forever, and nothing would say why. The
395        // two-axis model was built for git hunks and then only ever fed one
396        // axis.
397        //
398        // Emitting them unconditionally means a producer can anchor on any
399        // axis and get an honest answer. A counter that never moves reads as
400        // "unchanged", which is exactly right for a plane escriba does not
401        // track yet.
402        a = a.on(escriba_shirube::Axis::Index(self.index_rev));
403        // Both session kinds, unconditionally, for the reason above: a
404        // producer anchoring on either must get an honest answer rather than
405        // permanent staleness. They are separate axes because they move
406        // independently — a picker closing must not invalidate diagnostics.
407        a = a.on(escriba_shirube::Axis::Session(
408            escriba_shirube::SessionKind::Lsp,
409            self.lsp_gen,
410        ));
411        a.on(escriba_shirube::Axis::Session(
412            escriba_shirube::SessionKind::Scan,
413            self.scan_gen,
414        ))
415    }
416
417    /// Where the cursor is, WITH the buffer it is in.
418    ///
419    /// Every jumplist push goes through this. A bare `Position` is what let
420    /// `<C-o>` return to the right line in the wrong file.
421    #[must_use]
422    pub fn spot(&self) -> escriba_core::Spot {
423        escriba_core::Spot::new(self.active, self.cursor())
424    }
425
426    /// Move to a `Spot`, switching buffer if it names another one.
427    ///
428    /// The read half of [`spot`](Self::spot). `<C-o>` and `<C-i>` both land
429    /// here so neither can forget the buffer.
430    fn goto_spot(&mut self, s: escriba_core::Spot) {
431        if s.buffer != self.active && self.buffers.get(s.buffer).is_some() {
432            self.active = s.buffer;
433        }
434        let clamped = self
435            .buffers
436            .get(self.active)
437            .map_or(s.pos, |b| b.clamp(s.pos));
438        self.set_cursor(clamped);
439    }
440
441    /// Advance the git-index generation — every list anchored on
442    /// `Axis::Index` goes stale.
443    ///
444    /// Not called yet; a git layer calls it after a stage/reset. Present so
445    /// the axis is WIRED rather than declared, because an axis nothing can
446    /// move is indistinguishable from an axis that does not exist.
447    pub fn bump_index_rev(&mut self) {
448        self.index_rev = escriba_shirube::IndexRev(self.index_rev.0.wrapping_add(1));
449    }
450
451    /// Advance the language-server generation — a server restarted, so every
452    /// diagnostic it produced describes a conversation that no longer exists.
453    /// See [`bump_index_rev`](Self::bump_index_rev).
454    pub fn bump_lsp_gen(&mut self) {
455        self.lsp_gen = escriba_shirube::SessionGen(self.lsp_gen.0.wrapping_add(1));
456    }
457
458    /// Advance the filesystem-scan generation.
459    ///
460    /// This is what makes a superseded scan's rows stale. A scan runs on its
461    /// own thread and cannot be stopped mid-walk; bumping this means its
462    /// remaining batches are *ignored on arrival*, which is a reply filter, not
463    /// cancellation — the thread keeps going until it notices. Say the weaker
464    /// thing, because the stronger one is not true.
465    ///
466    /// Deliberately separate from [`bump_lsp_gen`](Self::bump_lsp_gen): they
467    /// move for unrelated reasons, and when they shared one axis, closing a
468    /// picker staled every diagnostic in the gutter.
469    pub fn bump_scan_gen(&mut self) {
470        self.scan_gen = escriba_shirube::SessionGen(self.scan_gen.0.wrapping_add(1));
471    }
472
473    /// Install the courier's runners. Called once, by the composition root.
474    pub fn hire(&mut self, crew: escriba_madoguchi::errand::Crew) {
475        self.courier.hire(crew);
476    }
477
478    /// What an errand of this class depends on — the ONE place a courier
479    /// anchor is minted.
480    ///
481    /// A total match, so a new [`Freight`](escriba_madoguchi::errand::Freight)
482    /// variant does not compile until somebody decides what makes its results
483    /// stale. That is the point: the failure this prevents is not a wrong
484    /// answer, it is an errand class shipping with no freshness rule at all and
485    /// nobody noticing, because "no rule" reads at runtime as "always fresh".
486    ///
487    /// The return type forbids the empty anchor by construction — see
488    /// [`NonEmptyAnchor`](escriba_shirube::NonEmptyAnchor).
489    fn seal(
490        &self,
491        freight: &escriba_madoguchi::errand::Freight,
492    ) -> escriba_shirube::NonEmptyAnchor {
493        use escriba_madoguchi::errand::Freight;
494        use escriba_shirube::{Axis, NonEmptyAnchor, SessionKind};
495        match freight {
496            // A scan reads the filesystem, which no axis tracks, so text
497            // revisions are irrelevant to it — anchoring one on the buffers
498            // would make it die on the next keystroke for no reason. What DOES
499            // supersede it is the surface it feeds opening or closing, which is
500            // exactly what `scan_gen` counts.
501            Freight::Scan { .. } => {
502                NonEmptyAnchor::on(Axis::Session(SessionKind::Scan, self.scan_gen))
503            }
504            // Diagnostics describe ONE buffer at one revision, from one server
505            // session. Narrow on purpose: anchoring on the whole world would
506            // mean an edit in an unrelated buffer discards them.
507            Freight::Diagnostics { buffer, .. } => {
508                let rev = self.buffers.get(*buffer).map_or_else(
509                    escriba_buffer::TextRev::default,
510                    escriba_buffer::Buffer::text_rev,
511                );
512                NonEmptyAnchor::on(Axis::Text(*buffer, rev))
513                    .and(Axis::Session(SessionKind::Lsp, self.lsp_gen))
514            }
515            // A formatter reply REWRITES text. It must be judged against the
516            // revision it read and nothing else — the whole hazard is applying
517            // one to a buffer the operator kept typing into.
518            Freight::Format { path, .. } => match self.buffers.find_by_path(path) {
519                Some(id) => {
520                    let rev = self.buffers.get(id).map_or_else(
521                        escriba_buffer::TextRev::default,
522                        escriba_buffer::Buffer::text_rev,
523                    );
524                    NonEmptyAnchor::on(Axis::Text(id, rev))
525                }
526                // No open buffer for that path: seal on the LSP session so the
527                // reply is judged against SOMETHING. Never an empty anchor —
528                // that would be fresh forever, which is the whole hazard.
529                None => NonEmptyAnchor::on(Axis::Session(SessionKind::Lsp, self.lsp_gen)),
530            },
531        }
532    }
533
534    /// How many courier replies one tick may apply.
535    ///
536    /// Bounded so a chatty runner cannot hold a frame open. The remainder is
537    /// not dropped — it lands on the next tick.
538    const DELIVER_BUDGET: usize = 64;
539
540    /// Apply whatever the courier has delivered since the last tick.
541    ///
542    /// Must run BEFORE input translation: a redraw event maps to
543    /// `InputOutcome::None`, so a drain hung off the input path would never see
544    /// a tick that carried no keystroke — which is every tick during a scan.
545    pub fn deliver(&mut self) {
546        let slips = self.courier.drain(Self::DELIVER_BUDGET);
547        if slips.is_empty() {
548            return;
549        }
550        for slip in slips {
551            self.honour_one(slip);
552        }
553        // Something landed, so the screen is out of date.
554        self.bump_gen();
555    }
556
557    /// Move the cursor to the next/previous finding in `list`.
558    ///
559    /// Reports the wrap, because `n`/`N` do and a reader losing their place
560    /// in a long file is the same problem either way.
561    fn walk_list(&mut self, list: &str, forward: bool) {
562        let world = self.world();
563        let Some(result) = self.results.get(list) else {
564            let mut m = String::from("no list named ");
565            m.push_str(list);
566            self.messages.push(m);
567            return;
568        };
569        if result.is_stale(&world) {
570            self.messages
571                .push("that list is out of date — run it again".to_string());
572            return;
573        }
574        let here = (Some(self.active), self.cursor().line);
575        let Some(found) = result.step(&world, here, forward, escriba_shirube::Bound::Exclusive)
576        else {
577            let mut m = String::from("no entries in ");
578            m.push_str(list);
579            self.messages.push(m);
580            return;
581        };
582        let site = found.site.clone();
583        let msg = found.message.clone();
584        self.jump_to_site(&site);
585        self.messages.push(msg);
586    }
587
588    /// Move the cursor to a located finding's SITE — the one operation that
589    /// cannot drop the buffer half of a location.
590    ///
591    /// A `Site` is `(buffer, range)`. Every jumper before this re-derived the
592    /// move itself and clamped against `self.active`, so a finding in another
593    /// file landed on the right LINE in the WRONG file. `on_line` and
594    /// `worst_on_line` already filter by buffer, so the gutter and the walker
595    /// disagreed — latent only because the first producer scanned one buffer.
596    ///
597    /// Every future producer (diagnostics, hunks, grep hits, test failures)
598    /// is cross-file by nature, which is why this is a shared operation
599    /// rather than a fix at the one call site that has it wrong today.
600    ///
601    /// Always a FAR jump: it pushes the jumplist, so `<C-o>` returns from a
602    /// `]t` exactly as it returns from an `n`.
603    pub fn jump_to_site(&mut self, site: &escriba_shirube::Site) {
604        self.jumps.push(self.spot());
605        // Switch buffers FIRST — clamping against the wrong buffer is how the
606        // position gets silently mangled before anyone can notice.
607        if let Some(target) = site.buffer {
608            if target != self.active && self.buffers.get(target).is_some() {
609                self.active = target;
610                self.refollow_cursor();
611            }
612        }
613        let to = site.range.start;
614        let clamped = self.buffers.get(self.active).map_or(to, |b| b.clamp(to));
615        self.set_cursor(clamped);
616    }
617
618    /// Close a buffer, keeping "there is always an active buffer" true.
619    ///
620    /// The invariant is the whole reason this is not just
621    /// `self.buffers.close(id)`. `EditorState::active` is a `BufferId`, not
622    /// an `Option`, so a dangling active is not a degraded state — it is a
623    /// state where every read of the active buffer returns `None` and the
624    /// editor renders `<no buffer>` forever. Closing the last buffer opens a
625    /// scratch rather than emptying the set, which is what vim's `:bd` does
626    /// and what the type demands.
627    fn close_buffer(&mut self, id: BufferId) {
628        if self.buffers.close(id).is_none() {
629            self.messages.push("no such buffer".to_string());
630            return;
631        }
632        if self.active != id {
633            return;
634        }
635        // The active buffer went. Prefer the next one by id so repeated
636        // closes walk forward predictably rather than jumping around.
637        let next = self.buffers.ids().into_iter().find(|b| *b > id);
638        self.active = match next.or_else(|| self.buffers.ids().into_iter().next_back()) {
639            Some(b) => b,
640            None => self.buffers.scratch(""),
641        };
642        self.set_cursor(Position::ZERO);
643        if let Some(w) = self.layout.active_window_mut() {
644            w.buffer_id = self.active;
645        }
646    }
647
648    /// Move to the next or previous buffer, wrapping.
649    fn cycle_buffer(&mut self, forward: bool) {
650        let ids = self.buffers.ids();
651        if ids.len() < 2 {
652            self.messages.push("only one buffer".to_string());
653            return;
654        }
655        let at = ids.iter().position(|b| *b == self.active).unwrap_or(0);
656        let next = if forward {
657            (at + 1) % ids.len()
658        } else {
659            (at + ids.len() - 1) % ids.len()
660        };
661        self.active = ids[next];
662        self.set_cursor(Position::ZERO);
663        if let Some(w) = self.layout.active_window_mut() {
664            w.buffer_id = self.active;
665        }
666    }
667
668    /// Re-clamp the cursor and re-contain the viewport after a buffer
669    /// mutation.
670    ///
671    /// An undo can SHRINK the buffer under a cursor that was legal a moment
672    /// ago, leaving it out of bounds and its viewport scrolled past the end.
673    /// The Action executor has always done this (`self.set_cursor(self.cursor())`
674    /// after undo/redo/save); the M1 interpreter did NOT, so `u` re-followed
675    /// and `:undo` did not — two implementations of one operation, already
676    /// drifted within one milestone of being written. Naming it once is the
677    /// fix; lowering the Action arms onto the same slips is what keeps it
678    /// fixed.
679    fn refollow(&mut self) {
680        self.set_cursor(self.cursor());
681    }
682
683    /// Apply one slip and record what it damaged.
684    ///
685    /// The bookkeeping wrapper. The Action executor calls
686    /// [`honour_one`](Self::honour_one) directly because it does its own,
687    /// wider bookkeeping (the dot register, the S3 damage seal) around a
688    /// whole action.
689    fn honour(&mut self, slip: Negai) {
690        let touches_text = slip.touches_text();
691        self.honour_one(slip);
692        self.damage = self.damage.join(if touches_text {
693            Damage::Full
694        } else {
695            Damage::Viewport
696        });
697        self.bump_gen();
698    }
699
700    /// Apply one slip. THE single implementation of every mutation a slip
701    /// can ask for.
702    ///
703    /// Total over `Negai`: a new request variant is a compile error here
704    /// rather than a request silently ignored — the same failure Phase 0
705    /// removed one layer up.
706    fn honour_one(&mut self, slip: Negai) {
707        match slip {
708            Negai::Edit { buffer, edit } => {
709                if let Some(b) = self.buffers.get_mut(buffer) {
710                    let _ = b.apply(&edit);
711                }
712                self.refollow();
713            }
714            Negai::SetCursor { buffer, to } => {
715                // Clamping is the interpreter's job, exactly so that no
716                // handler has to re-implement it and get it wrong.
717                let clamped = self.buffers.get(buffer).map_or(to, |b| b.clamp(to));
718                self.set_cursor(clamped);
719            }
720            Negai::EnterMode(m) => self.modal.enter(m),
721            Negai::OpenPicker(source) => self.open_picker(source),
722            Negai::SplitWindow { stacked } => {
723                let axis = if stacked {
724                    escriba_ui::shikiri::Axis::Stacked
725                } else {
726                    escriba_ui::shikiri::Axis::SideBySide
727                };
728                self.layout.split_active(axis);
729                // The new pane is narrower/shorter than the old one, so the
730                // cursor can now be outside it. Every face re-reports its
731                // frame on the next draw, but the invariant must hold NOW —
732                // an operator who splits and immediately types should not be
733                // editing off-screen.
734                self.refollow_cursor();
735                self.damage = self.damage.join(Damage::Viewport);
736            }
737            Negai::CloseWindow => {
738                let id = self.layout.active();
739                if self.layout.close(id) {
740                    self.refollow_cursor();
741                    self.damage = self.damage.join(Damage::Viewport);
742                } else {
743                    // vim's E444, and the same refusal: the last window is
744                    // the editor. Closing it would mean "quit", which is a
745                    // different verb the operator did not type.
746                    self.messages
747                        .push("E444: Cannot close last window".to_string());
748                }
749            }
750            Negai::FocusDir { dx, dy } => {
751                use escriba_ui::Dir;
752                let dir = match (dx, dy) {
753                    (d, _) if d < 0 => Dir::Left,
754                    (d, _) if d > 0 => Dir::Right,
755                    (_, d) if d < 0 => Dir::Up,
756                    _ => Dir::Down,
757                };
758                if let Some(id) = self.layout.neighbour(dir) {
759                    self.layout.focus(id);
760                    // The window we moved to has its OWN buffer; the editor's
761                    // active buffer follows focus, or the next keystroke
762                    // would edit the file we just navigated away from.
763                    if let Some(w) = self.layout.active_window() {
764                        self.active = w.buffer_id;
765                    }
766                    self.refollow_cursor();
767                    self.damage = self.damage.join(Damage::Viewport);
768                }
769                // No neighbour is not an error — it is the edge of the
770                // layout, and vim says nothing there either.
771            }
772            Negai::GrepProject { pattern } => self.grep_project(&pattern),
773            Negai::CycleBuffer { forward } => self.cycle_buffer(forward),
774            Negai::FocusBuffer(id) => {
775                if self.buffers.get(id).is_some() {
776                    self.active = id;
777                }
778            }
779            Negai::OpenPath(path) => match self.buffers.open(&path) {
780                Ok(id) => self.active = id,
781                Err(e) => self.messages.push(e.to_string()),
782            },
783            Negai::CloseBuffer(id) => self.close_buffer(id),
784            Negai::Save { buffer } => {
785                if let Some(b) = self.buffers.get_mut(buffer) {
786                    if let Err(e) = b.save() {
787                        self.messages.push(e.to_string());
788                    }
789                }
790                self.refollow();
791            }
792            Negai::Undo { buffer } => {
793                if let Some(b) = self.buffers.get_mut(buffer) {
794                    let _ = b.undo();
795                }
796                self.refollow();
797            }
798            Negai::Redo { buffer } => {
799                if let Some(b) = self.buffers.get_mut(buffer) {
800                    let _ = b.redo();
801                }
802                self.refollow();
803            }
804            Negai::Yank { text, .. } => self.register = Some(text),
805            Negai::ClearSearchHighlight => self.search.clear_highlight(),
806            Negai::SetOption { name, value } => {
807                self.options.insert(name, value);
808            }
809            Negai::InsertText(text) => self.insert_text(&text),
810            Negai::RunCommand { name, args } => self.run_command(&name, &args),
811            Negai::PublishFindings { list, findings } => {
812                let world = self.world();
813                self.results
814                    .publish(list, escriba_shirube::ResultList::new(findings, world));
815            }
816            // A reply from off the tick. Honour it only if the world it was
817            // computed against still holds.
818            //
819            // The drop is silent BY DESIGN, and this is the one place in the
820            // slip vocabulary where silence is right: a stale reply is not a
821            // failure anyone can act on. The operator kept typing, which is
822            // the correct thing to have done, and telling them "a diagnostic
823            // you never asked for was discarded" is noise. The producer
824            // re-runs against the new world; that is the whole contract.
825            Negai::ErrandReply { anchor, then } => {
826                if anchor.is_fresh(&self.world()) {
827                    match *then {
828                        // The reply's OWN anchor becomes the list's seal.
829                        //
830                        // Passing the gate and then re-sealing at `world()` —
831                        // which is what the direct `PublishFindings` arm does,
832                        // correctly, for an on-tick producer — is wrong for a
833                        // reply that crossed a thread. It widens a narrow claim
834                        // into a broad one: findings that depended on one
835                        // buffer would be stored as depending on every open
836                        // buffer, so an edit anywhere kills them. And it
837                        // upgrades an unearned claim into a durable one.
838                        //
839                        // Special-cased on this one payload because
840                        // `ErrandReply` WRAPS a slip rather than putting an
841                        // anchor field on `PublishFindings`; adding one there
842                        // now would reopen exactly the hole the wrapper closed.
843                        Negai::PublishFindings { list, findings } => {
844                            self.results.publish(
845                                list.clone(),
846                                escriba_shirube::ResultList::new(findings, anchor),
847                            );
848                            self.refresh_projected_picker(&list);
849                        }
850                        other => self.honour_one(other),
851                    }
852                }
853            }
854            Negai::WalkList { list, forward } => self.walk_list(&list, forward),
855            Negai::Message(m) => self.messages.push(m),
856            Negai::Quit => self.quit_requested = true,
857            // Hand the freight to the courier, sealed against the world it
858            // was dispatched in.
859            //
860            // The seal happens HERE and nowhere else. A handler named a class
861            // of work; it did not — and could not — say what world that work
862            // depends on, because a handler holds a read-only snapshot. If the
863            // slip carried an anchor, any handler could mint one depending on
864            // nothing, which is fresh forever, and the freshness gate would
865            // stop meaning anything.
866            Negai::Errand(freight) => {
867                let anchor = self.seal(&freight);
868                self.courier.send(*freight, anchor);
869            }
870            // Still unwired: the AwaitKey resume (M3). Announced, never
871            // silently dropped — a slip that vanishes is the class Phase 0
872            // sealed.
873            Negai::AwaitKey { .. } => {
874                self.messages
875                    .push("deferred work is not wired yet".to_string());
876            }
877        }
878    }
879}
880
881/// Outcome of feeding one key to the multi-key pending-stroke loop.
882enum SeqStep {
883    /// Key consumed into an in-progress sequence; wait for the next.
884    Pending,
885    /// A full bound sequence resolved — run this action.
886    Resolved(Action),
887    /// Key is not part of any sequence; hand it to single-key dispatch.
888    Passthrough,
889}
890
891/// Keys whose HELD repeat is a viewport storm, and which the repeat gate
892/// therefore exists to debounce.
893///
894/// This is an ALLOW-LIST, and it used to be the complement — an exception list
895/// of "discrete" keys that grew three times (`n`/`N`/`*`/`#`, then `.`/`u`/
896/// `<C-r>`, then `/`/`?`/`:`), each time because a key had been silently
897/// swallowed and someone noticed. The third growth is the signal that the
898/// default was backwards: almost every key in a modal editor is a discrete,
899/// deliberate press, and only a handful are ones you HOLD.
900///
901/// Inverting it makes the failure mode safe. Forgetting to list a key here now
902/// means it is ungated — one extra keypress honoured — instead of silently
903/// dropped, and a dropped key is indistinguishable from a dead one.
904///
905/// Measured cost of the old direction: `/foo<CR>` then `/<CR>` (vim's
906/// reuse-the-previous-pattern) lost the second `/` outright, because the gate
907/// is keyed by KEY and the two presses fell inside one debounce window.
908const fn is_repeat_storm_candidate(key: &Key) -> bool {
909    matches!(
910        key,
911        // The four navigation keys a user actually holds down. `h`/`l` and
912        // `j`/`k` flood the motion path and thrash the viewport; everything
913        // else is pressed once and meant once.
914        Key::Char('h')
915            | Key::Char('j')
916            | Key::Char('k')
917            | Key::Char('l')
918            | Key::Left
919            | Key::Right
920            | Key::Up
921            | Key::Down
922    )
923}
924
925/// Turn a command failure into the sentence an operator should read.
926///
927/// The two failures mean genuinely different things and must not be reported
928/// the same way:
929///
930/// - `:flurb` — the operator typed a name that does not exist. "command not
931///   found" is exactly right; it says *you* made a typo.
932/// - `<leader>ff` bound to `picker.files` — escriba's OWN shipped config
933///   declares this, `--list-rc` counts it, and it is not built yet. Telling
934///   the operator "command not found" blames them for a gap we shipped.
935///
936/// The discriminator is the dotted form. `:action` takes action SYMBOLS
937/// (`picker.files`), never command names — that boundary is already pinned by
938/// `action_naming_a_command_is_inert_not_recursive` in escriba-command. So a
939/// dotted name that reached dispatch and resolved to nothing is a declared
940/// capability with no implementation, which is precisely what the 85 entries
941/// in `escriba/tests/action_resolution.rs` are.
942fn describe_command_failure(name: &str, e: &escriba_command::CommandError) -> String {
943    use escriba_command::CommandError as E;
944    match e {
945        // Already the right words — the registry knew it was declared.
946        E::Unhandled(_) => e.to_string(),
947        E::NotFound(n) if n.contains('.') => {
948            let mut m = String::with_capacity(n.len() + 48);
949            m.push('`');
950            m.push_str(n);
951            m.push_str("` is declared but not implemented yet");
952            m
953        }
954        _ => {
955            let _ = name;
956            e.to_string()
957        }
958    }
959}
960
961/// What committing the open search prompt did.
962///
963/// The two commit paths — bare `/` and operated `d/` — used to own private
964/// copies of the whole sequence (read origin+skip, `accept`, three-arm
965/// match, `commit_step_skipping`), and they drifted: the operated one
966/// never reported the wrap, so `d/foo<CR>` that wrapped the file was
967/// silent where `/foo<CR>` printed "search hit BOTTOM, continuing at TOP".
968///
969/// Total, and matched exhaustively at BOTH call sites, so a new outcome is
970/// a compile error in two places rather than a case one path quietly
971/// forgets. It does not make divergence impossible — the two paths
972/// genuinely differ at the landing step — it makes FORGETTING A CASE
973/// impossible, which is the failure that actually happened.
974enum CommitOutcome {
975    /// The prompt committed and a match was found.
976    Landed {
977        origin: usize,
978        step: escriba_search::Step,
979    },
980    /// Committed, but nothing matched. E486 already reported.
981    NotFound,
982    /// Nothing typed and no previous pattern. E35 already reported.
983    NoPrevious,
984    /// No prompt was open.
985    NoPrompt,
986}
987
988/// A replayable text change.
989#[derive(Debug, Clone)]
990struct LastChange {
991    /// The action that began the change.
992    action: Action,
993    /// How many times it ran.
994    count: u32,
995    /// Characters typed while the change held Insert mode open.
996    inserted: String,
997}
998
999impl EditorState {
1000    /// Build a fresh editor with one buffer (scratch or file-backed).
1001    pub fn new_with_buffer(initial: BufferSet, active: BufferId) -> Self {
1002        let window = Window {
1003            id: WindowId(1),
1004            buffer_id: active,
1005            viewport: Viewport {
1006                top_line: 0,
1007                left_column: 0,
1008                visible_lines: 40,
1009                visible_columns: 160,
1010            },
1011        };
1012        Self {
1013            buffers: initial,
1014            modal: ModalState::new(),
1015            search: SearchState::new(escriba_search::CaseMode::Smart),
1016            search_at: None,
1017            last_change: None,
1018            recording_insert: false,
1019            jumps: JumpList::new(),
1020            keymap: Keymap::default_vim(),
1021            commands: CommandRegistry::default_set(),
1022            layout: Layout::single(window),
1023            active,
1024            cursors: Cursors::single(Position::ZERO),
1025            quit_requested: false,
1026            register: None,
1027            op_pending: zenmai::Stateful::new(OpState::Resting),
1028            pending_object: None,
1029            messages: Vec::new(),
1030            options: HashMap::new(),
1031            lisp_vm: None,
1032            pending_keys: Vec::new(),
1033            repeat_gate: KeyRepeatGate::new(),
1034            plugin_host: PluginHost::default(),
1035            edit_gen: EditGen::default(),
1036            damage: Damage::None,
1037            // The FLEET default until an rc says otherwise — never a
1038            // hand-written theme name, so a fleet re-point lands for free.
1039            dispatch_depth: 0,
1040            filetypes: escriba_core::FiletypeTable::new(),
1041            results: escriba_shirube::ListRegistry::new(),
1042            picker: None,
1043            index_rev: escriba_shirube::IndexRev::default(),
1044            lsp_gen: escriba_shirube::SessionGen::default(),
1045            scan_gen: escriba_shirube::SessionGen::default(),
1046            courier: courier::Courier::inert(),
1047            picker_projects: None,
1048            theme: FleetTheme::prescribed_default(),
1049            chrome: ChromePalette::prescribed(),
1050            splash: None,
1051        }
1052    }
1053
1054    /// The theme this editor is set to.
1055    #[must_use]
1056    pub const fn theme(&self) -> FleetTheme {
1057        self.theme
1058    }
1059
1060    /// The colours every face paints with — read once per frame.
1061    #[must_use]
1062    pub const fn chrome(&self) -> ChromePalette {
1063        self.chrome
1064    }
1065
1066    /// Point the editor at a theme. The wiring that makes
1067    /// `(deftheme :preset …)` real.
1068    ///
1069    /// Bumps the refresh generation, because a theme change repaints
1070    /// everything: the GPU face caches its shaped buffer against that
1071    /// generation and would otherwise keep the old colours until an
1072    /// unrelated edit happened to invalidate it.
1073    pub fn set_theme(&mut self, theme: FleetTheme) {
1074        if self.theme == theme {
1075            return;
1076        }
1077        self.theme = theme;
1078        self.chrome = ChromePalette::for_theme(theme);
1079        self.damage = self.damage.join(Damage::Viewport);
1080        self.bump_gen();
1081    }
1082
1083    /// The start screen, if one is up. Renderers paint this INSTEAD of the
1084    /// buffer pane; `None` is the ordinary editor.
1085    #[must_use]
1086    pub fn splash(&self) -> Option<&Splash> {
1087        self.splash.as_ref()
1088    }
1089
1090    /// Raise the start screen. The binary calls this at boot when no file
1091    /// was named; an empty splash is refused so a face never has to render
1092    /// a blank screen over a perfectly good buffer.
1093    pub fn set_splash(&mut self, splash: Splash) {
1094        if splash.is_empty() {
1095            return;
1096        }
1097        self.splash = Some(splash);
1098        self.damage = self.damage.join(Damage::Viewport);
1099        self.bump_gen();
1100    }
1101
1102    /// Take the start screen down. Idempotent; bumps the refresh generation
1103    /// only when something actually changed, so dismissing twice does not
1104    /// cost a repaint.
1105    pub fn dismiss_splash(&mut self) {
1106        if self.splash.take().is_some() {
1107            self.damage = self.damage.join(Damage::Viewport);
1108            self.bump_gen();
1109        }
1110    }
1111
1112    /// Offer `key` to the start screen.
1113    ///
1114    /// A menu key runs its entry; ANY other key simply takes the screen
1115    /// down and is then handled normally — so the first thing an operator
1116    /// types is never swallowed.
1117    /// The open picker, for a face to paint.
1118    #[must_use]
1119    pub fn picker(&self) -> Option<&escriba_ui::picker::Picker> {
1120        self.picker.as_ref()
1121    }
1122
1123    /// Give an open picker the key.
1124    ///
1125    /// Runs BEFORE the keymap, and before the sequence stepper: while a
1126    /// picker is up it owns every key, including ones it has no meaning for.
1127    /// An overlay that let unknown keys fall through would edit the file
1128    /// behind itself.
1129    /// Close the picker — the SOLE writer of `self.picker = None`.
1130    ///
1131    /// Sole on purpose. Closing has three consequences that must not come
1132    /// apart: the overlay goes, the screen repaints, and any scan feeding that
1133    /// overlay is superseded. Spread across call sites, one of them eventually
1134    /// forgets the third and a dismissed picker springs back open when a late
1135    /// batch arrives.
1136    ///
1137    /// `cancel_all` is asked as well as the generation bumped, but note which
1138    /// one is load-bearing: the bump is what makes late rows *ignored*, and it
1139    /// works whether or not any runner reads its flag. The cancel is a courtesy
1140    /// to a runner that checks.
1141    fn close_picker(&mut self) {
1142        self.picker = None;
1143        self.picker_projects = None;
1144        self.bump_scan_gen();
1145        self.courier.cancel_all();
1146        self.bump_gen();
1147    }
1148
1149    fn consume_picker_key(&mut self, key: &Key) -> escriba_ui::picker::Consumed {
1150        use escriba_ui::picker::Consumed;
1151        let Some(p) = self.picker.as_mut() else {
1152            return Consumed::NotShowing;
1153        };
1154        let outcome = p.on_key(key);
1155        match &outcome {
1156            // BOTH arms close the picker — choosing a row dismisses it just as
1157            // surely as pressing Esc, and an earlier reading of this that only
1158            // considered Esc would have left a scan running after every pick.
1159            Consumed::Dismissed | Consumed::Chose(_) => self.close_picker(),
1160            Consumed::Held => self.bump_gen(),
1161            Consumed::NotShowing => {}
1162        }
1163        outcome
1164    }
1165
1166    /// Lower an accepted pick into the ONE interpreter.
1167    ///
1168    /// The whole reason `Choice` is a closed enum: a new source must decide
1169    /// here, and the compiler says so.
1170    fn honour_choice(&mut self, choice: escriba_ui::picker::Choice) {
1171        use escriba_ui::picker::Choice;
1172        let slip = match choice {
1173            Choice::Buffer(id) => Negai::FocusBuffer(id),
1174            Choice::Command(name) => Negai::RunCommand {
1175                name,
1176                args: Vec::new(),
1177            },
1178            Choice::OpenFile(path) => Negai::OpenPath(path),
1179            Choice::Location { path, line } => {
1180                // Open FIRST, then jump: the buffer may not exist yet, and
1181                // `jump_to_site` needs a BufferId. Two slips, one interpret.
1182                self.interpret(Outcome::did(vec![Negai::OpenPath(path)]));
1183                let site = escriba_shirube::Site::in_buffer(
1184                    self.active,
1185                    escriba_core::Range::new(
1186                        escriba_core::Position::new(line, 0),
1187                        escriba_core::Position::new(line, 1),
1188                    ),
1189                );
1190                self.jump_to_site(&site);
1191                return;
1192            }
1193        };
1194        self.interpret(Outcome::did(vec![slip]));
1195    }
1196
1197    /// How many files a project grep will read, and how many hits it keeps.
1198    ///
1199    /// BOUNDED, and the bound is here rather than hidden, because this is a
1200    /// SYNCHRONOUS scan on the editor's own thread. The interpreter already
1201    /// does synchronous filesystem I/O (`OpenPath`, `Save`), so the posture
1202    /// is not new — but those touch one file and this walks a tree, which is
1203    /// the first one big enough to freeze the editor.
1204    ///
1205    /// GREP NO LONGER USES THIS. The courier carries the scan now, with no
1206    /// ceiling at all, and `GREP_HIT_LIMIT` is gone with it — the bound was
1207    /// a symptom of walking the tree on the thread that draws the screen.
1208    ///
1209    /// It survives for the files and project pickers, which still build
1210    /// their row set synchronously at open. Moving those onto the courier
1211    /// is the same change again and has not been made.
1212    const GREP_FILE_LIMIT: usize = 2_000;
1213
1214    /// Walk the working directory, bounded, returning `(files, truncated)`.
1215    ///
1216    /// ONE walker. grep, files and project each need to enumerate the tree,
1217    /// and three copies of a bounded traversal is three places to get the
1218    /// ceiling, the skip-list, or the truncation report subtly different.
1219    ///
1220    /// Skips dotfiles, `target` and `node_modules`. That is NOT a gitignore
1221    /// implementation and does not pretend to be — a real ignore crate comes
1222    /// with the courier.
1223    fn walk_project(limit: usize) -> (Vec<std::path::PathBuf>, bool) {
1224        Self::walk_from(std::path::Path::new("."), limit)
1225    }
1226
1227    /// The same bounded walk, from an explicit root.
1228    ///
1229    /// `walk_project` is this with `.` — one traversal, two callers, rather
1230    /// than a second copy for "browse from somewhere else".
1231    fn walk_from(root: &std::path::Path, limit: usize) -> (Vec<std::path::PathBuf>, bool) {
1232        let mut out = Vec::new();
1233        let mut truncated = false;
1234        let mut stack = vec![root.to_path_buf()];
1235        while let Some(dir) = stack.pop() {
1236            let Ok(entries) = std::fs::read_dir(&dir) else {
1237                continue;
1238            };
1239            for entry in entries.flatten() {
1240                let name = entry.file_name();
1241                let name = name.to_string_lossy();
1242                if name.starts_with('.') || name == "target" || name == "node_modules" {
1243                    continue;
1244                }
1245                let path = entry.path();
1246                if entry.file_type().is_ok_and(|t| t.is_dir()) {
1247                    stack.push(path);
1248                    continue;
1249                }
1250                if out.len() >= limit {
1251                    truncated = true;
1252                    return (out, truncated);
1253                }
1254                out.push(path);
1255            }
1256        }
1257        (out, truncated)
1258    }
1259
1260    /// Say plainly when a bounded scan stopped short.
1261    ///
1262    /// A truncated list presented as complete is the failure this codebase
1263    /// keeps finding in itself; it does not get to ship one.
1264    fn report_truncation(&mut self, truncated: bool) {
1265        if truncated {
1266            self.messages
1267                .push("scan stopped at the limit — results are INCOMPLETE".to_string());
1268        }
1269    }
1270
1271    /// Scan the working directory for `pattern`, off the editor thread.
1272    ///
1273    /// This used to walk the tree inline, capped at 2,000 files and 500 hits
1274    /// because it ran on the thread that draws the screen — and it reported
1275    /// that truncation, honestly, as INCOMPLETE. Both ceilings are gone with
1276    /// the walk: the courier carries it, and results arrive in batches.
1277    ///
1278    /// The picker opens EMPTY and then projects the findings list. That is why
1279    /// there is no "no matches" message here any more — at dispatch time
1280    /// nothing is known yet, and guessing would mean reporting an empty result
1281    /// before the scan had read a single file.
1282    fn grep_project(&mut self, pattern: &str) {
1283        use escriba_ui::picker::{Picker, Source};
1284        if pattern.is_empty() {
1285            self.messages.push("grep: empty pattern".to_string());
1286            return;
1287        }
1288        // A fresh scan supersedes whatever was running, and clears the list so
1289        // the previous pattern's rows are not shown under the new one.
1290        self.bump_scan_gen();
1291        self.courier.cancel_all();
1292        self.results.clear(crate::scan::LIST);
1293
1294        let freight = escriba_madoguchi::errand::Freight::Scan {
1295            raw: pattern.to_string(),
1296            case: escriba_search::CaseMode::Smart,
1297            root: std::path::PathBuf::from("."),
1298        };
1299        let anchor = self.seal(&freight);
1300        self.courier.send(freight, anchor);
1301
1302        self.picker = Some(Picker::open(Source::Grep, Vec::new()));
1303        self.picker_projects = Some((true, Some(crate::scan::LIST.to_string())));
1304        self.bump_gen();
1305    }
1306
1307    /// Re-list a projecting picker after `published` changed.
1308    ///
1309    /// A picker over a live producer is a VIEW of the registry, not a snapshot
1310    /// taken when it opened — otherwise a scan's later batches would have
1311    /// nowhere to land, since `Picker` has no append.
1312    fn refresh_projected_picker(&mut self, published: &str) {
1313        let Some((workspace, ref list)) = self.picker_projects else {
1314            return;
1315        };
1316        // Only the list this picker is projecting. A diagnostics publish must
1317        // not redraw a grep picker.
1318        if list.as_deref().is_some_and(|l| l != published) {
1319            return;
1320        }
1321        let items = self.finding_items(workspace, list.as_deref());
1322        if let Some(p) = self.picker.as_mut() {
1323            if p.refresh_items(items) {
1324                self.bump_gen();
1325            }
1326        }
1327    }
1328
1329    /// Where accepting a finding should take the operator.
1330    ///
1331    /// Returns `None` for a finding whose site names neither a path nor a
1332    /// live buffer — that is a finding about nowhere, and offering it would
1333    /// give the operator a row that does nothing when pressed.
1334    fn finding_choice(&self, f: &escriba_shirube::Finding) -> Option<escriba_ui::picker::Choice> {
1335        use escriba_ui::picker::Choice;
1336        let line = f.site.range.start.line;
1337        if let Some(p) = &f.site.path {
1338            return Some(Choice::Location {
1339                path: p.clone(),
1340                line,
1341            });
1342        }
1343        let id = f.site.buffer?;
1344        let b = self.buffers.get(id)?;
1345        // A buffer WITH a path becomes a Location, so the line survives. A
1346        // scratch buffer has no path to name, so the best available answer
1347        // is the buffer itself — and the line is lost. Stated rather than
1348        // hidden: a `Choice` that carried a BufferId AND a line would be
1349        // the fix, and it belongs with the picker, not here.
1350        b.path.as_ref().map_or(Some(Choice::Buffer(id)), |p| {
1351            Some(Choice::Location {
1352                path: p.clone(),
1353                line,
1354            })
1355        })
1356    }
1357
1358    /// How a finding's location reads in a list row.
1359    fn finding_label(&self, f: &escriba_shirube::Finding) -> String {
1360        if let Some(p) = &f.site.path {
1361            return p.to_string_lossy().into_owned();
1362        }
1363        f.site
1364            .buffer
1365            .and_then(|id| self.buffers.get(id))
1366            .and_then(|b| b.path.as_ref())
1367            .map_or_else(
1368                || String::from("[scratch]"),
1369                |p| p.to_string_lossy().into_owned(),
1370            )
1371    }
1372
1373    /// Picker rows for every file under `root`.
1374    ///
1375    /// `picker.files` and `files.open-parent` differ only in the root, so
1376    /// they share this rather than carrying two copies of the same body —
1377    /// which is what they did for one commit, and what the line-count lint
1378    /// correctly complained about.
1379    fn file_items(
1380        &mut self,
1381        root: &std::path::Path,
1382    ) -> Vec<escriba_ui::picker::PickerItem<escriba_ui::picker::Choice>> {
1383        use escriba_ui::picker::{Choice, PickerItem};
1384        let (files, truncated) = Self::walk_from(root, Self::GREP_FILE_LIMIT);
1385        self.report_truncation(truncated);
1386        files
1387            .into_iter()
1388            .map(|p| {
1389                let label = p.to_string_lossy().into_owned();
1390                PickerItem::new(Choice::OpenFile(p), label)
1391            })
1392            .collect()
1393    }
1394
1395    /// Picker rows for the located findings the `trouble.*` verbs show.
1396    ///
1397    /// Freshness is asked of the registry, not assumed: `fresh` filters
1398    /// against the CURRENT world, so a list anchored to a revision the
1399    /// buffer has moved past contributes nothing rather than offering a
1400    /// line that has since shifted.
1401    fn finding_items(
1402        &self,
1403        workspace: bool,
1404        only: Option<&str>,
1405    ) -> Vec<escriba_ui::picker::PickerItem<escriba_ui::picker::Choice>> {
1406        use escriba_ui::picker::PickerItem;
1407        let world = self.world();
1408        let active = Some(self.active);
1409        let mut items = Vec::new();
1410        // `None` means every list — the trouble.* behaviour, unchanged.
1411        // `Some(n)` narrows to one producer, so a grep picker does not also
1412        // render LSP diagnostics and the marker scan.
1413        let names: Vec<&str> = only.map_or_else(|| self.results.names(), |n| vec![n]);
1414        for name in names {
1415            let Some(list) = self.results.get(name) else {
1416                continue;
1417            };
1418            for f in list.fresh(&world) {
1419                // `trouble.document` narrows to the buffer in front of the
1420                // operator. A finding that names only a path is
1421                // workspace-scoped by construction — it has no buffer to be
1422                // "this" one.
1423                if !workspace && f.site.buffer != active {
1424                    continue;
1425                }
1426                let Some(choice) = self.finding_choice(f) else {
1427                    continue;
1428                };
1429                let line = f.site.range.start.line;
1430                let mut label = String::with_capacity(64);
1431                label.push_str(f.severity.label());
1432                label.push_str("  ");
1433                label.push_str(&self.finding_label(f));
1434                label.push(':');
1435                label.push_str(&(line + 1).to_string());
1436                label.push_str("  ");
1437                label.push_str(&f.message);
1438                items.push(PickerItem::new(choice, label));
1439            }
1440        }
1441        items
1442    }
1443
1444    /// Build and open a picker over `source`.
1445    fn open_picker(&mut self, source: escriba_madoguchi::PickerSource) {
1446        use escriba_ui::picker::{Choice, Picker, PickerItem, Source};
1447        let (src, items) = match source {
1448            escriba_madoguchi::PickerSource::Buffers => (
1449                Source::Buffers,
1450                self.buffers
1451                    .ids()
1452                    .into_iter()
1453                    .filter_map(|id| {
1454                        let b = self.buffers.get(id)?;
1455                        let label = b.path.as_ref().map_or_else(
1456                            || String::from("[scratch]"),
1457                            |p| p.to_string_lossy().into_owned(),
1458                        );
1459                        Some(PickerItem::new(Choice::Buffer(id), label))
1460                    })
1461                    .collect::<Vec<_>>(),
1462            ),
1463            escriba_madoguchi::PickerSource::Help => (
1464                Source::Help,
1465                self.keymap
1466                    .entries_sorted()
1467                    .into_iter()
1468                    .map(|(mode, key, b)| {
1469                        // "NORMAL  gd   goto definition" — searchable by key,
1470                        // by mode, or by what it does, because a reader
1471                        // arrives from any of the three.
1472                        let mut label = String::with_capacity(48);
1473                        label.push_str(mode.as_str());
1474                        label.push_str("  ");
1475                        // `{key:?}` because there is no shared key FORMATTER
1476                        // in the fleet — awase owns the chord vocabulary but
1477                        // escriba-keymap's `Key` has no Display. That gap
1478                        // belongs to the keymap consolidation, not here, and
1479                        // inventing a fourth spelling would make it worse.
1480                        label.push_str(&format!("{key:?}"));
1481                        label.push_str("  ");
1482                        label.push_str(&b.description);
1483                        // Accepting runs the binding's action if it names a
1484                        // command; a typed Action has no name to run, so it
1485                        // reports rather than pretending.
1486                        let choice = match &b.action {
1487                            escriba_core::Action::Command { name, .. } => {
1488                                Choice::Command(name.clone())
1489                            }
1490                            other => Choice::Command(format!("{other:?}")),
1491                        };
1492                        PickerItem::new(choice, label)
1493                    })
1494                    .collect::<Vec<_>>(),
1495            ),
1496            escriba_madoguchi::PickerSource::Files => {
1497                (Source::Files, self.file_items(std::path::Path::new(".")))
1498            }
1499            escriba_madoguchi::PickerSource::Project => {
1500                // A project root is a directory carrying a marker. Derived
1501                // from the SAME walk rather than a second traversal — the
1502                // markers are files, so the walker already visited them.
1503                const MARKERS: &[&str] = &[
1504                    "Cargo.toml",
1505                    "flake.nix",
1506                    "package.json",
1507                    "go.mod",
1508                    "pyproject.toml",
1509                ];
1510                let (files, truncated) = Self::walk_project(Self::GREP_FILE_LIMIT);
1511                self.report_truncation(truncated);
1512                let mut roots: Vec<std::path::PathBuf> = files
1513                    .into_iter()
1514                    .filter(|p| {
1515                        p.file_name()
1516                            .is_some_and(|n| MARKERS.contains(&n.to_string_lossy().as_ref()))
1517                    })
1518                    .filter_map(|p| p.parent().map(std::path::Path::to_path_buf))
1519                    .collect();
1520                roots.sort();
1521                roots.dedup();
1522                (
1523                    Source::Project,
1524                    roots
1525                        .into_iter()
1526                        .map(|p| {
1527                            let label = p.to_string_lossy().into_owned();
1528                            PickerItem::new(Choice::OpenFile(p), label)
1529                        })
1530                        .collect::<Vec<_>>(),
1531                )
1532            }
1533            escriba_madoguchi::PickerSource::Commands => (
1534                Source::Commands,
1535                self.commands
1536                    .names()
1537                    .into_iter()
1538                    .map(|n| PickerItem::new(Choice::Command(n.to_string()), n.to_string()))
1539                    .collect::<Vec<_>>(),
1540            ),
1541            escriba_madoguchi::PickerSource::FilesUnder(root) => {
1542                (Source::Files, self.file_items(&root))
1543            }
1544            escriba_madoguchi::PickerSource::Findings { workspace } => {
1545                (Source::Findings, self.finding_items(workspace, None))
1546            }
1547        };
1548        if items.is_empty() {
1549            self.messages.push("nothing to pick from".to_string());
1550            return;
1551        }
1552        self.picker = Some(Picker::open(src, items));
1553        self.bump_gen();
1554    }
1555
1556    /// Read one key as operator-pending object selection.
1557    ///
1558    /// Returns `None` when the key is nothing to do with objects, so the
1559    /// ordinary path runs untouched.
1560    fn consume_object_key(&mut self, key: Key) -> Option<ObjectKey> {
1561        use escriba_core::TextObject as O;
1562        let Key::Char(c) = key else {
1563            // Esc (or anything non-printable) abandons a half-typed object
1564            // rather than leaving the editor silently armed.
1565            if self.pending_object.take().is_some() {
1566                self.op_pending
1567                    .dispatch((Action::ChangeMode(Mode::Normal), 1));
1568                return Some(ObjectKey::Consumed);
1569            }
1570            return None;
1571        };
1572
1573        // Second key: it names the object.
1574        if let Some(around) = self.pending_object.take() {
1575            let object = match c {
1576                'w' => Some(O::Word { around }),
1577                // vim's `b` and `B` aliases for the bracket pairs, plus the
1578                // brackets themselves in both directions.
1579                '(' | ')' | 'b' => Some(O::Delimited {
1580                    open: '(',
1581                    close: ')',
1582                    around,
1583                }),
1584                '{' | '}' | 'B' => Some(O::Delimited {
1585                    open: '{',
1586                    close: '}',
1587                    around,
1588                }),
1589                '[' | ']' => Some(O::Delimited {
1590                    open: '[',
1591                    close: ']',
1592                    around,
1593                }),
1594                '<' | '>' => Some(O::Delimited {
1595                    open: '<',
1596                    close: '>',
1597                    around,
1598                }),
1599                // Quotes: `open == close`, which is what tells the resolver
1600                // not to count nesting.
1601                '"' => Some(O::Delimited {
1602                    open: '"',
1603                    close: '"',
1604                    around,
1605                }),
1606                '\'' => Some(O::Delimited {
1607                    open: '\'',
1608                    close: '\'',
1609                    around,
1610                }),
1611                '`' => Some(O::Delimited {
1612                    open: '`',
1613                    close: '`',
1614                    around,
1615                }),
1616                _ => None,
1617            };
1618            let OpState::Awaiting { op, count } = *self.op_pending.state() else {
1619                return Some(ObjectKey::Consumed);
1620            };
1621            // Disarm either way: an unknown object key cancels the operator,
1622            // it does not leave it armed for the next unrelated keystroke.
1623            self.op_pending
1624                .dispatch((Action::ChangeMode(Mode::Normal), 1));
1625            let Some(object) = object else {
1626                return Some(ObjectKey::Consumed);
1627            };
1628            let composed = Action::ApplyOperatorObject { op, object };
1629            // `2diw` applies the object twice. The caller runs it once, so
1630            // the extra repeats happen here.
1631            for _ in 1..count {
1632                self.apply(&composed);
1633            }
1634            return Some(ObjectKey::Compose(composed));
1635        }
1636
1637        // First key: `i` or `a` while an operator waits.
1638        if matches!(c, 'i' | 'a') && matches!(self.op_pending.state(), OpState::Awaiting { .. }) {
1639            self.pending_object = Some(c == 'a');
1640            return Some(ObjectKey::Consumed);
1641        }
1642        None
1643    }
1644
1645    fn consume_splash_key(&mut self, key: &Key) -> SplashKey {
1646        let Some(splash) = self.splash.as_ref() else {
1647            return SplashKey::NotShowing;
1648        };
1649        let chosen = match key {
1650            Key::Char(c) => splash.entry_for(*c).map(|e| e.action.clone()),
1651            _ => None,
1652        };
1653        self.dismiss_splash();
1654        chosen.map_or(SplashKey::Dismissed, SplashKey::Ran)
1655    }
1656
1657    /// The current refresh generation. A renderer caches its products against
1658    /// this; equality is the freshness test (an unchanged generation ⇒ the
1659    /// last frame is still valid, so skip the re-highlight + re-shape).
1660    #[must_use]
1661    pub fn edit_gen(&self) -> EditGen {
1662        self.edit_gen
1663    }
1664
1665    /// Advance the refresh generation (a mutation happened).
1666    fn bump_gen(&mut self) {
1667        self.edit_gen = self.edit_gen.next();
1668    }
1669
1670    /// The accumulated dirty region (read-only). See [`take_damage`](Self::take_damage).
1671    #[must_use]
1672    pub fn damage(&self) -> Damage {
1673        self.damage
1674    }
1675
1676    /// Drain the accumulated dirty region, resetting to [`Damage::None`]. The
1677    /// renderer calls this once per frame to learn what to repaint, then the
1678    /// accumulator restarts — so damage never double-counts across frames.
1679    pub fn take_damage(&mut self) -> Damage {
1680        std::mem::replace(&mut self.damage, Damage::None)
1681    }
1682
1683    /// The line count of the active buffer (0 if none) — used to compute the
1684    /// [`Damage`] scope of a mutation.
1685    fn active_line_count(&self) -> u32 {
1686        self.buffers
1687            .get(self.active)
1688            .map_or(0, escriba_buffer::Buffer::line_count)
1689    }
1690
1691    /// Register a lazy USER plugin: its escriba entry is deferred until
1692    /// one of its `triggers` fires. Bundled defaults do NOT go through
1693    /// here — they are applied eagerly at boot. Empty `triggers` means
1694    /// the plugin never lazily activates (the binary applies eager
1695    /// plugins directly).
1696    pub fn register_lazy_plugin(
1697        &mut self,
1698        name: impl Into<String>,
1699        triggers: Vec<LazyTrigger>,
1700        entry_src: impl Into<String>,
1701    ) {
1702        self.plugin_host.register(name, triggers, entry_src);
1703    }
1704
1705    /// Apply a plugin entry's escriba-lisp to live state — the same
1706    /// keymap / command / option apply paths a user rc uses. Options are
1707    /// applied before keybinds so a plugin that sets `mapleader` resolves
1708    /// `<leader>` correctly. Returns the count of commands + keybinds it
1709    /// registered (best-effort; a malformed entry is skipped, not fatal).
1710    fn apply_plugin_entry(&mut self, entry_src: &str) -> usize {
1711        let Ok(plan) = escriba_lisp::apply_source(entry_src) else {
1712            return 0;
1713        };
1714        let cmd = escriba_lisp::apply_plan_to_commands(&plan, &mut self.commands);
1715        escriba_lisp::apply_plan_to_options(&plan, &mut self.options);
1716        if let Some(value) = self.options.get("mapleader") {
1717            if let Some(key) = escriba_lisp::parse_leader_key(value) {
1718                self.keymap.set_leader(key);
1719            }
1720        }
1721        let km = escriba_lisp::apply_plan_to_keymap(&plan, &mut self.keymap);
1722        (cmd.registered + km.keybinds_applied) as usize
1723    }
1724
1725    /// Fire any lazy plugin gated on a `FileType` trigger for `filetype`.
1726    /// Returns the number of plugins activated. Call when a buffer of a
1727    /// known filetype is opened.
1728    pub fn activate_filetype_plugins(&mut self, filetype: &str) -> usize {
1729        let pending = self.plugin_host.pending_for_filetype(filetype);
1730        let n = pending.len();
1731        for src in pending {
1732            self.apply_plugin_entry(&src);
1733        }
1734        n
1735    }
1736
1737    /// Fire any lazy plugin gated on an `Event` trigger for `event`.
1738    /// Returns the number of plugins activated.
1739    pub fn activate_event_plugins(&mut self, event: &str) -> usize {
1740        let pending = self.plugin_host.pending_for_event(event);
1741        let n = pending.len();
1742        for src in pending {
1743            self.apply_plugin_entry(&src);
1744        }
1745        n
1746    }
1747
1748    /// Advance one frame's worth of state given a raw madori event.
1749    ///
1750    /// Key events pass through the [`KeyRepeatGate`] first (see
1751    /// [`Self::tick_at`]); everything else is handled directly.
1752    pub fn tick(&mut self, event: &AppEvent) {
1753        self.tick_at(event, Instant::now());
1754    }
1755
1756    /// [`Self::tick`] with an explicit timestamp for the key-repeat gate —
1757    /// lets tests drive the debounce window without depending on the
1758    /// wall clock.
1759    pub fn tick_at(&mut self, event: &AppEvent, now: Instant) {
1760        match translate_app_event(event) {
1761            InputOutcome::Key(k) => {
1762                if self.gate_key(&k, now) {
1763                    self.on_key(&k);
1764                }
1765            }
1766            InputOutcome::Resized { .. } => {
1767                // Damage only. Each face owns its own geometry: the GPU
1768                // backend derives the grid in `RenderCallback::resize`, and
1769                // the ratatui face reads its area every frame. This arm used
1770                // to write `Window.rect`, which nothing ever read — so the
1771                // resize path was already doing no real work, it just looked
1772                // like it was.
1773                self.damage = self.damage.join(Damage::Viewport);
1774                self.bump_gen();
1775            }
1776            InputOutcome::Quit => self.quit_requested = true,
1777            InputOutcome::Focus(_) | InputOutcome::None => {}
1778        }
1779    }
1780
1781    /// Decide whether `key` survives the key-repeat gate at time `now`.
1782    ///
1783    /// Returns `true` when the key should be processed, `false` when it is
1784    /// an OS key-repeat storm tick that should be dropped. Gating applies
1785    /// ONLY in the navigation modes (Normal / Visual / VisualLine) — those
1786    /// are where a held `j`/`l` floods the motion path and thrashes the
1787    /// viewport. Insert and Command modes pass every key through ungated,
1788    /// because there "hold a key to repeat the character" is the intended
1789    /// behavior, not a storm to suppress.
1790    fn gate_key(&mut self, key: &Key, now: Instant) -> bool {
1791        match self.modal.mode() {
1792            Mode::Normal | Mode::Visual | Mode::VisualLine => {
1793                // The gate exists for HELD keys that flood the motion path and
1794                // thrash the viewport (`j`, `l`). It is wrong for the discrete
1795                // jumps: two `n` presses 10 ms apart mean two matches, and
1796                // swallowing the second is indistinguishable from a dead key —
1797                // the exact symptom the gate was added to prevent elsewhere.
1798                if is_repeat_storm_candidate(key) {
1799                    return self.repeat_gate.try_pass_at(*key, now);
1800                }
1801                true
1802            }
1803            Mode::Insert | Mode::Command => true,
1804        }
1805    }
1806
1807    /// Dispatch a single key through the keymap + apply the resulting action.
1808    pub fn on_key(&mut self, key: &Key) {
1809        // An open picker owns EVERY key while it is up — before the splash,
1810        // before the sequence stepper, before the keymap.
1811        match self.consume_picker_key(key) {
1812            escriba_ui::picker::Consumed::NotShowing => {}
1813            escriba_ui::picker::Consumed::Held | escriba_ui::picker::Consumed::Dismissed => return,
1814            escriba_ui::picker::Consumed::Chose(c) => {
1815                self.honour_choice(c);
1816                return;
1817            }
1818        }
1819        // The start screen owns the first keypress and nothing after it.
1820        match self.consume_splash_key(key) {
1821            SplashKey::NotShowing | SplashKey::Dismissed => {}
1822            SplashKey::Ran(action) => {
1823                self.apply(&action);
1824                return;
1825            }
1826        }
1827        // Operator-pending OBJECT selection runs before EVERYTHING, because
1828        // `di(` must not be read as `d` then `i` (insert) then `(`.
1829        if let Some(action) = self.consume_object_key(*key) {
1830            match action {
1831                ObjectKey::Consumed => return,
1832                ObjectKey::Compose(a) => {
1833                    self.apply(&a);
1834                    return;
1835                }
1836            }
1837        }
1838        // Multi-key sequence resolution runs first: a key that begins or
1839        // continues a bound sequence (`<leader>ff`, `gg`) is held or
1840        // resolved here before the single-key path sees it.
1841        match self.step_sequence(key) {
1842            SeqStep::Pending => return,
1843            SeqStep::Resolved(action) => {
1844                let count = self.modal.pending_count().unwrap_or(1);
1845                self.modal.clear_count();
1846                for _ in 0..count {
1847                    self.apply(&action);
1848                    if self.quit_requested {
1849                        return;
1850                    }
1851                }
1852                return;
1853            }
1854            SeqStep::Passthrough => {}
1855        }
1856        let counted = self.keymap.dispatch(&self.modal, key);
1857        // Count prefixes accumulate into modal state.
1858        if matches!(counted.action, Action::Pending) {
1859            if let Key::Char(c) = key {
1860                if c.is_ascii_digit() {
1861                    let d = u32::from(*c as u8 - b'0');
1862                    self.modal.append_count(d);
1863                }
1864            }
1865            return;
1866        }
1867        // The count flows through the operator-pending FSM (apply_counted), which
1868        // owns repetition: a bare motion runs count× , an operator captures its
1869        // count, and an operated motion multiplies the two. No naive outer loop.
1870        self.apply_counted(&counted.action, counted.count);
1871        // After applying, reset pending count.
1872        self.modal.clear_count();
1873    }
1874
1875    /// Advance the multi-key pending-stroke state machine for `key`.
1876    ///
1877    /// Sequences only apply in normal / visual modes — insert and
1878    /// command modes treat keys as literal text. Rules:
1879    /// - Mid-sequence: extend the pending prefix. Exact match →
1880    ///   [`SeqStep::Resolved`]; still a live prefix → [`SeqStep::Pending`];
1881    ///   otherwise abort the sequence and re-process this key fresh.
1882    /// - Not mid-sequence: if `key` begins a bound sequence AND is not
1883    ///   itself a complete single binding (single bindings win, so no
1884    ///   chord timeout is needed) → start pending. Otherwise
1885    ///   [`SeqStep::Passthrough`] to the single-key dispatcher.
1886    fn step_sequence(&mut self, key: &Key) -> SeqStep {
1887        let mode = self.modal.mode();
1888        if !matches!(mode, Mode::Normal | Mode::Visual | Mode::VisualLine) {
1889            return SeqStep::Passthrough;
1890        }
1891        if !self.pending_keys.is_empty() {
1892            let mut seq = self.pending_keys.clone();
1893            seq.push(key.clone());
1894            if let Some(b) = self.keymap.lookup_sequence(mode, &seq) {
1895                let action = b.action.clone();
1896                self.pending_keys.clear();
1897                return SeqStep::Resolved(action);
1898            }
1899            if self.keymap.is_sequence_prefix(mode, &seq) {
1900                self.pending_keys = seq;
1901                return SeqStep::Pending;
1902            }
1903            // The key broke the in-progress sequence — abort it and let
1904            // the key be re-processed as a fresh stroke below.
1905            self.pending_keys.clear();
1906        }
1907        let start = [key.clone()];
1908        if self.keymap.is_sequence_prefix(mode, &start) && self.keymap.lookup(mode, key).is_none() {
1909            self.pending_keys = start.to_vec();
1910            return SeqStep::Pending;
1911        }
1912        SeqStep::Passthrough
1913    }
1914
1915    /// The primary cursor position. The single read accessor — every
1916    /// renderer + motion path goes through it, so the underlying
1917    /// representation (today a single-cursor [`Cursors`]) can grow to
1918    /// multi-caret without changing read sites.
1919    #[must_use]
1920    pub fn cursor(&self) -> Position {
1921        self.cursors.primary()
1922    }
1923
1924    /// The **single** cursor-mutation path. Clamp the requested position to
1925    /// the active buffer's bounds, then scroll the active window's viewport
1926    /// to contain it on BOTH axes. Routing every cursor change through this
1927    /// (and through [`Cursors::set_primary`]) makes "cursor outside its
1928    /// viewport" an unrepresentable state, AND keeps cursor state in ONE
1929    /// typed home — there is no code path that advances the cursor without
1930    /// re-deriving the viewport from it, and no second `Position` field to
1931    /// fall out of sync.
1932    /// Re-assert the cursor-visibility invariant against the CURRENT
1933    /// viewport.
1934    ///
1935    /// A resize changes how much a face can show without moving the cursor,
1936    /// so nothing would otherwise re-run `scroll_to_contain` — the cursor
1937    /// would sit off-screen until the operator happened to move it. Every
1938    /// face calls this after telling the runtime its new size.
1939    pub fn refollow_cursor(&mut self) {
1940        self.set_cursor(self.cursors.primary());
1941    }
1942
1943    fn set_cursor(&mut self, pos: Position) {
1944        let clamped = if let Some(buf) = self.buffers.get(self.active) {
1945            buf.clamp(pos)
1946        } else {
1947            pos
1948        };
1949        self.cursors.set_primary(clamped);
1950        if let Some(w) = self.layout.active_window_mut() {
1951            w.viewport = w.viewport.scroll_to_contain(self.cursors.primary(), 2);
1952        }
1953    }
1954
1955    /// Dispatch one resolved action at count 1. See [`apply_counted`](Self::apply_counted).
1956    fn apply(&mut self, action: &Action) {
1957        self.apply_counted(action, 1);
1958    }
1959
1960    /// Dispatch one resolved action with its count. Routes `(action, count)`
1961    /// through the operator-pending FSM ([`OperatorPending`], on `zenmai`): most
1962    /// actions pass straight to [`apply_resolved`](Self::apply_resolved) carrying
1963    /// their count (so `5j` runs the motion 5×), an operator key is held, and an
1964    /// operator-then-motion pair is rewritten into a counted
1965    /// [`Action::ApplyOperator`] (so `3dw` deletes 3 words). The FSM owns count
1966    /// composition — there is no naive outer repeat loop.
1967    fn apply_counted(&mut self, action: &Action, count: u32) {
1968        // An uncompilable pattern must not reach the operator machine.
1969        //
1970        // `SearchState::accept` puts the prompt BACK on a compile error so the
1971        // typed text is not lost — but the FSM had already transitioned out of
1972        // `AwaitingSearch` on the way in, so the prompt survived and the
1973        // OPERATOR did not, with nothing said about it. The `d` was simply
1974        // gone, and the corrected pattern then ran as a bare search.
1975        //
1976        // The machine is a pure `(State, Event) -> (State, effects)` and
1977        // cannot observe the result of an effect, so it cannot decide this
1978        // itself. The fix is to stop handing it an event it has no business
1979        // deciding: the runtime classifies the submit first, from state it
1980        // already holds. `prompt_error` returns `None` for an EMPTY prompt, so
1981        // the bare-`/<CR>` reuse path is untouched.
1982        //
1983        // Tier-honest: parse-rejected at the boundary, not
1984        // truly-unrepresentable.
1985        if matches!(action, Action::SubmitCommand) {
1986            if let Some(e) = self.search.prompt_error() {
1987                let mut m = String::from("E383: Invalid search string: ");
1988                m.push_str(&e.to_string());
1989                self.messages.push(m);
1990                return;
1991            }
1992        }
1993
1994        for (resolved, times) in self.op_pending.dispatch((action.clone(), count)) {
1995            // `3dw` is ONE delete of three words as far as the register is
1996            // concerned, not three deletes of one. Each repetition emits its
1997            // own `Negai::Yank`, and each used to overwrite the register — so
1998            // `3dwP` put back only the third word and silently lost two.
1999            //
2000            // Repetitions of a REGISTER-LEAVING operator therefore append,
2001            // and the flag is cleared after the group so an unrelated later
2002            // yank still replaces rather than growing forever.
2003            // A COUNTED operator-over-motion is ONE operation over a motion
2004            // resolved `times` over, not `times` operations over one motion.
2005            //
2006            // That distinction is not pedantry. Repeating the operation works
2007            // by accident for delete — the text vanishes, so the cursor ends
2008            // up somewhere new each round — and is simply wrong for yank,
2009            // which does not move the cursor: `2yw` re-yanked the FIRST word
2010            // twice and put "one one " in the register. Resolving the motion
2011            // twice and yanking once gives "one two ", and the register needs
2012            // no accumulation because there was only ever one yank.
2013            if let Action::ApplyOperator { op, motion } = resolved {
2014                self.apply_operator_n(op, motion, times);
2015                if self.quit_requested {
2016                    return;
2017                }
2018                continue;
2019            }
2020            for _ in 0..times {
2021                self.apply_resolved(&resolved);
2022                if self.quit_requested {
2023                    return;
2024                }
2025            }
2026        }
2027    }
2028
2029    /// The active buffer's text. Search is a pure function of it.
2030    /// The active buffer's text revision — the token an offset measured
2031    /// against it should carry.
2032    #[must_use]
2033    fn text_rev(&self) -> TextRev {
2034        self.buffers
2035            .get(self.active)
2036            .map_or_else(TextRev::default, escriba_buffer::Buffer::text_rev)
2037    }
2038
2039    fn active_text(&self) -> String {
2040        self.buffers
2041            .get(self.active)
2042            .map(escriba_buffer::Buffer::to_string)
2043            .unwrap_or_default()
2044    }
2045
2046    /// The cursor as a char offset — the coordinate search speaks.
2047    fn cursor_char(&self) -> usize {
2048        self.buffers
2049            .get(self.active)
2050            .and_then(|b| b.position_to_char(self.cursor()).ok())
2051            .unwrap_or(0)
2052    }
2053
2054    /// Move the cursor onto a match and report a wrap the way vim does.
2055    /// The status line as data — what every face draws.
2056    ///
2057    /// One model, so the two faces can only disagree about styling. Before
2058    /// this existed the GPU face built its own line from a fixed `format!()`
2059    /// and drew neither the prompt nor any message, which made a fully
2060    /// working `/` look like a dead key on escriba's default renderer.
2061    #[must_use]
2062    pub fn status_model(&self) -> StatusModel<'_> {
2063        let cursor = self.cursor();
2064        let prompt = self.search.prompt();
2065
2066        let kind = match prompt.map(|p| p.direction) {
2067            Some(escriba_search::Direction::Forward) => PromptKind::SearchForward,
2068            Some(escriba_search::Direction::Backward) => PromptKind::SearchBackward,
2069            // Command mode with no search prompt open is an ex-command; the
2070            // typed `Option<Prompt>` is the discriminator, never a mode flag.
2071            None if self.modal.mode() == Mode::Command => PromptKind::Ex,
2072            None => PromptKind::None,
2073        };
2074
2075        StatusModel {
2076            mode: self.modal.mode(),
2077            line: cursor.line.saturating_add(1) as usize,
2078            column: cursor.column.saturating_add(1) as usize,
2079            prompt: kind,
2080            prompt_text: prompt
2081                .map_or_else(|| self.modal.minibuffer(), escriba_search::Prompt::text),
2082            prompt_caret: prompt.map_or_else(
2083                || self.modal.minibuffer_caret(),
2084                escriba_search::Prompt::caret,
2085            ),
2086            count: self.match_count(),
2087            message: self.messages.last().map(String::as_str),
2088        }
2089    }
2090
2091    /// `[3/17]` for the current pattern.
2092    ///
2093    /// While a prompt is open the count describes the PREVIEW — the answer to
2094    /// "what would Enter do", which is the question being asked mid-typing.
2095    /// Once committed it describes where the cursor actually is.
2096    #[must_use]
2097    fn match_count(&self) -> MatchCount {
2098        if self.search.is_prompting() {
2099            let text = self.active_text();
2100            // ONE scan, four outcomes. `Incomplete` and `NoMatch` used to be
2101            // the same `None`, so a half-typed character class reported
2102            // `[0/0]` — telling the user their pattern matches nothing while
2103            // they are still writing it.
2104            return match self.search.preview(&text) {
2105                escriba_search::Preview::Landed { step, total } => {
2106                    MatchCount::new(step.index, total)
2107                }
2108                escriba_search::Preview::NoMatch => MatchCount::None,
2109                escriba_search::Preview::Incomplete | escriba_search::Preview::Idle => {
2110                    MatchCount::Idle
2111                }
2112            };
2113        }
2114        if self.search.pattern().is_none() {
2115            return MatchCount::Idle;
2116        }
2117        let total = self.search.matches().len();
2118        // Read THROUGH the anchor: an ordinal computed against text that has
2119        // since changed reads as absent, so a stale count cannot be displayed.
2120        let rev = self.text_rev();
2121        self.search_at.as_ref().and_then(|a| a.get(rev)).map_or(
2122            if total == 0 {
2123                MatchCount::None
2124            } else {
2125                MatchCount::Idle
2126            },
2127            |&i| MatchCount::new(i, total),
2128        )
2129    }
2130
2131    /// `.` — replay the last change at the cursor.
2132    ///
2133    /// Two steps, because a change can be two: run the action, then re-type
2134    /// whatever followed it. `cgn` + `.` is exactly this — change the next
2135    /// match, then repeat that whole gesture on the one after.
2136    fn repeat_last_change(&mut self) {
2137        let Some(change) = self.last_change.clone() else {
2138            self.messages
2139                .push("E32: No previous change to repeat".to_string());
2140            return;
2141        };
2142
2143        for _ in 0..change.count.max(1) {
2144            self.apply_resolved(&change.action);
2145        }
2146        for c in change.inserted.chars() {
2147            self.apply_resolved(&Action::InsertChar(c));
2148        }
2149        if self.modal.mode() == Mode::Insert {
2150            // A replayed change must not leave the editor in Insert — the
2151            // original ended with an Esc the recording deliberately does not
2152            // store, since it is punctuation rather than part of the change.
2153            self.apply_resolved(&Action::ChangeMode(Mode::Normal));
2154        }
2155        // The replay wrote through `apply_resolved`, which re-records
2156        // `last_change` from the inner action. Put the ORIGINAL back so a
2157        // second `.` repeats the same change rather than a fragment of it.
2158        self.last_change = Some(change);
2159        self.recording_insert = false;
2160    }
2161
2162    /// Resolve a text object to the range it names.
2163    ///
2164    /// `gn` uses the INCLUSIVE step, so a cursor already sitting inside a
2165    /// match operates on THAT match rather than skipping to the next — which
2166    /// is what makes `cgn` then `.` walk matches one at a time instead of
2167    /// every other one.
2168    /// `dd` — the current line INCLUDING its terminator.
2169    ///
2170    /// Taking the newline is what makes `dd` remove a line rather than blank
2171    /// it. On the last line there is no following newline to take, so it
2172    /// falls back to the preceding one — otherwise `dd` on the final line
2173    /// leaves an empty line behind, which is the one case a naive
2174    /// "start-of-line to start-of-next-line" range gets wrong.
2175    fn object_line(&self) -> Option<Range> {
2176        let buf = self.buffers.get(self.active)?;
2177        let line = self.cursor().line;
2178        let last = buf.line_count().saturating_sub(1);
2179        if line < last {
2180            Some(Range::new(
2181                Position::new(line, 0),
2182                Position::new(line + 1, 0),
2183            ))
2184        } else if line > 0 {
2185            // Final line: swallow the PRECEDING newline instead.
2186            Some(Range::new(
2187                Position::new(line - 1, buf.line_len_chars(line - 1)),
2188                Position::new(line, buf.line_len_chars(line)),
2189            ))
2190        } else {
2191            // The only line in the buffer: clear it, keep the line itself.
2192            Some(Range::new(
2193                Position::new(0, 0),
2194                Position::new(0, buf.line_len_chars(0)),
2195            ))
2196        }
2197    }
2198
2199    /// `iw` / `aw` — the word under the cursor.
2200    ///
2201    /// vim's `w` classes are word / punctuation / whitespace, and a text
2202    /// object never crosses a line. `around` additionally takes the trailing
2203    /// whitespace run, falling back to LEADING whitespace when there is none
2204    /// after — which is what vim does at end of line.
2205    fn object_word(&self, around: bool) -> Option<Range> {
2206        let buf = self.buffers.get(self.active)?;
2207        let pos = self.cursor();
2208        let text: Vec<char> = buf.line(pos.line)?.chars().collect();
2209        if text.is_empty() {
2210            return None;
2211        }
2212        let col = (pos.column as usize).min(text.len().saturating_sub(1));
2213
2214        #[derive(PartialEq, Clone, Copy)]
2215        enum Class {
2216            Word,
2217            Punct,
2218            Space,
2219        }
2220        let class = |c: char| {
2221            if c.is_alphanumeric() || c == '_' {
2222                Class::Word
2223            } else if c.is_whitespace() {
2224                Class::Space
2225            } else {
2226                Class::Punct
2227            }
2228        };
2229
2230        let here = class(text[col]);
2231        let mut start = col;
2232        while start > 0 && class(text[start - 1]) == here {
2233            start -= 1;
2234        }
2235        let mut end = col + 1;
2236        while end < text.len() && class(text[end]) == here {
2237            end += 1;
2238        }
2239
2240        if around {
2241            let after = end;
2242            while end < text.len() && class(text[end]) == Class::Space {
2243                end += 1;
2244            }
2245            // No trailing run: take the leading one instead, as vim does.
2246            if end == after {
2247                while start > 0 && class(text[start - 1]) == Class::Space {
2248                    start -= 1;
2249                }
2250            }
2251        }
2252
2253        Some(Range::new(
2254            Position::new(pos.line, start as u32),
2255            Position::new(pos.line, end as u32),
2256        ))
2257    }
2258
2259    /// `i(` / `a"` … — the region between a matched pair, on one line.
2260    ///
2261    /// Brackets NEST and quotes do not, and that is the only difference:
2262    /// with `open == close` the scan cannot count depth, so it takes the
2263    /// nearest delimiter on each side instead.
2264    fn object_delimited(&self, open: char, close: char, around: bool) -> Option<Range> {
2265        let buf = self.buffers.get(self.active)?;
2266        let pos = self.cursor();
2267        let text: Vec<char> = buf.line(pos.line)?.chars().collect();
2268        if text.is_empty() {
2269            return None;
2270        }
2271        let col = (pos.column as usize).min(text.len().saturating_sub(1));
2272
2273        let (l, r) = if open == close {
2274            // Quotes: nearest on each side, no nesting to track.
2275            let l = (0..=col).rev().find(|&i| text[i] == open)?;
2276            let r = ((col.max(l) + 1)..text.len()).find(|&i| text[i] == close)?;
2277            (l, r)
2278        } else {
2279            // Brackets: walk out counting depth, so an inner pair does not
2280            // terminate the search for the enclosing one.
2281            let mut depth = 0i32;
2282            let l = (0..=col).rev().find(|&i| {
2283                if text[i] == close && i != col {
2284                    depth += 1;
2285                    false
2286                } else if text[i] == open {
2287                    if depth == 0 {
2288                        true
2289                    } else {
2290                        depth -= 1;
2291                        false
2292                    }
2293                } else {
2294                    false
2295                }
2296            })?;
2297            depth = 0;
2298            let r = ((l + 1)..text.len()).find(|&i| {
2299                if text[i] == open {
2300                    depth += 1;
2301                    false
2302                } else if text[i] == close {
2303                    if depth == 0 {
2304                        true
2305                    } else {
2306                        depth -= 1;
2307                        false
2308                    }
2309                } else {
2310                    false
2311                }
2312            })?;
2313            (l, r)
2314        };
2315
2316        // `i` is strictly between the delimiters; `a` includes them.
2317        let (s, e) = if around { (l, r + 1) } else { (l + 1, r) };
2318        Some(Range::new(
2319            Position::new(pos.line, s as u32),
2320            Position::new(pos.line, e as u32),
2321        ))
2322    }
2323
2324    fn resolve_object(&self, object: escriba_core::TextObject) -> Option<Range> {
2325        use escriba_core::TextObject as O;
2326
2327        // The text-scanning objects resolve against the BUFFER; the two
2328        // search objects resolve against the match set. Splitting here keeps
2329        // the search logic below exactly as it was rather than threading a
2330        // second concern through it.
2331        match object {
2332            O::Line => return self.object_line(),
2333            O::Word { around } => return self.object_word(around),
2334            O::Delimited {
2335                open,
2336                close,
2337                around,
2338            } => return self.object_delimited(open, close, around),
2339            O::NextMatch | O::PrevMatch => {}
2340        }
2341
2342        let at = self.cursor_char();
2343        let matches = self.search.matches();
2344
2345        // A match CONTAINING the cursor wins outright, whichever direction the
2346        // object names.
2347        //
2348        // Comparing only against `m.start` — which is what a `starts`-vector
2349        // plus `Bound::Inclusive` does — is right only when the cursor sits on
2350        // a match's FIRST character. One column further in, `start < at` and
2351        // the match is rejected, so `cgn` skipped the very instance the
2352        // operator was standing in and the rename silently missed it. vim
2353        // operates on the containing match from every interior column, and the
2354        // `starts`-only comparison cannot express "contains" because it never
2355        // looks at `m.end`.
2356        let idx = matches.iter().position(|m| m.contains(at)).or_else(|| {
2357            let starts: Vec<usize> = matches.iter().map(|m| m.start).collect();
2358            match object {
2359                O::PrevMatch => Bound::Inclusive.first_matching(&starts, at, false),
2360                // Every other variant returned above; `NextMatch` is the only
2361                // one that can reach here besides `PrevMatch`.
2362                _ => Bound::Inclusive.first_matching(&starts, at, true),
2363            }
2364        })?;
2365
2366        let m = matches.get(idx)?;
2367        let buf = self.buffers.get(self.active)?;
2368        Some(Range {
2369            start: buf.char_to_position(m.start),
2370            end: buf.char_to_position(m.end),
2371        })
2372    }
2373
2374    fn land_on(&mut self, step: escriba_search::Step) {
2375        if let Some(buf) = self.buffers.get(self.active) {
2376            let pos = buf.char_to_position(step.target.start);
2377            self.set_cursor(pos);
2378        }
2379        // The `[3/17]` numerator. `Step` has carried this index since the
2380        // engine was written — `engine.rs` even names the counter as the
2381        // reason it exists — and every consumer discarded it until now.
2382        self.search_at = Some(Anchored::new(step.index, self.text_rev()));
2383    }
2384
2385    /// vim's "search hit BOTTOM, continuing at TOP".
2386    ///
2387    /// One reporter, called by the two places a search can wrap: the shared
2388    /// commit and `n`/`N`. `land_on` deliberately does NOT report, or the bare
2389    /// commit would say it twice.
2390    fn report_wrap(&mut self, step: &escriba_search::Step) {
2391        if let Some(msg) = escriba_search::wrap_message(step.wrapped) {
2392            self.messages.push(msg.to_string());
2393        }
2394    }
2395
2396    /// `n` / `N`. Reports vim's E486 when the pattern matches nothing, rather
2397    /// than failing silently — a search that appears to do nothing is
2398    /// indistinguishable from a dropped keystroke.
2399    fn jump_search(&mut self, reverse: bool) {
2400        // Using the matches re-lights them: `n` after an auto-clear shows you
2401        // what you are walking through.
2402        self.search.relight();
2403        // `n` is a far jump — record where we leave from so `<C-o>` works.
2404        self.jumps.push(self.spot());
2405        let at = self.cursor_char();
2406        match self.search.repeat(at, reverse) {
2407            Some(step) => {
2408                // `n` wrapping the file says so, same as a commit does.
2409                self.report_wrap(&step);
2410                self.land_on(step);
2411            }
2412            None => {
2413                let msg = self.search.pattern().map_or_else(
2414                    || "E35: No previous regular expression".to_string(),
2415                    |p| {
2416                        let mut m = String::from("E486: Pattern not found: ");
2417                        m.push_str(p.raw());
2418                        m
2419                    },
2420                );
2421                self.messages.push(msg);
2422            }
2423        }
2424    }
2425
2426    /// Move the cursor to where the in-progress pattern would land, without
2427    /// committing anything. vim's `incsearch`.
2428    ///
2429    /// A pattern that does not compile yet (`/a[`, mid-typing) previews
2430    /// nothing and reports nothing — an error toast on every keystroke of a
2431    /// character class would be unusable.
2432    fn preview_search(&mut self) {
2433        let text = self.active_text();
2434        let Some(origin) = self.search.prompt().map(|p| p.origin) else {
2435            return;
2436        };
2437        let target = match self.search.preview(&text) {
2438            escriba_search::Preview::Landed { step, .. } => step.target.start,
2439            // Nothing to show: back to where the search started. Covers a
2440            // half-typed pattern and a pattern that finds nothing alike —
2441            // both mean "there is no match to preview".
2442            escriba_search::Preview::Idle
2443            | escriba_search::Preview::Incomplete
2444            | escriba_search::Preview::NoMatch => origin,
2445        };
2446        // A pattern that STOPS matching returns the cursor to the origin.
2447        //
2448        // Preview used to only ever move forward, so typing `ch` (a match) and
2449        // then `chz` (none) left the cursor parked on the `ch` match — a
2450        // preview showing a position the pattern no longer justifies, while
2451        // the count beside it read `[0/0]`. Restoring is also what makes
2452        // Escape's promise legible: at every keystroke the cursor is either on
2453        // a real match or back where you started, never on a stale one.
2454        if let Some(buf) = self.buffers.get(self.active) {
2455            let pos = buf.char_to_position(target);
2456            self.set_cursor(pos);
2457        }
2458    }
2459
2460    /// `d/foo<CR>` — commit the prompt and operate from the prompt's origin to
2461    /// where the search lands, as ONE action.
2462    ///
2463    /// Split from [`Self::submit_search`] rather than sharing it because the
2464    /// two want opposite things from the commit: the bare `/` MOVES the cursor
2465    /// to the match, and an operated `/` must NOT — the cursor is the
2466    /// operator's start point, and moving it first would leave the operator
2467    /// with a zero-width range.
2468    /// Commit the open search prompt. The ONE copy of the sequence.
2469    ///
2470    /// Reports its own failures (E486 / E35) so neither caller has to carry a
2471    /// third copy of the message strings. `Accepted::Invalid` cannot reach
2472    /// here — `apply_counted` rejects an uncompilable pattern at the dispatch
2473    /// boundary before the FSM or this method ever sees the submit.
2474    fn commit_search_prompt(&mut self) -> CommitOutcome {
2475        let text = self.active_text();
2476        let Some((origin, skip)) = self.search.prompt().map(|p| (p.origin, p.preview_skip()))
2477        else {
2478            return CommitOutcome::NoPrompt;
2479        };
2480
2481        match self.search.accept(&text) {
2482            escriba_search::Accepted::Committed | escriba_search::Accepted::ReusedPrevious => {
2483                self.modal.clear_minibuffer();
2484                self.modal.enter(Mode::Normal);
2485                match self.search.commit_step_skipping(origin, skip) {
2486                    Some(step) => {
2487                        // The wrap notice belongs HERE, once, for both commit
2488                        // paths. Reporting it in each caller is what let the
2489                        // operated path lose it in the first place — and my
2490                        // first attempt at this refactor duplicated it again
2491                        // rather than moving it, which the red proof caught.
2492                        self.report_wrap(&step);
2493                        CommitOutcome::Landed { origin, step }
2494                    }
2495                    None => {
2496                        self.report_pattern_not_found();
2497                        CommitOutcome::NotFound
2498                    }
2499                }
2500            }
2501            escriba_search::Accepted::NothingToRepeat => {
2502                self.modal.clear_minibuffer();
2503                self.modal.enter(Mode::Normal);
2504                self.messages
2505                    .push("E35: No previous regular expression".to_string());
2506                CommitOutcome::NoPrevious
2507            }
2508            // Unreachable: the boundary guard in `apply_counted` returns early
2509            // on an uncompilable pattern, leaving the prompt open. Reported
2510            // rather than `unreachable!()` — a panic in the editor's commit
2511            // path is a worse failure than a duplicate message.
2512            escriba_search::Accepted::Invalid(e) => {
2513                let mut m = String::from("E383: Invalid search string: ");
2514                m.push_str(&e.to_string());
2515                self.messages.push(m);
2516                CommitOutcome::NoPrompt
2517            }
2518        }
2519    }
2520
2521    /// vim's E486, with the pattern named. One place, so every path that fails
2522    /// to find reports identically.
2523    fn report_pattern_not_found(&mut self) {
2524        let mut m = String::from("E486: Pattern not found");
2525        if let Some(p) = self.search.pattern() {
2526            m.push_str(": ");
2527            m.push_str(p.raw());
2528        }
2529        self.messages.push(m);
2530    }
2531
2532    /// Bare `/foo<CR>` — commit and MOVE the cursor to the match.
2533    ///
2534    /// The only difference from the operated path is that this one lands;
2535    /// everything else lives in `commit_search_prompt`.
2536    fn submit_search(&mut self) {
2537        match self.commit_search_prompt() {
2538            CommitOutcome::Landed { origin, step } => {
2539                if let Some(buf) = self.buffers.get(self.active) {
2540                    let from = buf.char_to_position(origin);
2541                    self.jumps.push(escriba_core::Spot::new(self.active, from));
2542                }
2543                self.land_on(step);
2544            }
2545            CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
2546        }
2547    }
2548
2549    /// `d/foo<CR>` — commit, then operate from the prompt's origin to where the
2550    /// search lands, as ONE action.
2551    ///
2552    /// The cursor must NOT move to the match first: it is the operator's start
2553    /// point. That is the whole reason this differs from the bare path, and
2554    /// now the only reason.
2555    fn submit_search_operated(&mut self, op: Operator) {
2556        match self.commit_search_prompt() {
2557            CommitOutcome::Landed { origin, step } => {
2558                if let Some(buf) = self.buffers.get(self.active) {
2559                    let from = buf.char_to_position(origin);
2560                    let target = buf.char_to_position(step.target.start);
2561                    // Operating over a search is itself a far jump.
2562                    self.jumps.push(escriba_core::Spot::new(self.active, from));
2563                    self.set_cursor(from);
2564                    self.apply_operator_to(op, target);
2565                }
2566            }
2567            CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
2568        }
2569    }
2570
2571    fn apply_resolved(&mut self, action: &Action) {
2572        // Snapshot the scope inputs before the mutation so the resulting
2573        // Damage covers the changed region (the S3 seal — conservative widen).
2574        let lines_before = self.active_line_count();
2575        // Snapshot for the dot register: the only reliable witness that this
2576        // action changed text is that the buffer's revision moved.
2577        let rev_before = self.text_rev();
2578        let cline_before = self.cursor().line;
2579        match action {
2580            // Every action with an exact slip equivalent goes through the
2581            // interpreter, so "undo" has ONE implementation rather than one
2582            // per entry point. These had already drifted: the executor
2583            // re-followed the viewport after undo and the M1 interpreter did
2584            // not, so `u` and `:undo` behaved differently within a milestone
2585            // of each other.
2586            // Listed EXPLICITLY rather than behind a `if lower(..).is_some()`
2587            // guard: a guard arm does not count toward exhaustiveness, so the
2588            // guarded form silently gave up the total match — the compiler
2589            // said so, and it was right. `lowering_and_dispatch_agree` pins
2590            // that this list and `lower` stay the same set.
2591            Action::Quit
2592            | Action::ClearSearchHighlight
2593            | Action::Save
2594            | Action::Undo
2595            | Action::Redo
2596            | Action::Edit(_) => {
2597                for slip in Self::lower(action, self.active).unwrap_or_default() {
2598                    self.honour_one(slip);
2599                }
2600            }
2601            Action::Move(m) => self.apply_motion(*m),
2602            Action::SearchOpen(dir) => {
2603                // vim's `/` is the command-line with a different prompt char,
2604                // so we reuse Command mode; `search.prompt` is what tells a
2605                // later <CR> this is a search and not an ex-command.
2606                let origin = self.cursor_char();
2607                self.search.open(*dir, origin);
2608                self.modal.enter(Mode::Command);
2609            }
2610            Action::SearchRepeat { reverse } => self.jump_search(*reverse),
2611            Action::SearchWord { reverse } => {
2612                let dir = if *reverse {
2613                    SearchDirection::Backward
2614                } else {
2615                    SearchDirection::Forward
2616                };
2617                let (text, at) = (self.active_text(), self.cursor_char());
2618                // `*` jumps, so it records too.
2619                self.jumps.push(self.spot());
2620                match self.search.search_word(&text, at, dir) {
2621                    Some(step) => self.land_on(step),
2622                    // vim beeps and stays put when there is no word under the
2623                    // cursor; a silent no-op would look like a broken key.
2624                    None => self
2625                        .messages
2626                        .push("E348: No string under cursor".to_string()),
2627                }
2628            }
2629            Action::SearchSubmitOperated { op } => self.submit_search_operated(*op),
2630            Action::TextObject(object) => {
2631                // Bare `gn` moves onto the match. vim additionally starts a
2632                // Visual selection of it; escriba's Visual plumbing does not
2633                // carry a selection an operator can consume yet, so this
2634                // stops at the jump rather than faking a selection that
2635                // nothing would honour.
2636                if let Some(range) = self.resolve_object(*object) {
2637                    self.jumps.push(self.spot());
2638                    self.set_cursor(range.start);
2639                } else {
2640                    self.report_pattern_not_found();
2641                }
2642            }
2643            Action::ApplyOperatorObject { op, object } => match self.resolve_object(*object) {
2644                Some(range) => self.apply_operator_over(*op, range),
2645                None => self.report_pattern_not_found(),
2646            },
2647            Action::RepeatLastChange => self.repeat_last_change(),
2648            Action::JumpBack => {
2649                let here = self.spot();
2650                if let Some(spot) = self.jumps.back(here) {
2651                    self.goto_spot(spot);
2652                } else {
2653                    self.messages
2654                        .push("E662: At start of changelist".to_string());
2655                }
2656            }
2657            Action::JumpForward => {
2658                if let Some(spot) = self.jumps.forward() {
2659                    self.goto_spot(spot);
2660                } else {
2661                    self.messages.push("E663: At end of changelist".to_string());
2662                }
2663            }
2664            Action::ChangeMode(m) => {
2665                // Leaving the cmdline abandons any open search prompt and
2666                // returns the cursor home. The COMMITTED pattern survives —
2667                // cancelling a new search must not erase the old highlights.
2668                if *m == Mode::Normal && self.search.is_prompting() {
2669                    if let Some(origin) = self.search.cancel() {
2670                        if let Some(buf) = self.buffers.get(self.active) {
2671                            let pos = buf.char_to_position(origin);
2672                            self.set_cursor(pos);
2673                        }
2674                    }
2675                }
2676                self.modal.enter(*m);
2677            }
2678            Action::InsertChar(c) => self.insert_char(*c),
2679
2680            Action::SubmitCommand => {
2681                if self.search.is_prompting() {
2682                    self.submit_search();
2683                } else {
2684                    self.submit_command();
2685                }
2686            }
2687            Action::Command { name, args } => self.run_command(name, args),
2688            Action::ApplyOperator { op, motion } => self.apply_operator(*op, *motion),
2689            // The operator-pending FSM consumes Operator keys (begins pending);
2690            // they never reach the executor. Defensive no-op for exhaustiveness.
2691            Action::Operator(_) => {}
2692            Action::PromptCaret { to } => {
2693                // Both prompts have a caret now, and the same keys move it.
2694                if self.search.is_prompting() {
2695                    self.search.move_caret(*to);
2696                } else {
2697                    self.modal.move_minibuffer_caret(*to);
2698                }
2699            }
2700            Action::SearchPreviewStep { forward } => {
2701                if self.search.is_prompting() {
2702                    self.search.preview_step(*forward);
2703                    self.preview_search();
2704                }
2705            }
2706            Action::PromptDelete => {
2707                if self.search.is_prompting() {
2708                    self.search.delete_at_caret();
2709                    self.preview_search();
2710                } else {
2711                    self.modal.delete_minibuffer_at_caret();
2712                }
2713            }
2714            Action::PromptDeleteWord => {
2715                if self.search.is_prompting() {
2716                    self.search.delete_word_before_caret();
2717                    self.preview_search();
2718                }
2719            }
2720            Action::PromptClearToStart => {
2721                if self.search.is_prompting() {
2722                    self.search.clear_before_caret();
2723                    self.preview_search();
2724                }
2725            }
2726            Action::PromptBackspace => {
2727                self.prompt_backspace();
2728                // Shortening the pattern changes which matches exist, so the
2729                // preview must re-run — otherwise the cursor sits on a match
2730                // of a pattern that is no longer typed.
2731                if self.search.is_prompting() {
2732                    self.preview_search();
2733                }
2734            }
2735            Action::PromptHistory { back } => {
2736                if self.search.is_prompting() {
2737                    self.search.history_step(*back);
2738                    // No minibuffer resync: the shadow is the ex-line's store
2739                    // and nothing reads it while a search prompt is open, so
2740                    // rewriting it here was maintaining a copy for no reader.
2741                    self.preview_search();
2742                }
2743            }
2744            Action::Pending => {}
2745        }
2746        // Widen the dirty region by what this action touched (M1). Content
2747        // mutations that changed the line count run to end-of-document (every
2748        // line below shifted); an in-place edit or a cursor move is local;
2749        // arbitrary commands are conservatively Full. Never narrows.
2750        let lines_after = self.active_line_count();
2751        let cline_after = self.cursor().line;
2752        let d = match action {
2753            // A search repaints every highlight in the viewport, not just the
2754            // line the cursor left — so it must widen to Full. Treating it as a
2755            // cursor move would leave stale highlights on untouched lines.
2756            Action::SearchOpen(_)
2757            | Action::PromptHistory { .. }
2758            | Action::PromptBackspace
2759            | Action::PromptCaret { .. }
2760            | Action::SearchPreviewStep { .. }
2761            | Action::PromptDelete
2762            | Action::PromptDeleteWord
2763            | Action::PromptClearToStart
2764            | Action::SearchRepeat { .. }
2765            | Action::SearchWord { .. }
2766            | Action::ClearSearchHighlight
2767            | Action::SearchSubmitOperated { .. }
2768            // A replayed change can edit anywhere the original could, and a
2769            // match object can be anywhere in the document.
2770            | Action::RepeatLastChange
2771            | Action::TextObject(_)
2772            | Action::ApplyOperatorObject { .. }
2773            // A jump can land anywhere, so the viewport may scroll wholesale.
2774            | Action::JumpBack
2775            | Action::JumpForward => Damage::Full,
2776            Action::InsertChar(_)
2777            | Action::Edit(_)
2778            | Action::Undo
2779            | Action::Redo
2780            | Action::ApplyOperator { .. } => {
2781                if lines_after == lines_before {
2782                    Damage::span(cline_before, cline_after)
2783                } else {
2784                    Damage::Lines {
2785                        from: cline_before.min(cline_after),
2786                        to: u32::MAX,
2787                    }
2788                }
2789            }
2790            Action::Move(_) | Action::ChangeMode(_) => Damage::span(cline_before, cline_after),
2791            Action::Save => Damage::Viewport,
2792            Action::Command { .. } | Action::SubmitCommand => Damage::Full,
2793            Action::Quit | Action::Operator(_) | Action::Pending => Damage::None,
2794        };
2795        self.damage = self.damage.join(d);
2796        // Remember this change for `.`.
2797        //
2798        // Recorded from an OBSERVED MUTATION, not from the action's variant.
2799        // `text_effect()` is the wrong predicate here even though it looks
2800        // like the right one: it exists to decide cache invalidation, where
2801        // OVER-reporting is the safe direction, and the dot register needs the
2802        // opposite bias. Leaning on it meant `last_change` was set by actions
2803        // that changed no text at all, with two measured consequences:
2804        //
2805        //   `iZ<Esc>` then `/a<CR>` then `.`  — did nothing; the register held
2806        //       `SubmitCommand`, whose replay reads an already-cleared
2807        //       minibuffer.
2808        //   `iZ<Esc>` then `/q<Esc>` then `.` — TYPED `q` INTO THE BUFFER. An
2809        //       abandoned prompt left the register holding `InsertChar('q')`,
2810        //       and `.` in Normal mode routes that to the text. A corrupting
2811        //       register, not merely a lost one.
2812        //
2813        // Comparing the buffer's `TextRev` across the action answers the only
2814        // question that matters — did this actually change the text — and gets
2815        // the failed-operator case (`dgn` with no pattern) right for free.
2816        if self.recording_insert {
2817            match action {
2818                Action::InsertChar(c) => {
2819                    if let Some(lc) = self.last_change.as_mut() {
2820                        lc.inserted.push(*c);
2821                    }
2822                }
2823                // Leaving Insert ends the session; the change is now whole.
2824                Action::ChangeMode(m) if *m != Mode::Insert => self.recording_insert = false,
2825                _ => {}
2826            }
2827        } else if self.text_rev() != rev_before
2828            && !matches!(
2829                action,
2830                Action::RepeatLastChange | Action::Undo | Action::Redo
2831            )
2832        {
2833            self.last_change = Some(LastChange {
2834                action: action.clone(),
2835                count: 1,
2836                inserted: String::new(),
2837            });
2838            self.recording_insert = self.modal.mode() == Mode::Insert;
2839        }
2840
2841        // The search is over the moment you move on or edit — clear the
2842        // highlight rather than leaving the buffer as confetti until an
2843        // explicit `:noh`, which is the remap nearly every vimrc carries.
2844        // Clearing suppresses without forgetting, so `n` still works.
2845        if action.highlight_effect() == HighlightEffect::Clear {
2846            self.search.clear_highlight();
2847        }
2848        // Text changed ⇒ every match offset cached against the old text is
2849        // wrong. `SearchState::refresh` existed for exactly this and had ZERO
2850        // callers, so inserting four characters left both renderers painting
2851        // the highlight four columns off.
2852        //
2853        // Gated on the typed classifier rather than on `bump_gen` (which fires
2854        // for pure cursor moves too): re-scanning the document on every `j`
2855        // would be a per-keystroke full pass for no reason.
2856        if action.text_effect() == TextEffect::Mutates && self.search.pattern().is_some() {
2857            let text = self.active_text();
2858            self.search.refresh(&text);
2859            // NO manual invalidation of `search_at` here, deliberately. It is
2860            // `Anchored` to the text revision, so an ordinal computed against
2861            // the old text now reads as `None` on its own. This is the line
2862            // that used to have to be remembered.
2863        }
2864        // An action reached the executor ⇒ visible state may have changed.
2865        // Advance the refresh generation so the renderer repaints (and
2866        // re-highlights) exactly once. A gated-out key never reaches here, so
2867        // a key-repeat storm does not spin the renderer.
2868        self.bump_gen();
2869    }
2870
2871    /// Resolve a [`Motion`] from `from` to its target [`Position`] against the
2872    /// active buffer — **pure**: no cursor mutation, no side effects. This is
2873    /// the single motion-resolution source of truth that both [`apply_motion`]
2874    /// (move the cursor *to* the target) and [`apply_operator`] (use the target
2875    /// as the *other end* of an operated range) stand on. `None` only if there
2876    /// is no active buffer.
2877    ///
2878    /// [`apply_motion`]: Self::apply_motion
2879    /// [`apply_operator`]: Self::apply_operator
2880    fn resolve_motion(&self, from: Position, motion: Motion) -> Option<Position> {
2881        let buf = self.buffers.get(self.active)?;
2882        let pos = from;
2883        Some(match motion {
2884            // Search-as-motion: what makes `dn` / `d/foo<CR>` work. Resolved
2885            // against the committed match list, so it is `None` (motion fails,
2886            // operator aborts, buffer untouched) when nothing is committed —
2887            // never a silent move to 0, which would delete to the file start.
2888            Motion::SearchNext | Motion::SearchPrev => {
2889                let at = buf.position_to_char(pos).ok()?;
2890                let step = self
2891                    .search
2892                    .repeat(at, matches!(motion, Motion::SearchPrev))?;
2893                buf.char_to_position(step.target.start)
2894            }
2895            Motion::Left => Position::new(pos.line, pos.column.saturating_sub(1)),
2896            Motion::Right => Position::new(pos.line, pos.column.saturating_add(1)),
2897            Motion::Up => Position::new(pos.line.saturating_sub(1), pos.column),
2898            Motion::Down => Position::new(pos.line.saturating_add(1), pos.column),
2899            Motion::LineStart => Position::new(pos.line, 0),
2900            Motion::LineEnd => Position::new(pos.line, buf.line_len_chars(pos.line)),
2901            Motion::LineFirstNonBlank => first_non_blank(buf, pos.line),
2902            Motion::DocStart => Position::ZERO,
2903            Motion::DocEnd => Position::new(
2904                buf.line_count().saturating_sub(1),
2905                buf.line_len_chars(buf.line_count().saturating_sub(1)),
2906            ),
2907            Motion::WordStartNext | Motion::WordEndNext => word_next(buf, pos),
2908            Motion::WordStartPrev => word_prev(buf, pos),
2909            Motion::PageDown | Motion::HalfPageDown => {
2910                Position::new(pos.line.saturating_add(10), pos.column)
2911            }
2912            Motion::PageUp | Motion::HalfPageUp => {
2913                Position::new(pos.line.saturating_sub(10), pos.column)
2914            }
2915            Motion::GotoLine(n) => Position::new(n.saturating_sub(1), 0),
2916            // Structural Lisp motions — stubs for phase 1.B; full paredit
2917            // semantics land when caixa-ast is wired to the active buffer.
2918            Motion::ForwardSexp
2919            | Motion::BackwardSexp
2920            | Motion::UpList
2921            | Motion::DownList
2922            | Motion::BeginningOfDefun
2923            | Motion::EndOfDefun
2924            | Motion::BeginningOfSexp
2925            | Motion::EndOfSexp => pos,
2926        })
2927    }
2928
2929    fn apply_motion(&mut self, motion: Motion) {
2930        // A bare search motion is a FAR JUMP and it REPORTS — it records into
2931        // the jumplist, prints vim's "hit BOTTOM" on a wrap, and says E486
2932        // when nothing matches. `resolve_motion` can do none of that: it is
2933        // deliberately pure because the OPERATOR path calls it to find a range
2934        // without moving the cursor. So `n` routes to the one executor that
2935        // owns those side effects, and `Action::SearchRepeat` routes to the
2936        // same place — one code path, two spellings.
2937        if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
2938            self.jump_search(matches!(motion, Motion::SearchPrev));
2939            return;
2940        }
2941        let Some(pos) = self.resolve_motion(self.cursor(), motion) else {
2942            return;
2943        };
2944        // The single cursor-mutation path clamps to the buffer and scrolls
2945        // the viewport to contain the cursor on both axes.
2946        self.set_cursor(pos);
2947    }
2948
2949    /// Apply an operator over a motion — the vim `{operator}{motion}` verbs
2950    /// (`dw` delete-word, `c$` change-to-line-end, `y0` yank-to-line-start).
2951    /// Composition is explicit: the motion resolves a target via
2952    /// [`resolve_motion`](Self::resolve_motion); the operator acts over the
2953    /// `[cursor, target)` range. Register-leaving operators
2954    /// ([`Operator::leaves_register`]) capture the text first.
2955    /// Apply `op` over `motion` resolved `n` times from the cursor.
2956    ///
2957    /// `n == 1` is the ordinary path. Larger `n` walks the motion forward
2958    /// first and operates over the whole span in one go, which is what vim
2959    /// means by `3dw` — and the only way a non-moving operator like yank can
2960    /// honour a count at all.
2961    fn apply_operator_n(&mut self, op: Operator, motion: Motion, n: u32) {
2962        if n <= 1 {
2963            self.apply_operator(op, motion);
2964            return;
2965        }
2966        let from = self.cursor();
2967        let mut to = from;
2968        for _ in 0..n {
2969            match self.resolve_motion(to, motion) {
2970                Some(next) if next != to => to = next,
2971                // The motion stopped making progress (start/end of buffer):
2972                // operate over what we reached rather than aborting, which is
2973                // what vim does for `999dw` near the end of a file.
2974                _ => break,
2975            }
2976        }
2977        if to == from {
2978            // Nothing to operate over. Fall through to the single-step path
2979            // so its error reporting (E35, pattern-not-found) still runs.
2980            self.apply_operator(op, motion);
2981            return;
2982        }
2983        self.apply_operator_to(op, to);
2984    }
2985
2986    fn apply_operator(&mut self, op: Operator, motion: Motion) {
2987        let from = self.cursor();
2988        let Some(to) = self.resolve_motion(from, motion) else {
2989            // A motion that cannot resolve aborts the operator with the buffer
2990            // untouched. A search motion says WHY — `dn` with no pattern armed
2991            // is otherwise indistinguishable from a dropped keystroke, which
2992            // is the same complaint that motivated E486 on the bare path.
2993            if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
2994                if self.search.pattern().is_none() {
2995                    self.messages
2996                        .push("E35: No previous regular expression".to_string());
2997                } else {
2998                    self.report_pattern_not_found();
2999                }
3000            }
3001            return;
3002        };
3003        self.apply_operator_to(op, to);
3004    }
3005
3006    /// Apply `op` over `[cursor, to)`.
3007    ///
3008    /// Split out of [`Self::apply_operator`] so the operated-search path can
3009    /// reach the same range machinery with a target it resolved itself — the
3010    /// alternative was a second copy of the delete/yank/register logic, which
3011    /// is how the two would drift.
3012    fn apply_operator_to(&mut self, op: Operator, to: Position) {
3013        let from = self.cursor();
3014        self.apply_operator_over(
3015            op,
3016            Range {
3017                start: from,
3018                end: to,
3019            },
3020        );
3021    }
3022
3023    /// Apply `op` over an explicit range.
3024    ///
3025    /// The object path needs this: `gn`'s extent need not begin at the cursor,
3026    /// so it cannot go through the `[cursor, target)` shape the motion path
3027    /// uses. One implementation of the delete/yank/register logic, reached two
3028    /// ways.
3029    fn apply_operator_over(&mut self, op: Operator, range: Range) {
3030        let range = range.normalized();
3031        if range.is_empty() {
3032            return;
3033        }
3034        // Capture the operated text (for the register) before mutating.
3035        let text = self
3036            .buffers
3037            .get(self.active)
3038            .and_then(|buf| buf.slice(range).ok());
3039        if op.leaves_register() {
3040            if let Some(t) = &text {
3041                self.register = Some(t.clone());
3042            }
3043        }
3044        match op {
3045            // Delete + Change remove the range; Change then enters Insert so
3046            // the operator pairs with immediate typing (`ciw`, `c$`).
3047            Operator::Delete | Operator::Change => {
3048                if let Some(buf) = self.buffers.get_mut(self.active) {
3049                    let _ = buf.apply(&Edit::delete(range));
3050                }
3051                self.set_cursor(range.start);
3052                if op == Operator::Change {
3053                    self.modal.enter(Mode::Insert);
3054                }
3055            }
3056            // Yank copies to the register without mutating the buffer; vim
3057            // leaves the cursor at the range start.
3058            Operator::Yank => {
3059                self.set_cursor(range.start);
3060            }
3061            // Indent/Format/structural operators are not yet wired — named,
3062            // not faked (no buffer mutation, register already captured for the
3063            // register-leaving ones above).
3064            _ => {
3065                self.messages
3066                    .push("operator not yet implemented".to_owned());
3067            }
3068        }
3069    }
3070
3071    /// The text last yanked or deleted into the unnamed register, if any.
3072    /// The future `p`/`P` paste reads this.
3073    #[must_use]
3074    pub fn register(&self) -> Option<&str> {
3075        self.register.as_deref()
3076    }
3077
3078    fn insert_char(&mut self, c: char) {
3079        if self.modal.mode() == Mode::Command {
3080            // A search prompt and an ex-command share Command mode (vim's
3081            // cmdline). `search.is_prompting()` is the typed discriminator —
3082            // it can only be true when `/` or `?` actually opened a prompt.
3083            if self.search.is_prompting() {
3084                // The search prompt is the SOLE store while it is open.
3085                //
3086                // This used to also `push_minibuffer(c)`, and the two stores
3087                // insert differently — `search.push` at the caret, the
3088                // minibuffer always at the end — so `/fo<Left>X` left them
3089                // reading `fXo` and `foX`. That was one of FIVE desync paths;
3090                // the caret moves, forward-delete, delete-word and
3091                // clear-to-start never touched the shadow at all.
3092                //
3093                // Deleting the write costs nothing because `status_model`
3094                // already selects the minibuffer only on the `prompt == None`
3095                // branch — the shadow is the EX-LINE's store, and while a
3096                // search prompt is open nothing reads it.
3097                self.search.push(c);
3098                self.preview_search();
3099            } else {
3100                self.modal.push_minibuffer(c);
3101            }
3102            return;
3103        }
3104        let cursor = self.cursor();
3105        let Some(buf) = self.buffers.get_mut(self.active) else {
3106            return;
3107        };
3108        let edit = Edit::insert(cursor, c.to_string());
3109        if buf.apply(&edit).is_ok() {
3110            let next = if c == '\n' {
3111                Position::new(cursor.line.saturating_add(1), 0)
3112            } else {
3113                cursor.shift_right(1)
3114            };
3115            // Route through the single cursor-mutation path so the viewport
3116            // follows the cursor (both axes) and the cursor stays clamped.
3117            self.set_cursor(next);
3118        }
3119    }
3120
3121    /// Backspace inside a prompt. Keeps the search buffer and the displayed
3122    /// minibuffer in lockstep — if only one shrank, the pattern submitted
3123    /// would differ from the text on screen.
3124    fn prompt_backspace(&mut self) -> bool {
3125        if self.modal.mode() != Mode::Command {
3126            return false;
3127        }
3128        if self.search.is_prompting() {
3129            // Backspacing past the `/` closes the prompt, as vim does. No
3130            // `pop_minibuffer` here for the same reason as `insert_char`: the
3131            // shadow is the ex-line's, and popping its TAIL when the caret is
3132            // mid-pattern was another desync path.
3133            if self.search.backspace() {
3134                self.modal.clear_minibuffer();
3135                self.modal.enter(Mode::Normal);
3136            }
3137            // Never `pop_minibuffer` on the search path: it pops the TAIL,
3138            // while `search.backspace()` removes the char before the CARET.
3139            return true;
3140        }
3141        self.modal.pop_minibuffer();
3142        true
3143    }
3144
3145    fn submit_command(&mut self) {
3146        // Read the command line BEFORE leaving Command mode — the minibuffer
3147        // exists only in the `Command` variant, so the escape must come
3148        // after the capture.
3149        let line = self.modal.minibuffer().to_string();
3150        self.modal.escape();
3151        let (name, args) = parse_command_line(&line);
3152        if name.is_empty() {
3153            return;
3154        }
3155        self.run_command(&name, &args);
3156    }
3157
3158    fn run_command(&mut self, name: &str, args: &[String]) {
3159        // Bound the command -> RunCommand slip -> command cycle. Refused and
3160        // reported, never a stack overflow: an editor that dies under the
3161        // operator loses their buffer, and a script that loops is a mistake
3162        // they should be told about, not punished for.
3163        if self.dispatch_depth >= Self::MAX_DISPATCH_DEPTH {
3164            let mut m = String::from("command recursion too deep at `");
3165            m.push_str(name);
3166            m.push_str("` — refusing");
3167            self.messages.push(m);
3168            self.damage = self.damage.join(Damage::Viewport);
3169            self.bump_gen();
3170            return;
3171        }
3172        self.dispatch_depth += 1;
3173        self.run_command_inner(name, args);
3174        self.dispatch_depth -= 1;
3175    }
3176
3177    /// How many nested command dispatches are allowed. Deep enough that no
3178    /// legitimate script notices, shallow enough to fail fast.
3179    const MAX_DISPATCH_DEPTH: u8 = 8;
3180
3181    fn run_command_inner(&mut self, name: &str, args: &[String]) {
3182        // Lazy-activation seam (lazy.nvim `cmd =` model): a user plugin
3183        // gated on `Command: <name>` has its entry applied the first time
3184        // that command runs, BEFORE dispatch — so the activated plugin
3185        // can register the very command being invoked and it resolves on
3186        // this same call.
3187        if self.plugin_host.pending() > 0 {
3188            let pending = self.plugin_host.pending_for_command(name);
3189            for src in pending {
3190                self.apply_plugin_entry(&src);
3191            }
3192        }
3193        // Read through the counter, then interpret. Two immutable borrows of
3194        // `self` (the window and the registry) coexist; the `&mut` comes
3195        // afterwards, once the outcome is owned. That sequencing IS the
3196        // seam: there is no moment where a command body and `&mut self` are
3197        // live at the same time.
3198        let outcome = {
3199            let window = self.window();
3200            self.commands.run(name, &window, args)
3201        };
3202        match outcome {
3203            Ok(o) => self.interpret(o),
3204            // Reported, never fatal (Phase 0). A failed command must not
3205            // take the editor down, but it must not be invisible either.
3206            Err(e) => {
3207                self.messages.push(describe_command_failure(name, &e));
3208                self.damage = self.damage.join(Damage::Viewport);
3209                self.bump_gen();
3210            }
3211        }
3212    }
3213
3214    // ── tatara-lisp runtime bridge (imperative programmability tier) ──
3215
3216    /// Capture a read snapshot of the editor for the tatara-lisp host.
3217    /// Lisp reads (`cursor-line`, `current-line`, …) answer from this.
3218    #[must_use]
3219    pub fn snapshot(&self) -> EditorSnapshot {
3220        let current_line = self
3221            .buffers
3222            .get(self.active)
3223            .and_then(|b| b.line(self.cursor().line))
3224            .map(|s| s.trim_end_matches('\n').to_string())
3225            .unwrap_or_default();
3226        let buffer_name = self
3227            .buffers
3228            .get(self.active)
3229            .and_then(|b| b.path.as_ref())
3230            .map(|p| p.display().to_string())
3231            .unwrap_or_else(|| "[scratch]".to_string());
3232        EditorSnapshot {
3233            cursor_line: i64::from(self.cursor().line),
3234            cursor_column: i64::from(self.cursor().column),
3235            current_line,
3236            mode: self.modal.mode().as_str().to_string(),
3237            buffer_name,
3238        }
3239    }
3240
3241    /// Evaluate tatara-lisp `src` against this editor: capture a
3242    /// snapshot, run it in the embedded VM, then apply the typed effects
3243    /// the program emitted. This is the imperative programmability tier
3244    /// — live Lisp that reads state and drives the editor through the
3245    /// sandboxed effect boundary.
3246    ///
3247    /// **Snapshot semantics:** the read snapshot is captured ONCE before
3248    /// eval, and effects are applied AFTER the program returns. So within
3249    /// a single `run_lisp` call a program cannot observe its own writes —
3250    /// `(insert "x") (cursor-column)` reads the pre-insert column. This
3251    /// snapshot-isolation is deliberate (it's what makes the effect
3252    /// boundary a clean sandbox seam); a program that must read its own
3253    /// effects splits the work across calls. The VM is cached
3254    /// ([`Self::lisp_vm`]) so the stdlib is installed once and top-level
3255    /// `define`s persist across calls (REPL-like).
3256    pub fn run_lisp(&mut self, src: &str) -> Result<(), VmError> {
3257        let mut host = EscribaHost::with_snapshot(self.snapshot());
3258        let vm = self.lisp_vm.get_or_insert_with(EscribaVm::new);
3259        vm.eval(src, &mut host)?;
3260        let effects = host.take_effects();
3261        self.apply_host_effects(effects);
3262        Ok(())
3263    }
3264
3265    /// Apply tatara-lisp effects to live editor state.
3266    ///
3267    /// A thin adapter now. It used to be `apply_host_effects`, a THIRD
3268    /// implementation of message-push / option-insert / insert-text beside
3269    /// the Action executor and the slip interpreter — the same duplication
3270    /// that let `u` and `:undo` drift apart in M3. The VM emits slips; this
3271    /// hands them to the one interpreter.
3272    pub fn apply_host_effects(&mut self, effects: Vec<Negai>) {
3273        self.interpret(Outcome::did(effects));
3274    }
3275
3276    /// Insert a (possibly multi-line) string at the cursor and advance
3277    /// the cursor past it. Used by the `(insert …)` effect.
3278    fn insert_text(&mut self, text: &str) {
3279        if text.is_empty() {
3280            return;
3281        }
3282        let cursor = self.cursor();
3283        let Some(buf) = self.buffers.get_mut(self.active) else {
3284            return;
3285        };
3286        let edit = Edit::insert(cursor, text.to_string());
3287        if buf.apply(&edit).is_ok() {
3288            let next = if let Some(nl) = text.rfind('\n') {
3289                let added_lines = u32::try_from(text.matches('\n').count()).unwrap_or(0);
3290                let last_line_len = u32::try_from(text[nl + 1..].chars().count()).unwrap_or(0);
3291                Position::new(cursor.line + added_lines, last_line_len)
3292            } else {
3293                let n = u32::try_from(text.chars().count()).unwrap_or(0);
3294                cursor.shift_right(n)
3295            };
3296            // Route through the single cursor-mutation path so the viewport
3297            // follows the cursor (both axes) and the cursor stays clamped.
3298            self.set_cursor(next);
3299        }
3300    }
3301}
3302
3303fn first_non_blank(buf: &escriba_buffer::Buffer, line: u32) -> Position {
3304    let Some(text) = buf.line(line) else {
3305        return Position::new(line, 0);
3306    };
3307    let col = text
3308        .chars()
3309        .take_while(|c| c.is_whitespace() && *c != '\n')
3310        .count();
3311    Position::new(line, u32::try_from(col).unwrap_or(0))
3312}
3313
3314fn word_next(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
3315    let Some(text) = buf.line(pos.line) else {
3316        return pos;
3317    };
3318    let chars: Vec<char> = text.chars().collect();
3319    let start = pos.column as usize;
3320    let mut i = start;
3321    while i < chars.len() && !chars[i].is_whitespace() {
3322        i += 1;
3323    }
3324    while i < chars.len() && chars[i].is_whitespace() {
3325        i += 1;
3326    }
3327    if i >= chars.len() {
3328        // No more words on this line — jump to next line.
3329        if pos.line + 1 < buf.line_count() {
3330            return Position::new(pos.line + 1, 0);
3331        }
3332    }
3333    Position::new(pos.line, u32::try_from(i).unwrap_or(pos.column))
3334}
3335
3336fn word_prev(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
3337    let Some(text) = buf.line(pos.line) else {
3338        return pos;
3339    };
3340    let chars: Vec<char> = text.chars().collect();
3341    let mut i = (pos.column as usize).min(chars.len());
3342    while i > 0 && chars[i - 1].is_whitespace() {
3343        i -= 1;
3344    }
3345    while i > 0 && !chars[i - 1].is_whitespace() {
3346        i -= 1;
3347    }
3348    Position::new(pos.line, u32::try_from(i).unwrap_or(0))
3349}
3350
3351fn parse_command_line(line: &str) -> (String, Vec<String>) {
3352    let mut parts = line.split_whitespace();
3353    let Some(first) = parts.next() else {
3354        return (String::new(), Vec::new());
3355    };
3356    let head = first.strip_prefix(':').unwrap_or(first);
3357    let name = match head {
3358        "w" => "save",
3359        "q" => "quit",
3360        "u" => "undo",
3361        other => other,
3362    };
3363    (name.to_string(), parts.map(str::to_string).collect())
3364}
3365
3366#[cfg(test)]
3367mod tests {
3368    use super::*;
3369    use madori::event::{KeyCode, KeyEvent, Modifiers};
3370
3371    // ── search wiring (escriba-search integration) ────────────────────
3372    //
3373    // The engine is proven in escriba-search's own 61 tests. These prove the
3374    // WIRING: that keys reach it, that the cursor lands where it says, and
3375    // that a search prompt and an ex-command can share Command mode without
3376    // being confused for one another.
3377
3378    fn type_search(st: &mut EditorState, dir: SearchDirection, pat: &str) {
3379        st.apply(&Action::SearchOpen(dir));
3380        for c in pat.chars() {
3381            st.apply(&Action::InsertChar(c));
3382        }
3383        st.apply(&Action::SubmitCommand);
3384    }
3385
3386    #[test]
3387    fn slash_search_moves_the_cursor_to_the_match() {
3388        let mut st = new_state_with("alpha\nbravo\ncharlie\n");
3389        type_search(&mut st, SearchDirection::Forward, "charlie");
3390        assert_eq!(st.cursor().line, 2, "cursor lands on the matching line");
3391        assert_eq!(st.modal.mode(), Mode::Normal, "prompt closes on submit");
3392        assert_eq!(st.search.matches().len(), 1);
3393    }
3394
3395    #[test]
3396    // `N` is a DIFFERENT vim key from `n` — see escriba-search.
3397    #[allow(non_snake_case)]
3398    fn n_and_N_walk_matches_in_both_directions() {
3399        let mut st = new_state_with("foo\nbar\nfoo\nbaz\nfoo\n");
3400        type_search(&mut st, SearchDirection::Forward, "foo");
3401        let first = st.cursor().line;
3402        st.apply(&Action::SearchRepeat { reverse: false });
3403        let second = st.cursor().line;
3404        assert!(second > first, "n advances ({first} -> {second})");
3405        st.apply(&Action::SearchRepeat { reverse: true });
3406        assert_eq!(st.cursor().line, first, "N comes back");
3407    }
3408
3409    #[test]
3410    fn star_searches_the_word_under_the_cursor() {
3411        let mut st = new_state_with("needle\nhaystack\nneedle\n");
3412        st.apply(&Action::SearchWord { reverse: false });
3413        assert_eq!(st.search.pattern().unwrap().raw(), r"\bneedle\b");
3414        assert_eq!(st.cursor().line, 2, "jumps to the other occurrence");
3415    }
3416
3417    #[test]
3418    fn escape_abandons_the_prompt_and_keeps_the_previous_search() {
3419        let mut st = new_state_with("foo\nbar\nfoo\n");
3420        type_search(&mut st, SearchDirection::Forward, "foo");
3421        let matches_before = st.search.matches().len();
3422
3423        st.apply(&Action::SearchOpen(SearchDirection::Forward));
3424        st.apply(&Action::InsertChar('z'));
3425        st.apply(&Action::ChangeMode(Mode::Normal));
3426
3427        assert!(!st.search.is_prompting(), "prompt gone");
3428        assert_eq!(
3429            st.search.pattern().unwrap().raw(),
3430            "foo",
3431            "old pattern survives"
3432        );
3433        assert_eq!(
3434            st.search.matches().len(),
3435            matches_before,
3436            "old highlights survive"
3437        );
3438    }
3439
3440    #[test]
3441    fn a_search_prompt_and_an_ex_command_are_not_confused() {
3442        let mut st = new_state_with("foo\n");
3443        // No `/` pressed: Command mode belongs to the ex-command line.
3444        st.apply(&Action::ChangeMode(Mode::Command));
3445        assert!(!st.search.is_prompting(), "`:` must not open a search");
3446        st.apply(&Action::InsertChar('w'));
3447        assert!(
3448            st.search.prompt().is_none(),
3449            "typed char went to the ex line"
3450        );
3451    }
3452
3453    #[test]
3454    fn a_missing_pattern_reports_instead_of_failing_silently() {
3455        let mut st = new_state_with("alpha\nbravo\n");
3456        type_search(&mut st, SearchDirection::Forward, "zzz");
3457        assert!(
3458            st.messages.iter().any(|m| m.contains("E486")),
3459            "must report not-found, got {:?}",
3460            st.messages
3461        );
3462    }
3463
3464    #[test]
3465    fn n_without_any_search_reports_rather_than_moving() {
3466        let mut st = new_state_with("alpha\nbravo\n");
3467        let before = st.cursor();
3468        st.apply(&Action::SearchRepeat { reverse: false });
3469        assert_eq!(st.cursor(), before, "cursor must not move");
3470        assert!(
3471            st.messages.iter().any(|m| m.contains("E35")),
3472            "got {:?}",
3473            st.messages
3474        );
3475    }
3476
3477    #[test]
3478    fn search_as_a_motion_composes_with_an_operator() {
3479        // The point of Motion::SearchNext: `d` + search deletes to the match.
3480        let mut st = new_state_with("alpha bravo charlie\n");
3481        type_search(&mut st, SearchDirection::Forward, "charlie");
3482        st.set_cursor(Position::new(0, 0));
3483        let target = st.resolve_motion(Position::new(0, 0), Motion::SearchNext);
3484        assert!(target.is_some(), "search must resolve as a motion");
3485        assert_eq!(target.unwrap().column, 12, "at `charlie`");
3486    }
3487
3488    #[test]
3489    fn search_motion_without_a_pattern_fails_the_motion_instead_of_moving_to_zero() {
3490        // A silent fallback to offset 0 would make `d` + search delete to the
3491        // start of the file — the worst possible failure for an operator.
3492        let st = new_state_with("alpha bravo\n");
3493        assert!(
3494            st.resolve_motion(Position::new(0, 5), Motion::SearchNext)
3495                .is_none()
3496        );
3497    }
3498
3499    #[test]
3500    fn clear_highlight_keeps_the_pattern_usable() {
3501        let mut st = new_state_with("foo\nbar\nfoo\n");
3502        type_search(&mut st, SearchDirection::Forward, "foo");
3503        st.apply(&Action::ClearSearchHighlight);
3504        assert!(st.search.highlights().is_empty(), "nothing lit");
3505        st.apply(&Action::SearchRepeat { reverse: false });
3506        assert!(st.search.pattern().is_some(), "but n still works");
3507    }
3508
3509    #[test]
3510    fn typing_previews_incrementally_before_commit() {
3511        let mut st = new_state_with("alpha\nbravo\ncharlie\n");
3512        st.apply(&Action::SearchOpen(SearchDirection::Forward));
3513        for c in "charlie".chars() {
3514            st.apply(&Action::InsertChar(c));
3515        }
3516        // incsearch: the cursor has already moved, with nothing committed.
3517        assert_eq!(st.cursor().line, 2, "preview moved the cursor");
3518        assert!(st.search.pattern().is_none(), "but nothing is committed");
3519    }
3520
3521    #[test]
3522    fn backspace_corrects_the_prompt_and_reruns_the_preview() {
3523        let mut st = new_state_with("alpha\nbravo\n");
3524        st.apply(&Action::SearchOpen(SearchDirection::Forward));
3525        for c in "bravox".chars() {
3526            st.apply(&Action::InsertChar(c));
3527        }
3528        assert_eq!(st.search.prompt().unwrap().text(), "bravox");
3529        st.apply(&Action::PromptBackspace);
3530        assert_eq!(
3531            st.search.prompt().unwrap().text(),
3532            "bravo",
3533            "typo corrected"
3534        );
3535        assert_eq!(
3536            st.status_model().prompt_text,
3537            "bravo",
3538            "the model reads the PROMPT — the minibuffer is the ex-line's store",
3539        );
3540        assert_eq!(st.cursor().line, 1, "preview re-ran and found it");
3541    }
3542
3543    #[test]
3544    fn backspacing_past_the_slash_closes_the_prompt() {
3545        let mut st = new_state_with("alpha\n");
3546        st.apply(&Action::SearchOpen(SearchDirection::Forward));
3547        st.apply(&Action::InsertChar('a'));
3548        st.apply(&Action::PromptBackspace);
3549        st.apply(&Action::PromptBackspace);
3550        assert!(!st.search.is_prompting(), "prompt closed");
3551        assert_eq!(st.modal.mode(), Mode::Normal);
3552    }
3553
3554    #[test]
3555    fn noh_clears_highlights_and_keeps_the_pattern() {
3556        let mut st = new_state_with("foo\nbar\nfoo\n");
3557        type_search(&mut st, SearchDirection::Forward, "foo");
3558        assert!(!st.search.highlights().is_empty());
3559        st.run_command("noh", &[]);
3560        assert!(st.search.highlights().is_empty(), ":noh turns them off");
3561        assert!(st.search.pattern().is_some(), "but n still works");
3562    }
3563
3564    #[test]
3565    fn noh_accepts_the_vim_aliases() {
3566        for name in ["noh", "nohl", "nohlsearch"] {
3567            let mut st = new_state_with("foo\nfoo\n");
3568            type_search(&mut st, SearchDirection::Forward, "foo");
3569            st.run_command(name, &[]);
3570            assert!(st.search.highlights().is_empty(), "{name} must clear");
3571        }
3572    }
3573
3574    #[test]
3575    fn backspace_on_the_ex_line_does_not_touch_search_state() {
3576        let mut st = new_state_with("foo\n");
3577        st.apply(&Action::ChangeMode(Mode::Command));
3578        st.apply(&Action::InsertChar('w'));
3579        st.apply(&Action::InsertChar('q'));
3580        st.apply(&Action::PromptBackspace);
3581        assert_eq!(st.status_model().prompt_text, "w");
3582        assert!(st.search.prompt().is_none(), "no search was involved");
3583    }
3584
3585    #[test]
3586    fn up_arrow_recalls_the_previous_search() {
3587        let mut st = new_state_with("alpha\nbravo\n");
3588        type_search(&mut st, SearchDirection::Forward, "bravo");
3589        st.apply(&Action::SearchOpen(SearchDirection::Forward));
3590        st.apply(&Action::PromptHistory { back: true });
3591        assert_eq!(st.search.prompt().unwrap().text(), "bravo");
3592        assert_eq!(
3593            st.status_model().prompt_text,
3594            "bravo",
3595            "display follows the prompt"
3596        );
3597    }
3598
3599    #[test]
3600    fn arrowing_back_down_restores_the_half_typed_pattern() {
3601        let mut st = new_state_with("alpha\nbravo\n");
3602        type_search(&mut st, SearchDirection::Forward, "bravo");
3603        st.apply(&Action::SearchOpen(SearchDirection::Forward));
3604        st.apply(&Action::InsertChar('a'));
3605        st.apply(&Action::PromptHistory { back: true });
3606        assert_eq!(st.search.prompt().unwrap().text(), "bravo");
3607        st.apply(&Action::PromptHistory { back: false });
3608        assert_eq!(
3609            st.search.prompt().unwrap().text(),
3610            "a",
3611            "the draft comes back"
3612        );
3613        assert_eq!(st.status_model().prompt_text, "a");
3614    }
3615
3616    #[test]
3617    fn history_arrows_do_nothing_on_the_ex_line() {
3618        let mut st = new_state_with("alpha\n");
3619        st.apply(&Action::ChangeMode(Mode::Command));
3620        st.apply(&Action::InsertChar('w'));
3621        st.apply(&Action::PromptHistory { back: true });
3622        assert_eq!(st.status_model().prompt_text, "w", "ex line untouched");
3623    }
3624
3625    // ── trouble.* — the findings view ────────────────────────────────
3626    //
3627    // These assert on the ROWS the picker would be built from, not on the
3628    // registry: the registry is already tested, and what could be wrong
3629    // here is the projection — scoping, freshness, and whether a row goes
3630    // anywhere when pressed.
3631
3632    fn finding_at(buffer: BufferId, line: u32, msg: &str) -> escriba_shirube::Finding {
3633        use escriba_core::{Position, Range};
3634        escriba_shirube::Finding::new(
3635            escriba_shirube::Site::in_buffer(
3636                buffer,
3637                Range::new(Position::new(line, 0), Position::new(line, 1)),
3638            ),
3639            escriba_shirube::Severity::Error,
3640            msg.to_string(),
3641            escriba_shirube::Origin::Text("test"),
3642        )
3643    }
3644
3645    #[test]
3646    fn published_findings_become_picker_rows() {
3647        let mut st = new_state_with("a\nb\nc\n");
3648        let world = st.world();
3649        st.results.publish(
3650            "test",
3651            escriba_shirube::ResultList::new(vec![finding_at(st.active, 1, "boom")], world),
3652        );
3653        let rows = st.finding_items(true, None);
3654        assert_eq!(rows.len(), 1, "the published finding produces a row");
3655        // The row must SAY something an operator can act on: severity,
3656        // 1-based line, and the message.
3657        let label = &rows[0].label;
3658        assert!(label.contains("ERROR"), "{label}");
3659        assert!(label.contains(":2"), "lines are 1-based on screen: {label}");
3660        assert!(label.contains("boom"), "{label}");
3661    }
3662
3663    #[test]
3664    fn a_stale_list_contributes_no_rows() {
3665        // THE load-bearing one. A list anchored to a revision the buffer has
3666        // moved past must vanish from the view rather than offer a line that
3667        // has since shifted — which is the whole reason findings carry an
3668        // anchor instead of just a position.
3669        let mut st = new_state_with("a\nb\nc\n");
3670        let world = st.world();
3671        st.results.publish(
3672            "test",
3673            escriba_shirube::ResultList::new(vec![finding_at(st.active, 1, "boom")], world),
3674        );
3675        assert_eq!(st.finding_items(true, None).len(), 1, "fresh to begin with");
3676
3677        st.apply(&Action::InsertChar('x'));
3678        assert!(
3679            st.finding_items(true, None).is_empty(),
3680            "an edit moved the text on; the list is stale and must not be shown"
3681        );
3682    }
3683
3684    #[test]
3685    fn document_scope_excludes_another_buffer() {
3686        // `trouble.document` vs `trouble.workspace` is one bool, so this is
3687        // the only thing that can distinguish them.
3688        let mut st = new_state_with("a\nb\n");
3689        let other = st.buffers.scratch("z\n");
3690        let world = st.world();
3691        st.results.publish(
3692            "test",
3693            escriba_shirube::ResultList::new(
3694                vec![
3695                    finding_at(st.active, 0, "mine"),
3696                    finding_at(other, 0, "theirs"),
3697                ],
3698                world,
3699            ),
3700        );
3701        let ws = st.finding_items(true, None);
3702        assert_eq!(ws.len(), 2, "workspace scope shows both");
3703        let doc = st.finding_items(false, None);
3704        assert_eq!(doc.len(), 1, "document scope shows only the active buffer");
3705        assert!(doc[0].label.contains("mine"), "{}", doc[0].label);
3706    }
3707
3708    #[test]
3709    fn files_under_a_root_produces_rows() {
3710        // `files.open-parent` differs from `files.open` only in the root, so
3711        // what must hold is that a root is actually honoured.
3712        let mut st = new_state_with("");
3713        let rows = st.file_items(std::path::Path::new("."));
3714        assert!(!rows.is_empty(), "the working directory has files");
3715    }
3716
3717    // ── vim text objects ─────────────────────────────────────────────
3718    //
3719    // Asserted through `apply` on real buffer text, so a wrong RANGE shows
3720    // up as wrong text rather than as a range that merely looks plausible.
3721
3722    fn after(text: &str, line: u32, col: u32, act: Action) -> String {
3723        let mut st = new_state_with(text);
3724        st.set_cursor(Position::new(line, col));
3725        st.apply(&act);
3726        st.buffers
3727            .get(st.active)
3728            .map(|b| b.to_string())
3729            .unwrap_or_default()
3730    }
3731
3732    fn del_obj(o: escriba_core::TextObject) -> Action {
3733        Action::ApplyOperatorObject {
3734            op: escriba_core::Operator::Delete,
3735            object: o,
3736        }
3737    }
3738
3739    #[test]
3740    fn dd_removes_the_line_not_just_its_contents() {
3741        // The distinction the newline makes: without it, `dd` blanks a line
3742        // and leaves it behind.
3743        let got = after("a\nb\nc\n", 1, 0, del_obj(escriba_core::TextObject::Line));
3744        assert_eq!(got, "a\nc\n");
3745    }
3746
3747    #[test]
3748    fn dd_on_the_last_line_leaves_no_blank_behind() {
3749        // The case a naive start-of-line..start-of-next range gets wrong:
3750        // there is no following newline to take, so it must take the
3751        // preceding one.
3752        let got = after("a\nb\nc\n", 2, 0, del_obj(escriba_core::TextObject::Line));
3753        assert_eq!(got, "a\nb\n", "no trailing empty line: {got:?}");
3754    }
3755
3756    #[test]
3757    fn dd_on_the_only_line_clears_it_but_keeps_the_line() {
3758        let got = after("solo\n", 0, 2, del_obj(escriba_core::TextObject::Line));
3759        assert!(got.starts_with('\n') || got.is_empty(), "{got:?}");
3760    }
3761
3762    #[test]
3763    fn diw_takes_the_word_and_daw_takes_its_trailing_space() {
3764        let inner = after(
3765            "one two three\n",
3766            0,
3767            5,
3768            del_obj(escriba_core::TextObject::Word { around: false }),
3769        );
3770        assert_eq!(inner, "one  three\n", "iw leaves both spaces");
3771        let around = after(
3772            "one two three\n",
3773            0,
3774            5,
3775            del_obj(escriba_core::TextObject::Word { around: true }),
3776        );
3777        assert_eq!(around, "one three\n", "aw takes the trailing space");
3778    }
3779
3780    #[test]
3781    fn iw_from_any_column_inside_the_word_takes_the_whole_word() {
3782        for col in 4..=6 {
3783            let got = after(
3784                "one two three\n",
3785                0,
3786                col,
3787                del_obj(escriba_core::TextObject::Word { around: false }),
3788            );
3789            assert_eq!(got, "one  three\n", "from column {col}");
3790        }
3791    }
3792
3793    #[test]
3794    fn iw_on_punctuation_takes_the_punctuation_run() {
3795        // vim's three classes: word / punctuation / whitespace. A `::` is a
3796        // run of punctuation, not part of either identifier.
3797        let got = after(
3798            "foo::bar\n",
3799            0,
3800            3,
3801            del_obj(escriba_core::TextObject::Word { around: false }),
3802        );
3803        assert_eq!(got, "foobar\n");
3804    }
3805
3806    #[test]
3807    fn i_paren_takes_the_inside_and_a_paren_takes_the_brackets_too() {
3808        let inner = after(
3809            "f(a, b)\n",
3810            0,
3811            3,
3812            del_obj(escriba_core::TextObject::Delimited {
3813                open: '(',
3814                close: ')',
3815                around: false,
3816            }),
3817        );
3818        assert_eq!(inner, "f()\n");
3819        let around = after(
3820            "f(a, b)\n",
3821            0,
3822            3,
3823            del_obj(escriba_core::TextObject::Delimited {
3824                open: '(',
3825                close: ')',
3826                around: true,
3827            }),
3828        );
3829        assert_eq!(around, "f\n");
3830    }
3831
3832    #[test]
3833    fn nested_brackets_resolve_to_the_enclosing_pair() {
3834        // THE reason the bracket scan counts depth: an inner pair must not
3835        // terminate the search for the one the cursor is actually inside.
3836        let got = after(
3837            "f(g(x), y)\n",
3838            0,
3839            8,
3840            del_obj(escriba_core::TextObject::Delimited {
3841                open: '(',
3842                close: ')',
3843                around: false,
3844            }),
3845        );
3846        assert_eq!(got, "f()\n", "took the outer pair");
3847    }
3848
3849    #[test]
3850    fn quotes_do_not_nest_so_the_nearest_pair_wins() {
3851        let got = after(
3852            r#"say "hi there" ok"#,
3853            0,
3854            7,
3855            del_obj(escriba_core::TextObject::Delimited {
3856                open: '"',
3857                close: '"',
3858                around: false,
3859            }),
3860        );
3861        assert_eq!(got, "say \"\" ok");
3862    }
3863
3864    #[test]
3865    fn an_unmatched_delimiter_resolves_to_nothing_rather_than_guessing() {
3866        let mut st = new_state_with("f(a, b\n");
3867        st.set_cursor(Position::new(0, 3));
3868        let before = st
3869            .buffers
3870            .get(st.active)
3871            .map(|b| b.to_string())
3872            .unwrap_or_default();
3873        st.apply(&del_obj(escriba_core::TextObject::Delimited {
3874            open: '(',
3875            close: ')',
3876            around: false,
3877        }));
3878        let got_after = st
3879            .buffers
3880            .get(st.active)
3881            .map(|b| b.to_string())
3882            .unwrap_or_default();
3883        assert_eq!(got_after, before, "no closing bracket: change nothing");
3884    }
3885
3886    fn new_state_with(text: &str) -> EditorState {
3887        let mut bufs = BufferSet::new();
3888        let id = bufs.scratch(text);
3889        EditorState::new_with_buffer(bufs, id)
3890    }
3891
3892    /// The refresh-seal driver (theory/ESCRIBA.md §Refresh-Seal): an applied
3893    /// action advances `edit_gen` (so the renderer repaints), and merely
3894    /// reading the generation does not. This is what lets `gpu.rs` gate the
3895    /// re-highlight/re-shape on a generation change — an idle frame observes an
3896    /// unchanged generation and reuses its cached buffer.
3897    #[test]
3898    fn edit_gen_advances_on_applied_action_not_on_read() {
3899        let mut s = new_state_with("hello\nworld\n");
3900        let g0 = s.edit_gen();
3901        s.apply(&Action::InsertChar('X'));
3902        assert_ne!(
3903            s.edit_gen(),
3904            g0,
3905            "an applied action must advance the refresh generation",
3906        );
3907        // Reading the generation is not a mutation — idle frames stay put.
3908        let g1 = s.edit_gen();
3909        assert_eq!(s.edit_gen(), g1, "reading edit_gen must not advance it");
3910    }
3911
3912    /// The M1 refresh node (theory/ESCRIBA.md §X): a mutation widens the typed
3913    /// `Damage` to cover exactly what changed — local for an in-place edit,
3914    /// to-end-of-document when the line count shifts — and the renderer drains
3915    /// it per frame. `Damage ⊇ changed` by construction; it never narrows.
3916    #[test]
3917    fn damage_tracks_edit_scope_and_drains() {
3918        let mut s = new_state_with("hello\nworld\n");
3919        assert!(s.damage().is_none(), "a fresh state has no damage");
3920
3921        s.apply(&Action::InsertChar('X')); // in-place edit on line 0
3922        assert_eq!(
3923            s.damage(),
3924            Damage::Lines { from: 0, to: 0 },
3925            "a local edit damages just its line",
3926        );
3927
3928        let drained = s.take_damage();
3929        assert_eq!(drained, Damage::Lines { from: 0, to: 0 });
3930        assert!(s.damage().is_none(), "take_damage drains to None");
3931
3932        s.apply(&Action::InsertChar('\n')); // splits line 0 → line count grows
3933        assert_eq!(
3934            s.damage(),
3935            Damage::Lines {
3936                from: 0,
3937                to: u32::MAX,
3938            },
3939            "a line-count change damages to end-of-document",
3940        );
3941    }
3942
3943    /// A state whose active window is a deliberately tiny viewport
3944    /// (`visible_lines` × `visible_columns`) so the scroll-to-contain
3945    /// invariant is exercised on small inputs.
3946    fn new_state_small_viewport(text: &str, vis_lines: u32, vis_cols: u32) -> EditorState {
3947        let mut s = new_state_with(text);
3948        for w in s.layout.windows_mut() {
3949            w.viewport.visible_lines = vis_lines;
3950            w.viewport.visible_columns = vis_cols;
3951        }
3952        s
3953    }
3954
3955    /// The core regression invariant: the active window's viewport CONTAINS
3956    /// the cursor on BOTH axes. This is the operator's exact complaint —
3957    /// "typing past the bottom (or right) leaves the cursor off-screen" —
3958    /// made into a checkable property.
3959    fn assert_cursor_in_viewport(s: &EditorState, ctx: &str) {
3960        let w = s.layout.active_window().expect("active window");
3961        let v = w.viewport;
3962        let c = s.cursor();
3963        assert!(
3964            v.top_line <= c.line && c.line < v.top_line + v.visible_lines,
3965            "[{ctx}] cursor line {} not in vertical window [{}, {}); viewport={v:?}",
3966            c.line,
3967            v.top_line,
3968            v.top_line + v.visible_lines,
3969        );
3970        assert!(
3971            v.left_column <= c.column && c.column < v.left_column + v.visible_columns,
3972            "[{ctx}] cursor column {} not in horizontal window [{}, {}); viewport={v:?}",
3973            c.column,
3974            v.left_column,
3975            v.left_column + v.visible_columns,
3976        );
3977    }
3978
3979    /// `dd` from the KEYBOARD, not from a synthesized action.
3980    ///
3981    /// The FSM composition is unit-tested, but what an operator actually
3982    /// does is press `d` twice — and that path goes through the keymap and
3983    /// the sequence stepper, either of which could swallow the second `d`.
3984    #[test]
3985    fn pressing_d_twice_deletes_the_line() {
3986        let mut st = new_state_with("alpha\nbeta\ngamma\n");
3987        st.set_cursor(Position::new(1, 0));
3988        st.tick(&press(KeyCode::Char('d')));
3989        st.tick(&press(KeyCode::Char('d')));
3990        let got = st
3991            .buffers
3992            .get(st.active)
3993            .map(|b| b.to_string())
3994            .unwrap_or_default();
3995        assert_eq!(got, "alpha\ngamma\n", "dd from the keyboard");
3996    }
3997
3998    #[test]
3999    fn pressing_2_d_d_deletes_two_lines() {
4000        let mut st = new_state_with("a\nb\nc\nd\n");
4001        st.set_cursor(Position::new(0, 0));
4002        for k in ['2', 'd', 'd'] {
4003            st.tick(&press(KeyCode::Char(k)));
4004        }
4005        let got = st
4006            .buffers
4007            .get(st.active)
4008            .map(|b| b.to_string())
4009            .unwrap_or_default();
4010        assert_eq!(got, "c\nd\n", "count applies to the doubled operator");
4011    }
4012
4013    /// Text objects FROM THE KEYBOARD — the layer the last commit said was
4014    /// missing. `i` is `ChangeMode(Insert)` in Normal and `a` and every
4015    /// bracket are unbound, so all of this had to be decided on the KEY.
4016
4017    fn keys(text: &str, line: u32, col: u32, seq: &str) -> String {
4018        let mut st = new_state_with(text);
4019        st.set_cursor(Position::new(line, col));
4020        for c in seq.chars() {
4021            st.tick(&press(KeyCode::Char(c)));
4022        }
4023        st.buffers
4024            .get(st.active)
4025            .map(|b| b.to_string())
4026            .unwrap_or_default()
4027    }
4028
4029    #[test]
4030    fn diw_from_the_keyboard() {
4031        assert_eq!(keys("one two three\n", 0, 5, "diw"), "one  three\n");
4032    }
4033
4034    #[test]
4035    fn daw_from_the_keyboard_takes_the_space() {
4036        assert_eq!(keys("one two three\n", 0, 5, "daw"), "one three\n");
4037    }
4038
4039    #[test]
4040    fn ciw_deletes_and_enters_insert() {
4041        let mut st = new_state_with("one two\n");
4042        st.set_cursor(Position::new(0, 5));
4043        for c in "ciw".chars() {
4044            st.tick(&press(KeyCode::Char(c)));
4045        }
4046        assert_eq!(st.modal.mode(), Mode::Insert, "change leaves you inserting");
4047        let got = st
4048            .buffers
4049            .get(st.active)
4050            .map(|b| b.to_string())
4051            .unwrap_or_default();
4052        assert_eq!(got, "one \n");
4053    }
4054
4055    #[test]
4056    fn di_paren_and_da_paren_from_the_keyboard() {
4057        assert_eq!(keys("f(a, b)\n", 0, 3, "di("), "f()\n");
4058        assert_eq!(keys("f(a, b)\n", 0, 3, "da("), "f\n");
4059    }
4060
4061    #[test]
4062    fn the_closing_bracket_and_b_are_aliases() {
4063        // vim accepts `i(`, `i)` and `ib` for the same object.
4064        for sel in ["di(", "di)", "dib"] {
4065            assert_eq!(keys("f(a, b)\n", 0, 3, sel), "f()\n", "{sel}");
4066        }
4067    }
4068
4069    #[test]
4070    fn di_quote_from_the_keyboard() {
4071        assert_eq!(keys("say \"hi\" ok\n", 0, 6, "di\""), "say \"\" ok\n");
4072    }
4073
4074    #[test]
4075    fn i_alone_still_enters_insert_when_no_operator_is_pending() {
4076        // The load-bearing negative: the object layer must not steal `i`
4077        // from ordinary use.
4078        let mut st = new_state_with("abc\n");
4079        st.tick(&press(KeyCode::Char('i')));
4080        assert_eq!(st.modal.mode(), Mode::Insert);
4081    }
4082
4083    #[test]
4084    fn an_unknown_object_key_cancels_rather_than_staying_armed() {
4085        // `diz` is not an object. The operator must disarm, and the buffer
4086        // must be untouched — not left waiting to eat the next keystroke.
4087        let mut st = new_state_with("one two\n");
4088        st.set_cursor(Position::new(0, 5));
4089        for c in "diz".chars() {
4090            st.tick(&press(KeyCode::Char(c)));
4091        }
4092        let got = st
4093            .buffers
4094            .get(st.active)
4095            .map(|b| b.to_string())
4096            .unwrap_or_default();
4097        assert_eq!(got, "one two\n", "nothing was deleted");
4098        assert_eq!(*st.op_pending.state(), OpState::Resting, "and it disarmed");
4099    }
4100
4101    // ── the register under a count ───────────────────────────────────
4102
4103    #[test]
4104    fn a_counted_delete_puts_ALL_of_it_in_the_register() {
4105        // `3dw` is one delete of three words as far as the register is
4106        // concerned. Each repetition emits its own Yank, and each used to
4107        // overwrite — so `3dwP` put back only the third word and silently
4108        // lost two.
4109        let mut st = new_state_with("one two three four\n");
4110        st.set_cursor(Position::new(0, 0));
4111        for c in "3dw".chars() {
4112            st.tick(&press(KeyCode::Char(c)));
4113        }
4114        assert_eq!(
4115            st.register.as_deref(),
4116            Some("one two three "),
4117            "all three words, in the order they were deleted"
4118        );
4119    }
4120
4121    #[test]
4122    fn an_uncounted_delete_still_replaces_the_register() {
4123        // The combining flag must not leak: a later single delete replaces.
4124        let mut st = new_state_with("alpha beta\n");
4125        st.set_cursor(Position::new(0, 0));
4126        for c in "3dw".chars() {
4127            st.tick(&press(KeyCode::Char(c)));
4128        }
4129        let mut st2 = new_state_with("gamma delta\n");
4130        st2.set_cursor(Position::new(0, 0));
4131        for c in "dw".chars() {
4132            st2.tick(&press(KeyCode::Char(c)));
4133        }
4134        assert_eq!(st2.register.as_deref(), Some("gamma "));
4135    }
4136
4137    #[test]
4138    fn two_separate_counted_deletes_do_not_accumulate_into_each_other() {
4139        // The flag is cleared after each group, so the second `2dw` starts
4140        // from empty rather than appending to the first.
4141        let mut st = new_state_with("a b c d e f\n");
4142        st.set_cursor(Position::new(0, 0));
4143        for c in "2dw".chars() {
4144            st.tick(&press(KeyCode::Char(c)));
4145        }
4146        let first = st.register.clone();
4147        for c in "2dw".chars() {
4148            st.tick(&press(KeyCode::Char(c)));
4149        }
4150        assert_eq!(first.as_deref(), Some("a b "));
4151        assert_eq!(st.register.as_deref(), Some("c d "), "not \"a b c d \"");
4152    }
4153
4154    #[test]
4155    fn a_counted_yank_accumulates_without_changing_the_buffer() {
4156        let mut st = new_state_with("one two three\n");
4157        st.set_cursor(Position::new(0, 0));
4158        let before = st
4159            .buffers
4160            .get(st.active)
4161            .map(|b| b.to_string())
4162            .unwrap_or_default();
4163        for c in "2yw".chars() {
4164            st.tick(&press(KeyCode::Char(c)));
4165        }
4166        assert_eq!(st.register.as_deref(), Some("one two "));
4167        let after = st
4168            .buffers
4169            .get(st.active)
4170            .map(|b| b.to_string())
4171            .unwrap_or_default();
4172        assert_eq!(after, before, "yank does not edit");
4173    }
4174
4175    // ── the anchored reply (Negai::ErrandReply) ──────────────────────
4176    //
4177    // Landed BEFORE the courier that will produce these. The class being
4178    // closed: a reply computed off the tick, applied against a world that
4179    // has since moved, and RESEALED as fresh by the interpreter — which is
4180    // what every synchronous slip correctly does and what an async one must
4181    // never do.
4182
4183    fn a_finding(buffer: BufferId, line: u32) -> escriba_shirube::Finding {
4184        use escriba_core::{Position, Range};
4185        escriba_shirube::Finding::new(
4186            escriba_shirube::Site::in_buffer(
4187                buffer,
4188                Range::new(Position::new(line, 0), Position::new(line, 1)),
4189            ),
4190            escriba_shirube::Severity::Error,
4191            "computed off the tick".to_string(),
4192            escriba_shirube::Origin::Text("test"),
4193        )
4194    }
4195
4196    #[test]
4197    fn a_fresh_errand_reply_is_honoured() {
4198        let mut st = new_state_with("a\nb\nc\n");
4199        let anchor = st.world();
4200        st.honour_one(escriba_madoguchi::Negai::ErrandReply {
4201            anchor,
4202            then: Box::new(escriba_madoguchi::Negai::PublishFindings {
4203                list: "lsp".to_string(),
4204                findings: vec![a_finding(st.active, 1)],
4205            }),
4206        });
4207        assert_eq!(
4208            st.finding_items(true, None).len(),
4209            1,
4210            "the world had not moved"
4211        );
4212    }
4213
4214    /// THE red run. Without the freshness check this passes findings
4215    /// straight through, and `PublishFindings` reseals them with the
4216    /// CURRENT world — so they are reported fresh at columns that moved.
4217    #[test]
4218    fn a_stale_errand_reply_is_dropped_not_resealed() {
4219        let mut st = new_state_with("a\nb\nc\n");
4220        // Capture the world the "server" computed against...
4221        let anchor = st.world();
4222        // ...then let the operator keep typing, which is the whole point.
4223        st.apply(&Action::InsertChar('x'));
4224
4225        st.honour_one(escriba_madoguchi::Negai::ErrandReply {
4226            anchor,
4227            then: Box::new(escriba_madoguchi::Negai::PublishFindings {
4228                list: "lsp".to_string(),
4229                findings: vec![a_finding(st.active, 1)],
4230            }),
4231        });
4232        assert!(
4233            st.finding_items(true, None).is_empty(),
4234            "a reply computed against an older text revision must be DROPPED, \
4235             not resealed against the current one"
4236        );
4237    }
4238
4239    /// The failure the wrapper exists for, and the reason it wraps a slip
4240    /// rather than adding an anchor field to PublishFindings: a stale EDIT
4241    /// corrupts the file, where a stale diagnostic merely mis-decorates it.
4242    #[test]
4243    fn a_stale_errand_reply_cannot_edit_the_buffer() {
4244        let mut st = new_state_with("hello\n");
4245        let anchor = st.world();
4246        st.apply(&Action::InsertChar('!'));
4247        let before = st
4248            .buffers
4249            .get(st.active)
4250            .map(|b| b.to_string())
4251            .unwrap_or_default();
4252
4253        st.honour_one(escriba_madoguchi::Negai::ErrandReply {
4254            anchor,
4255            then: Box::new(escriba_madoguchi::Negai::Edit {
4256                buffer: st.active,
4257                edit: escriba_core::Edit {
4258                    range: Range::new(Position::new(0, 0), Position::new(0, 0)),
4259                    kind: escriba_core::EditKind::Insert {
4260                        text: "FORMATTED".to_string(),
4261                    },
4262                },
4263            }),
4264        });
4265        let after = st
4266            .buffers
4267            .get(st.active)
4268            .map(|b| b.to_string())
4269            .unwrap_or_default();
4270        assert_eq!(
4271            after, before,
4272            "a stale formatter reply must not touch the text"
4273        );
4274    }
4275
4276    fn press(kc: KeyCode) -> AppEvent {
4277        AppEvent::Key(KeyEvent {
4278            key: kc,
4279            pressed: true,
4280            modifiers: Modifiers::default(),
4281            text: None,
4282        })
4283    }
4284
4285    // ── operator-over-motion (the `dw`/`c$`/`y0` verbs) ──────────────
4286
4287    fn line0_len(s: &EditorState) -> u32 {
4288        s.buffers.get(s.active).unwrap().line_len_chars(0)
4289    }
4290
4291    #[test]
4292    fn delete_to_line_end_clears_line_and_fills_register() {
4293        let mut s = new_state_with("hello world");
4294        s.apply(&Action::ApplyOperator {
4295            op: Operator::Delete,
4296            motion: Motion::LineEnd,
4297        });
4298        assert_eq!(line0_len(&s), 0, "d$ deletes to end of line");
4299        assert_eq!(
4300            s.register(),
4301            Some("hello world"),
4302            "delete fills the register"
4303        );
4304        assert_eq!(
4305            s.cursor(),
4306            Position::ZERO,
4307            "cursor lands at the range start"
4308        );
4309    }
4310
4311    #[test]
4312    fn delete_over_right_motion_removes_one_char() {
4313        let mut s = new_state_with("abc");
4314        s.apply(&Action::ApplyOperator {
4315            op: Operator::Delete,
4316            motion: Motion::Right,
4317        });
4318        assert_eq!(
4319            s.buffers.get(s.active).unwrap().line(0).as_deref(),
4320            Some("bc")
4321        );
4322        assert_eq!(s.register(), Some("a"));
4323    }
4324
4325    #[test]
4326    fn change_to_line_end_deletes_and_enters_insert() {
4327        let mut s = new_state_with("hello world");
4328        assert_eq!(s.modal.mode(), Mode::Normal);
4329        s.apply(&Action::ApplyOperator {
4330            op: Operator::Change,
4331            motion: Motion::LineEnd,
4332        });
4333        assert_eq!(line0_len(&s), 0, "c$ deletes the range");
4334        assert_eq!(
4335            s.modal.mode(),
4336            Mode::Insert,
4337            "change enters Insert to type the replacement"
4338        );
4339        assert_eq!(
4340            s.register(),
4341            Some("hello world"),
4342            "change fills the register"
4343        );
4344    }
4345
4346    #[test]
4347    fn yank_to_line_end_fills_register_without_mutating() {
4348        let mut s = new_state_with("hello world");
4349        s.apply(&Action::ApplyOperator {
4350            op: Operator::Yank,
4351            motion: Motion::LineEnd,
4352        });
4353        assert_eq!(line0_len(&s), 11, "yank does not mutate the buffer");
4354        assert_eq!(s.register(), Some("hello world"), "yank fills the register");
4355        assert_eq!(s.modal.mode(), Mode::Normal, "yank stays in Normal");
4356    }
4357
4358    #[test]
4359    fn resolve_motion_is_the_shared_target_for_move_and_operator() {
4360        // The encapsulation proof: apply_motion (cursor move) and
4361        // apply_operator (range end) BOTH stand on resolve_motion — so a move
4362        // to LineEnd lands at exactly the position the operator deletes to.
4363        let mut s = new_state_with("hello world");
4364        let target = s.resolve_motion(Position::ZERO, Motion::LineEnd).unwrap();
4365        assert_eq!(target, Position::new(0, 11));
4366        s.apply_motion(Motion::LineEnd);
4367        assert_eq!(
4368            s.cursor(),
4369            target,
4370            "the move path resolves the same target the operator uses"
4371        );
4372    }
4373
4374    #[test]
4375    fn empty_motion_range_is_a_no_op() {
4376        // An operator over a zero-width motion (cursor already at line start)
4377        // mutates nothing and leaves the register untouched.
4378        let mut s = new_state_with("abc");
4379        s.apply(&Action::ApplyOperator {
4380            op: Operator::Delete,
4381            motion: Motion::LineStart,
4382        });
4383        assert_eq!(
4384            s.buffers.get(s.active).unwrap().line(0).as_deref(),
4385            Some("abc")
4386        );
4387        assert_eq!(s.register(), None);
4388    }
4389
4390    #[test]
4391    fn operator_then_motion_composes_through_the_pending_fsm() {
4392        // The full keymap→FSM→engine path: dispatching the `d` operator action
4393        // then a `$` motion composes `d$` via the zenmai operator-pending FSM —
4394        // the operator key alone does nothing until the motion arrives.
4395        let mut s = new_state_with("hello world");
4396        s.apply(&Action::Operator(Operator::Delete));
4397        assert_eq!(line0_len(&s), 11, "the operator key alone mutates nothing");
4398        s.apply(&Action::Move(Motion::LineEnd));
4399        assert_eq!(
4400            line0_len(&s),
4401            0,
4402            "d then $ composes d$ and deletes the line"
4403        );
4404        assert_eq!(s.register(), Some("hello world"));
4405    }
4406
4407    #[test]
4408    fn change_operator_through_fsm_enters_insert() {
4409        let mut s = new_state_with("hello world");
4410        s.apply(&Action::Operator(Operator::Change));
4411        s.apply(&Action::Move(Motion::LineEnd));
4412        assert_eq!(s.modal.mode(), Mode::Insert, "c$ deletes and enters Insert");
4413    }
4414
4415    #[test]
4416    fn lone_motion_after_no_operator_just_moves() {
4417        // Without a preceding operator the motion passes through unchanged.
4418        let mut s = new_state_with("hello world");
4419        s.apply(&Action::Move(Motion::LineEnd));
4420        assert_eq!(s.cursor(), Position::new(0, 11));
4421        assert_eq!(line0_len(&s), 11, "a bare motion never mutates");
4422    }
4423
4424    #[test]
4425    fn counted_operator_deletes_count_times() {
4426        // `3d` + a right-motion = `3dl` = delete 3 chars. The operator's count
4427        // flows through the FSM to the composed motion (the bug fix: previously
4428        // the count repeated the operator key and toggled the FSM).
4429        let mut s = new_state_with("abcdef");
4430        s.apply_counted(&Action::Operator(Operator::Delete), 3);
4431        assert_eq!(line0_len(&s), 6, "the operator key alone mutates nothing");
4432        s.apply(&Action::Move(Motion::Right));
4433        assert_eq!(
4434            s.buffers.get(s.active).unwrap().line(0).as_deref(),
4435            Some("def")
4436        );
4437    }
4438
4439    #[test]
4440    fn operator_and_motion_counts_multiply_end_to_end() {
4441        // `2d3l` = delete 2×3 = 6 chars.
4442        let mut s = new_state_with("abcdefgh");
4443        s.apply_counted(&Action::Operator(Operator::Delete), 2);
4444        s.apply_counted(&Action::Move(Motion::Right), 3);
4445        assert_eq!(
4446            s.buffers.get(s.active).unwrap().line(0).as_deref(),
4447            Some("gh")
4448        );
4449    }
4450
4451    #[test]
4452    fn bare_counted_motion_still_repeats_no_regression() {
4453        // `3j` still moves down 3 lines — the count passes through the FSM
4454        // unchanged when no operator is pending.
4455        let mut s = new_state_with("a\nb\nc\nd\ne");
4456        s.apply_counted(&Action::Move(Motion::Down), 3);
4457        assert_eq!(s.cursor().line, 3, "5j-style counted motion preserved");
4458    }
4459
4460    /// A monotonic clock for the key-repeat gate in tests — each `next()`
4461    /// jumps a full second past the previous, so every press it stamps is
4462    /// well outside the 80ms debounce window and therefore an INTENTIONAL
4463    /// press (never a storm tick). Used by tests that fire the *same*
4464    /// navigation key twice and assert editor logic, not debounce timing.
4465    struct SpacedClock(std::time::Instant);
4466    impl SpacedClock {
4467        fn new() -> Self {
4468            Self(std::time::Instant::now())
4469        }
4470        fn next(&mut self) -> std::time::Instant {
4471            self.0 += std::time::Duration::from_secs(1);
4472            self.0
4473        }
4474    }
4475
4476    #[test]
4477    fn hjkl_moves_cursor() {
4478        let mut s = new_state_with("hello\nworld");
4479        s.tick(&press(KeyCode::Char('l')));
4480        assert_eq!(s.cursor().column, 1);
4481        s.tick(&press(KeyCode::Char('j')));
4482        assert_eq!(s.cursor().line, 1);
4483        s.tick(&press(KeyCode::Char('h')));
4484        assert_eq!(s.cursor().column, 0);
4485    }
4486
4487    #[test]
4488    fn insert_mode_inserts_chars() {
4489        let mut s = new_state_with("");
4490        s.tick(&press(KeyCode::Char('i')));
4491        assert_eq!(s.modal.mode(), Mode::Insert);
4492        s.tick(&press(KeyCode::Char('h')));
4493        s.tick(&press(KeyCode::Char('i')));
4494        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "hi");
4495        assert_eq!(s.cursor().column, 2);
4496    }
4497
4498    #[test]
4499    fn esc_returns_to_normal() {
4500        let mut s = new_state_with("");
4501        s.tick(&press(KeyCode::Char('i')));
4502        s.tick(&press(KeyCode::Escape));
4503        assert_eq!(s.modal.mode(), Mode::Normal);
4504    }
4505
4506    #[test]
4507    fn count_prefix_repeats_motion() {
4508        let mut s = new_state_with("abcdefghij");
4509        s.tick(&press(KeyCode::Char('5')));
4510        s.tick(&press(KeyCode::Char('l')));
4511        assert_eq!(s.cursor().column, 5);
4512    }
4513
4514    #[test]
4515    fn close_event_requests_quit() {
4516        let mut s = new_state_with("");
4517        s.tick(&AppEvent::CloseRequested);
4518        assert!(s.quit_requested);
4519    }
4520
4521    #[test]
4522    fn word_next_jumps_past_whitespace() {
4523        let mut s = new_state_with("foo bar baz");
4524        // Two INTENTIONAL `w` presses, spaced past the key-repeat window so
4525        // the gate passes both (a real user's two taps are ≥80ms apart).
4526        let mut clk = SpacedClock::new();
4527        s.tick_at(&press(KeyCode::Char('w')), clk.next());
4528        assert_eq!(s.cursor().column, 4);
4529        s.tick_at(&press(KeyCode::Char('w')), clk.next());
4530        assert_eq!(s.cursor().column, 8);
4531    }
4532
4533    // ── Multi-key / leader pending-stroke ───────────────────────────
4534
4535    #[test]
4536    fn leader_sequence_holds_then_resolves() {
4537        let mut s = new_state_with("a\nbb\nccc");
4538        s.keymap.bind_sequence(
4539            Mode::Normal,
4540            vec![Key::Char(','), Key::Char('g')],
4541            Action::Move(Motion::DocEnd),
4542            "doc end",
4543        );
4544        // `,` begins the sequence — held pending, nothing applied yet.
4545        s.on_key(&Key::Char(','));
4546        assert_eq!(s.pending_keys, vec![Key::Char(',')]);
4547        assert_eq!(s.cursor(), Position::ZERO);
4548        // `g` completes `<leader>g` → DocEnd; pending clears.
4549        s.on_key(&Key::Char('g'));
4550        assert!(s.pending_keys.is_empty());
4551        assert_eq!(s.cursor().line, 2);
4552    }
4553
4554    #[test]
4555    fn two_key_gg_jumps_doc_start() {
4556        let mut s = new_state_with("a\nbb\nccc");
4557        s.keymap.bind_sequence(
4558            Mode::Normal,
4559            vec![Key::Char('g'), Key::Char('g')],
4560            Action::Move(Motion::DocStart),
4561            "doc start",
4562        );
4563        let mut clk = SpacedClock::new();
4564        s.tick_at(&press(KeyCode::Char('j')), clk.next());
4565        s.tick_at(&press(KeyCode::Char('j')), clk.next());
4566        assert_eq!(s.cursor().line, 2);
4567        s.on_key(&Key::Char('g')); // pending
4568        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
4569        s.on_key(&Key::Char('g')); // resolve
4570        assert_eq!(s.cursor(), Position::ZERO);
4571    }
4572
4573    #[test]
4574    fn broken_sequence_aborts_and_clears_pending() {
4575        let mut s = new_state_with("hello");
4576        s.keymap.bind_sequence(
4577            Mode::Normal,
4578            vec![Key::Char('g'), Key::Char('g')],
4579            Action::Move(Motion::DocEnd),
4580            "doc end",
4581        );
4582        s.on_key(&Key::Char('g')); // pending [g]
4583        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
4584        s.on_key(&Key::Char('x')); // breaks gg → abort; x is unbound → no-op
4585        assert!(s.pending_keys.is_empty());
4586        assert_eq!(s.cursor(), Position::ZERO);
4587    }
4588
4589    #[test]
4590    fn single_binding_wins_over_sequence_prefix() {
4591        // A key that is BOTH a complete single binding and the start of
4592        // a sequence fires the single binding immediately (no chord
4593        // timeout needed). Here `h` (move-left) also prefixes `hz`.
4594        let mut s = new_state_with("abcde");
4595        let mut clk = SpacedClock::new();
4596        s.tick_at(&press(KeyCode::Char('l')), clk.next());
4597        s.tick_at(&press(KeyCode::Char('l')), clk.next());
4598        assert_eq!(s.cursor().column, 2);
4599        s.keymap.bind_sequence(
4600            Mode::Normal,
4601            vec![Key::Char('h'), Key::Char('z')],
4602            Action::Move(Motion::DocEnd),
4603            "shadowed",
4604        );
4605        s.on_key(&Key::Char('h'));
4606        assert!(s.pending_keys.is_empty(), "single binding should not pend");
4607        assert_eq!(s.cursor().column, 1, "h moved left immediately");
4608    }
4609
4610    // ── tatara-lisp runtime bridge (imperative programmability) ─────
4611
4612    #[test]
4613    fn lisp_set_option_writes_live_options() {
4614        let mut s = new_state_with("");
4615        s.run_lisp(r#"(set-option "number" "true")"#).unwrap();
4616        assert_eq!(s.options.get("number").map(String::as_str), Some("true"));
4617    }
4618
4619    #[test]
4620    fn lisp_insert_modifies_buffer_and_advances_cursor() {
4621        let mut s = new_state_with("");
4622        s.run_lisp(r#"(insert "abc")"#).unwrap();
4623        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
4624        assert_eq!(s.cursor(), Position::new(0, 3));
4625    }
4626
4627    #[test]
4628    fn lisp_message_appends_to_messages() {
4629        let mut s = new_state_with("");
4630        s.run_lisp(r#"(message "hello from lisp")"#).unwrap();
4631        assert_eq!(s.messages, vec!["hello from lisp".to_string()]);
4632    }
4633
4634    #[test]
4635    fn lisp_reads_snapshot_and_branches_to_effect() {
4636        // Genuine programmability: Lisp reads the live cursor line and
4637        // an `if` decides which option to set.
4638        let mut s = new_state_with("one\ntwo\nthree");
4639        // cursor at line 0 → "top" branch
4640        s.run_lisp(r#"(if (= (cursor-line) 0) (set-option "pos" "top") (set-option "pos" "mid"))"#)
4641            .unwrap();
4642        assert_eq!(s.options.get("pos").map(String::as_str), Some("top"));
4643    }
4644
4645    #[test]
4646    fn lisp_run_command_effect_drives_registry() {
4647        // `(run-command "undo")` reaches the live command registry and
4648        // reverts a prior Lisp-driven insert — proving the RunCommand
4649        // effect dispatches through real editor commands.
4650        let mut s = new_state_with("");
4651        s.run_lisp(r#"(insert "abc")"#).unwrap();
4652        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
4653        s.run_lisp(r#"(run-command "undo")"#).unwrap();
4654        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "");
4655    }
4656
4657    #[test]
4658    fn lisp_run_command_quit_sets_quit_requested_via_typed_flag() {
4659        // The full imperative-quit path: (run-command "quit") routes
4660        // through the registry's typed `quit_requested` signal — no string
4661        // sentinel, and no minibuffer pollution (the editor stays in a
4662        // clean Normal state, which has no minibuffer at all).
4663        let mut s = new_state_with("");
4664        s.run_lisp(r#"(run-command "quit")"#).unwrap();
4665        assert!(s.quit_requested, "lisp-driven quit must set quit_requested");
4666        assert_eq!(
4667            s.modal.minibuffer(),
4668            "",
4669            "quit must not pollute any command line — Normal mode has no minibuffer",
4670        );
4671    }
4672
4673    // ── Lazy plugin activation (PluginHost) ────────────────────────
4674
4675    #[test]
4676    fn lazy_plugin_activates_on_command_trigger() {
4677        // A user plugin gated on `Command: LazyGo` has its entry applied
4678        // the first time that command runs — proving the lazy.nvim
4679        // `cmd =` model works end-to-end against live editor state.
4680        let mut s = new_state_with("");
4681        s.register_lazy_plugin(
4682            "user-lazy",
4683            vec![LazyTrigger::Command("LazyGo".into())],
4684            r#"(defoption :name "lazy-loaded" :value "yes")
4685               (defcmd :name "LazyGo" :description "noop" :action "editor.noop")"#,
4686        );
4687        assert_eq!(s.plugin_host.pending(), 1);
4688        assert!(
4689            s.options.get("lazy-loaded").is_none(),
4690            "entry not applied yet"
4691        );
4692
4693        // Drive the command through the public imperative path.
4694        s.run_lisp(r#"(run-command "LazyGo")"#).unwrap();
4695
4696        assert_eq!(
4697            s.options.get("lazy-loaded").map(String::as_str),
4698            Some("yes"),
4699            "the command trigger applied the plugin's entry",
4700        );
4701        assert_eq!(s.plugin_host.pending(), 0, "plugin activated exactly once");
4702    }
4703
4704    #[test]
4705    fn lazy_plugin_activates_on_filetype() {
4706        let mut s = new_state_with("");
4707        s.register_lazy_plugin(
4708            "user-rust",
4709            vec![LazyTrigger::FileType("rust".into())],
4710            r#"(defoption :name "rust-plugin" :value "on")"#,
4711        );
4712        let n = s.activate_filetype_plugins("rust");
4713        assert_eq!(n, 1);
4714        assert_eq!(s.options.get("rust-plugin").map(String::as_str), Some("on"));
4715        // A second open of the same filetype is a no-op (one-shot).
4716        assert_eq!(s.activate_filetype_plugins("rust"), 0);
4717    }
4718
4719    #[test]
4720    fn cached_vm_serves_multiple_run_lisp_calls() {
4721        let mut s = new_state_with("");
4722        s.run_lisp(r#"(message "one")"#).unwrap();
4723        assert!(
4724            s.lisp_vm.is_some(),
4725            "VM should be cached after first run_lisp"
4726        );
4727        s.run_lisp(r#"(message "two")"#).unwrap();
4728        assert_eq!(s.messages, vec!["one".to_string(), "two".to_string()]);
4729    }
4730
4731    #[test]
4732    fn lisp_define_persists_across_run_lisp_calls() {
4733        // The cached VM's top-level env persists across calls (REPL
4734        // semantics): a `define` in one call is visible in the next.
4735        let mut s = new_state_with("");
4736        s.run_lisp(r#"(define greeting "hi")"#).unwrap();
4737        s.run_lisp(r#"(message greeting)"#).unwrap();
4738        assert_eq!(s.messages, vec!["hi".to_string()]);
4739    }
4740
4741    #[test]
4742    fn snapshot_is_isolated_within_one_run_lisp_call_and_refreshes_across() {
4743        // Within ONE call a program cannot observe its own writes — the
4744        // read snapshot is captured before eval, effects apply after. A
4745        // later call sees the refreshed snapshot.
4746        let mut s = new_state_with("");
4747        s.run_lisp(
4748            r#"(insert "ab") (set-option "col" (if (= (cursor-column) 0) "stale-zero" "live"))"#,
4749        )
4750        .unwrap();
4751        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "ab");
4752        assert_eq!(
4753            s.options.get("col").map(String::as_str),
4754            Some("stale-zero"),
4755            "cursor-column within the same call reads the pre-eval snapshot",
4756        );
4757        // After the first call the cursor advanced to column 2; the next
4758        // call's snapshot reflects it.
4759        s.run_lisp(r#"(set-option "col2" (if (= (cursor-column) 2) "live-two" "other"))"#)
4760            .unwrap();
4761        assert_eq!(
4762            s.options.get("col2").map(String::as_str),
4763            Some("live-two"),
4764            "a later call sees the refreshed snapshot",
4765        );
4766    }
4767
4768    #[test]
4769    fn insert_text_effect_multiline_lands_cursor_on_last_line() {
4770        let mut s = new_state_with("");
4771        s.apply_host_effects(vec![Negai::InsertText("foo\nbar".to_string())]);
4772        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "foo\nbar");
4773        assert_eq!(s.cursor(), Position::new(1, 3));
4774    }
4775
4776    #[test]
4777    fn visual_mode_sequence_resolves() {
4778        let mut s = new_state_with("abc");
4779        s.modal.enter(Mode::Visual);
4780        s.keymap.bind_sequence(
4781            Mode::Visual,
4782            vec![Key::Char('g'), Key::Char('e')],
4783            Action::Move(Motion::DocEnd),
4784            "ge",
4785        );
4786        s.on_key(&Key::Char('g'));
4787        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
4788        s.on_key(&Key::Char('e'));
4789        assert!(s.pending_keys.is_empty());
4790        assert_eq!(
4791            s.cursor().column,
4792            3,
4793            "ge resolved to doc-end in visual mode"
4794        );
4795    }
4796
4797    #[test]
4798    fn sequence_abort_with_bound_breaking_key_redispatches() {
4799        // gg is a sequence; `l` (move-right) is a bound single key. After
4800        // `g` pends, `l` breaks gg, aborts, and is re-dispatched fresh.
4801        let mut s = new_state_with("abcde");
4802        s.keymap.bind_sequence(
4803            Mode::Normal,
4804            vec![Key::Char('g'), Key::Char('g')],
4805            Action::Move(Motion::DocEnd),
4806            "gg",
4807        );
4808        s.on_key(&Key::Char('g'));
4809        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
4810        s.on_key(&Key::Char('l'));
4811        assert!(s.pending_keys.is_empty());
4812        assert_eq!(
4813            s.cursor().column,
4814            1,
4815            "the breaking key l should re-dispatch as move-right",
4816        );
4817    }
4818
4819    // ── Viewport-follows-cursor invariant (both axes) ───────────────
4820
4821    #[test]
4822    fn viewport_contains_cursor_after_every_op() {
4823        // Tiny window: 5 visible lines × 10 visible columns. Drive a
4824        // representative scripted sequence and assert the viewport contains
4825        // the cursor after EVERY mutating step.
4826        let mut s = new_state_small_viewport("", 5, 10);
4827        assert_cursor_in_viewport(&s, "initial");
4828
4829        // Enter insert mode and type 30 newline-separated lines — this is
4830        // the exact "type past the bottom" complaint.
4831        s.tick(&press(KeyCode::Char('i')));
4832        assert_eq!(s.modal.mode(), Mode::Insert);
4833        for line in 0..30u32 {
4834            for c in "line".chars() {
4835                s.tick(&press(KeyCode::Char(c)));
4836                assert_cursor_in_viewport(&s, "typing chars");
4837            }
4838            s.tick(&press(KeyCode::Enter));
4839            assert_cursor_in_viewport(&s, &format!("newline after line {line}"));
4840        }
4841
4842        // Type a long (200-char) line — the "type past the right edge"
4843        // complaint. The cursor must stay horizontally visible the whole way.
4844        for i in 0..200u32 {
4845            s.tick(&press(KeyCode::Char('x')));
4846            assert_cursor_in_viewport(&s, &format!("long-line char {i}"));
4847        }
4848
4849        // Multi-line insert_text effect (the `(insert …)` Lisp path).
4850        s.insert_text("alpha\nbeta\ngamma delta epsilon zeta");
4851        assert_cursor_in_viewport(&s, "insert_text multiline");
4852
4853        // Back to normal mode and move in all directions / to extremes.
4854        s.tick(&press(KeyCode::Escape));
4855        assert_eq!(s.modal.mode(), Mode::Normal);
4856        for m in [
4857            Motion::DocStart,
4858            Motion::DocEnd,
4859            Motion::Down,
4860            Motion::Down,
4861            Motion::Up,
4862            Motion::Right,
4863            Motion::Right,
4864            Motion::Left,
4865            Motion::LineEnd,
4866            Motion::LineStart,
4867            Motion::GotoLine(1),
4868            Motion::GotoLine(40),
4869            Motion::PageDown,
4870            Motion::PageUp,
4871        ] {
4872            s.apply_motion(m);
4873            assert_cursor_in_viewport(&s, &format!("after motion {m:?}"));
4874        }
4875
4876        // Undo many times — the buffer shrinks; the viewport must re-follow
4877        // the (now clamped) cursor.
4878        for i in 0..50u32 {
4879            s.apply(&Action::Undo);
4880            assert_cursor_in_viewport(&s, &format!("undo {i}"));
4881        }
4882        // Redo back up.
4883        for i in 0..50u32 {
4884            s.apply(&Action::Redo);
4885            assert_cursor_in_viewport(&s, &format!("redo {i}"));
4886        }
4887    }
4888
4889    #[test]
4890    fn insert_at_eof_keeps_cursor_in_bounds() {
4891        // Inserting at the end of the buffer must leave the cursor clamped
4892        // to a valid position (and inside the viewport).
4893        let mut s = new_state_small_viewport("abc", 5, 10);
4894        s.apply_motion(Motion::DocEnd);
4895        s.tick(&press(KeyCode::Char('i')));
4896        s.tick(&press(KeyCode::Char('d')));
4897        let buf = s.buffers.get(s.active).unwrap();
4898        let clamped = buf.clamp(s.cursor());
4899        assert_eq!(
4900            s.cursor(),
4901            clamped,
4902            "cursor must be clamped in-bounds at EOF"
4903        );
4904        assert_cursor_in_viewport(&s, "insert at eof");
4905    }
4906
4907    #[test]
4908    fn count_prefix_then_sequence_repeats() {
4909        // `2` then `gj` (→ move-down) repeats the resolved action twice.
4910        let mut s = new_state_with("a\nb\nc\nd\ne");
4911        s.keymap.bind_sequence(
4912            Mode::Normal,
4913            vec![Key::Char('g'), Key::Char('j')],
4914            Action::Move(Motion::Down),
4915            "gj",
4916        );
4917        s.on_key(&Key::Char('2'));
4918        s.on_key(&Key::Char('g'));
4919        s.on_key(&Key::Char('j'));
4920        assert_eq!(s.cursor().line, 2, "count 2 should repeat the gj motion");
4921    }
4922
4923    // ── Key-repeat gate (awase::KeyRepeatGate) ──────────────────────────
4924
4925    #[test]
4926    fn held_key_repeat_storm_is_debounced_in_normal_mode() {
4927        // The audit's exact complaint: holding `j` floods motion events
4928        // and thrashes the viewport. Simulate an OS key-repeat storm — 20
4929        // identical `j` KeyDowns at 50ms intervals (typical repeat cadence)
4930        // — and assert only the gated subset (one per 80ms window) actually
4931        // moves the cursor.
4932        let mut s = new_state_with(&"x\n".repeat(40));
4933        let t0 = std::time::Instant::now();
4934        let mut delivered = 0u32;
4935        for i in 0..20u32 {
4936            let before = s.cursor().line;
4937            s.tick_at(
4938                &press(KeyCode::Char('j')),
4939                t0 + std::time::Duration::from_millis(u64::from(i) * 50),
4940            );
4941            if s.cursor().line != before {
4942                delivered += 1;
4943            }
4944        }
4945        // 20 events over ~1s at 50ms spacing, 80ms gate ⇒ ~13 pass — far
4946        // fewer than the 20 the ungated path would have applied.
4947        assert!(
4948            (10..=14).contains(&delivered),
4949            "expected the storm debounced to ~13 moves, got {delivered}",
4950        );
4951        assert!(
4952            delivered < 20,
4953            "the gate must drop SOME storm ticks, not pass all 20",
4954        );
4955    }
4956
4957    #[test]
4958    fn spaced_intentional_taps_all_pass() {
4959        // Intentional taps spaced past the debounce window must ALL reach
4960        // the editor — the gate filters storms, never deliberate input.
4961        let mut s = new_state_with(&"x\n".repeat(10));
4962        let t0 = std::time::Instant::now();
4963        for i in 0..5u32 {
4964            s.tick_at(
4965                &press(KeyCode::Char('j')),
4966                // 100ms apart — comfortably past the 80ms window.
4967                t0 + std::time::Duration::from_millis(u64::from(i) * 100),
4968            );
4969        }
4970        assert_eq!(s.cursor().line, 5, "all 5 spaced `j` taps moved the cursor");
4971    }
4972
4973    #[test]
4974    fn distinct_keys_have_independent_clocks() {
4975        // Holding `j` must not block a simultaneous `l` — the gate keys on
4976        // the Key, so independent keys have independent windows.
4977        let mut s = new_state_with("abc\ndef\nghi");
4978        let t = std::time::Instant::now();
4979        s.tick_at(&press(KeyCode::Char('j')), t);
4980        // `j` again within the window is dropped…
4981        s.tick_at(
4982            &press(KeyCode::Char('j')),
4983            t + std::time::Duration::from_millis(10),
4984        );
4985        assert_eq!(s.cursor().line, 1, "second `j` within window dropped");
4986        // …but `l` at the same instant passes (its own clock).
4987        s.tick_at(
4988            &press(KeyCode::Char('l')),
4989            t + std::time::Duration::from_millis(10),
4990        );
4991        assert_eq!(s.cursor().column, 1, "`l` is not blocked by `j`'s clock");
4992    }
4993
4994    // ── Cursors newtype is the single cursor home ──────────────────────
4995
4996    #[test]
4997    fn cursor_home_preserves_single_cursor_behavior() {
4998        // The typed `Cursors` wrapper behaves exactly like the old bare
4999        // `Position` field for single-cursor editing: the read accessor
5000        // tracks every mutation routed through `set_cursor`, and there is
5001        // exactly one caret.
5002        let mut s = new_state_with("hello\nworld\nthere");
5003        assert_eq!(s.cursor(), Position::ZERO);
5004        assert_eq!(s.cursors.count(), 1, "phase-1 holds exactly one caret");
5005
5006        s.apply_motion(Motion::Down);
5007        s.apply_motion(Motion::Right);
5008        s.apply_motion(Motion::Right);
5009        assert_eq!(s.cursor(), Position::new(1, 2));
5010        // Still a single caret after a sequence of motions.
5011        assert_eq!(s.cursors.count(), 1);
5012
5013        // The accessor is the SAME value the viewport-follow path read.
5014        let w = s.layout.active_window().unwrap();
5015        assert!(w.viewport.top_line <= s.cursor().line);
5016    }
5017
5018    #[test]
5019    fn insert_mode_is_ungated_so_repeat_typing_works() {
5020        // Holding a key to repeat-type a character is intended in Insert
5021        // mode — the gate must NOT suppress it. 10 rapid identical `x`
5022        // keystrokes at the same instant must all land as text.
5023        let mut s = new_state_with("");
5024        s.tick(&press(KeyCode::Char('i')));
5025        assert_eq!(s.modal.mode(), Mode::Insert);
5026        let t = std::time::Instant::now();
5027        for _ in 0..10 {
5028            s.tick_at(&press(KeyCode::Char('x')), t);
5029        }
5030        assert_eq!(
5031            s.buffers.get(s.active).unwrap().to_string(),
5032            "xxxxxxxxxx",
5033            "insert-mode repeat typing is ungated",
5034        );
5035    }
5036
5037    // ── the courier seam (denrei) ────────────────────────────────────
5038    //
5039    // What these pin is not "work happens off-thread" — that is the runner's
5040    // business. It is that a reply computed against one world cannot be
5041    // applied against a different one, and that the machinery says so out loud
5042    // when it declines to do something.
5043
5044    mod courier_seam {
5045        use super::new_state_with;
5046        use escriba_madoguchi::Negai;
5047        use escriba_madoguchi::errand::{Crew, Errand, Freight, Parcel, Runner};
5048        use escriba_shirube::{Anchor, Axis, ResultList, SessionKind};
5049        use std::sync::Arc;
5050        use std::sync::atomic::AtomicBool;
5051        use std::sync::mpsc::Sender;
5052
5053        fn a_scan() -> Freight {
5054            Freight::Scan {
5055                raw: "needle".into(),
5056                case: escriba_search::CaseMode::Smart,
5057                root: ".".into(),
5058            }
5059        }
5060
5061        /// Replies with whatever slip it was built with, immediately and on the
5062        /// calling thread — so these tests assert the SEAM, not thread timing.
5063        struct Says(Negai);
5064        impl Runner for Says {
5065            fn start(&self, e: Errand, _c: Arc<AtomicBool>, reply: Sender<Parcel>) {
5066                let _ = reply.send(Parcel {
5067                    id: e.id,
5068                    slip: self.0.clone(),
5069                });
5070            }
5071        }
5072
5073        /// Replies by wrapping its payload in the anchor the DISPATCHER sealed
5074        /// — which is what a real runner does: it echoes back the seal it was
5075        /// handed, because it has no way to mint its own.
5076        struct EchoesSeal(Negai);
5077        impl Runner for EchoesSeal {
5078            fn start(&self, e: Errand, _c: Arc<AtomicBool>, reply: Sender<Parcel>) {
5079                let _ = reply.send(Parcel {
5080                    id: e.id,
5081                    slip: Negai::ErrandReply {
5082                        anchor: e.anchor.into_anchor(),
5083                        then: Box::new(self.0.clone()),
5084                    },
5085                });
5086            }
5087        }
5088
5089        fn crew_with_scan(r: impl Runner + 'static) -> Crew {
5090            Crew {
5091                scan: Box::new(r),
5092                diagnostics: Box::new(escriba_madoguchi::errand::Idle("t")),
5093                format: Box::new(escriba_madoguchi::errand::Idle("t")),
5094            }
5095        }
5096
5097        /// The whole path in one test: a handler names a class of work, the
5098        /// dispatcher seals it, a runner answers, and the reply is applied at a
5099        /// tick boundary.
5100        #[test]
5101        fn an_errand_is_dispatched_sealed_and_its_reply_applied_at_the_drain() {
5102            let mut st = new_state_with("x\n");
5103            st.hire(crew_with_scan(EchoesSeal(Negai::Message("done".into()))));
5104
5105            st.honour_one(Negai::Errand(Box::new(a_scan())));
5106            assert!(
5107                !st.messages.iter().any(|m| m == "done"),
5108                "nothing is applied before the drain"
5109            );
5110
5111            st.deliver();
5112            assert!(
5113                st.messages.iter().any(|m| m == "done"),
5114                "the reply lands at the drain: {:?}",
5115                st.messages
5116            );
5117        }
5118
5119        /// **The reason the whole seam exists.** A reply sealed against the
5120        /// world at dispatch must be discarded once that world has moved.
5121        #[test]
5122        fn a_reply_whose_world_moved_is_dropped() {
5123            let mut st = new_state_with("x\n");
5124            st.hire(crew_with_scan(EchoesSeal(Negai::Message("late".into()))));
5125
5126            st.honour_one(Negai::Errand(Box::new(a_scan())));
5127            // The surface the scan feeds closed while it was running.
5128            st.bump_scan_gen();
5129            st.deliver();
5130
5131            assert!(
5132                !st.messages.iter().any(|m| m == "late"),
5133                "a superseded reply must not be applied: {:?}",
5134                st.messages
5135            );
5136        }
5137
5138        /// The converse, so the test above is not passing because nothing ever
5139        /// applies.
5140        #[test]
5141        fn a_reply_whose_world_held_is_applied() {
5142            let mut st = new_state_with("x\n");
5143            st.hire(crew_with_scan(EchoesSeal(Negai::Message("ok".into()))));
5144            st.honour_one(Negai::Errand(Box::new(a_scan())));
5145            st.deliver();
5146            assert!(st.messages.iter().any(|m| m == "ok"));
5147        }
5148
5149        /// A scan must NOT be staled by typing. It reads the filesystem; no
5150        /// text revision has anything to say about it, and anchoring one on the
5151        /// buffers would kill every result on the next keystroke.
5152        #[test]
5153        fn typing_does_not_stale_a_scan_reply() {
5154            let mut st = new_state_with("x\n");
5155            st.hire(crew_with_scan(EchoesSeal(Negai::Message("rows".into()))));
5156            st.honour_one(Negai::Errand(Box::new(a_scan())));
5157
5158            st.insert_text("hello");
5159            st.deliver();
5160            assert!(
5161                st.messages.iter().any(|m| m == "rows"),
5162                "a scan does not depend on buffer text: {:?}",
5163                st.messages
5164            );
5165        }
5166
5167        /// The seal's OWN anchor becomes the list's seal. Re-sealing at the
5168        /// arrival world would widen a one-axis claim into an every-buffer one,
5169        /// so the findings would die on the next unrelated edit.
5170        #[test]
5171        fn findings_from_an_errand_keep_the_narrow_seal_they_were_computed_with() {
5172            let mut st = new_state_with("x\n");
5173            st.hire(crew_with_scan(EchoesSeal(Negai::PublishFindings {
5174                list: "grep".into(),
5175                findings: vec![],
5176            })));
5177            st.honour_one(Negai::Errand(Box::new(a_scan())));
5178            st.deliver();
5179
5180            let sealed_with = st.results.get("grep").expect("published").anchor().clone();
5181            let axes = sealed_with.axes();
5182            assert_eq!(axes.len(), 1, "narrow, not the whole world: {axes:?}");
5183            assert!(
5184                matches!(axes[0], Axis::Session(SessionKind::Scan, _)),
5185                "sealed on the scan session: {axes:?}"
5186            );
5187
5188            // …and the consequence that makes it worth doing: an edit
5189            // elsewhere does not discard it.
5190            st.insert_text("more");
5191            assert!(
5192                !st.results
5193                    .get("grep")
5194                    .expect("still there")
5195                    .is_stale(&st.world()),
5196                "an unrelated edit must not stale a scan list"
5197            );
5198        }
5199
5200        /// A directly-dispatched `PublishFindings` — an on-tick producer like
5201        /// the marker scan — still seals at the world, which is correct for it.
5202        /// The special case must not have changed that.
5203        #[test]
5204        fn a_direct_publish_still_seals_at_the_world() {
5205            let mut st = new_state_with("x\n");
5206            st.honour_one(Negai::PublishFindings {
5207                list: "todo".into(),
5208                findings: vec![],
5209            });
5210            let axes = st.results.get("todo").expect("published").anchor().axes();
5211            assert!(
5212                axes.len() > 1,
5213                "the on-tick path anchors on the whole world: {axes:?}"
5214            );
5215        }
5216
5217        /// An empty anchor is fresh against every world, so a forged reply
5218        /// carrying one bypasses the gate entirely. The courier cannot produce
5219        /// this — `seal` returns a `NonEmptyAnchor` — and the test exists to
5220        /// document why that type is not decoration.
5221        #[test]
5222        fn an_empty_anchor_would_bypass_the_gate_which_is_why_seal_cannot_mint_one() {
5223            let mut st = new_state_with("x\n");
5224            st.bump_scan_gen();
5225            st.bump_lsp_gen();
5226            st.insert_text("moved a long way");
5227
5228            st.honour_one(Negai::ErrandReply {
5229                anchor: Anchor::new(),
5230                then: Box::new(Negai::Message("forged".into())),
5231            });
5232            assert!(
5233                st.messages.iter().any(|m| m == "forged"),
5234                "an empty anchor passes any world — the hazard NonEmptyAnchor removes"
5235            );
5236        }
5237
5238        /// Closing the picker supersedes the scan feeding it. Both closing
5239        /// paths must do it — choosing a row closes the overlay exactly as Esc
5240        /// does, and only handling Esc leaves a scan running after every pick.
5241        #[test]
5242        fn closing_the_picker_supersedes_the_scan_it_was_feeding() {
5243            let mut st = new_state_with("x\n");
5244            st.hire(crew_with_scan(EchoesSeal(Negai::Message("rows".into()))));
5245            st.honour_one(Negai::Errand(Box::new(a_scan())));
5246
5247            st.close_picker();
5248            st.deliver();
5249            assert!(
5250                !st.messages.iter().any(|m| m == "rows"),
5251                "rows must not reopen a picker the operator closed: {:?}",
5252                st.messages
5253            );
5254        }
5255
5256        /// The default state. An errand with nobody hired must report that it
5257        /// went nowhere — a request that silently does nothing is the exact
5258        /// failure the pre-courier stub had.
5259        #[test]
5260        fn an_errand_with_no_crew_hired_says_so() {
5261            let mut st = new_state_with("x\n");
5262            st.honour_one(Negai::Errand(Box::new(a_scan())));
5263            st.deliver();
5264            assert!(
5265                st.messages.iter().any(|m| m.contains("scan")),
5266                "the inert crew announces: {:?}",
5267                st.messages
5268            );
5269        }
5270
5271        /// A quiet tick must be free — `deliver` is called on every frame.
5272        #[test]
5273        fn delivering_nothing_does_not_repaint() {
5274            let mut st = new_state_with("x\n");
5275            let before = st.edit_gen();
5276            st.deliver();
5277            assert_eq!(st.edit_gen(), before, "an empty drain is not a change");
5278        }
5279
5280        /// …and a tick that DID deliver must repaint, or the result sits in
5281        /// state that nothing draws.
5282        #[test]
5283        fn delivering_something_repaints() {
5284            let mut st = new_state_with("x\n");
5285            st.hire(crew_with_scan(Says(Negai::Message("hi".into()))));
5286            st.honour_one(Negai::Errand(Box::new(a_scan())));
5287            let before = st.edit_gen();
5288            st.deliver();
5289            assert_ne!(st.edit_gen(), before, "a delivered reply repaints");
5290        }
5291
5292        /// The two session kinds must not alias at the runtime level either: an
5293        /// LSP restart must not discard scan results, and vice versa.
5294        #[test]
5295        fn the_two_session_generations_are_independent() {
5296            let mut st = new_state_with("x\n");
5297            let scan_sealed = ResultList::new(
5298                vec![],
5299                Anchor::new().on(Axis::Session(SessionKind::Scan, st.scan_gen)),
5300            );
5301            st.bump_lsp_gen();
5302            assert!(
5303                !scan_sealed.is_stale(&st.world()),
5304                "an LSP restart must not discard scan results"
5305            );
5306            st.bump_scan_gen();
5307            assert!(scan_sealed.is_stale(&st.world()), "…but a scan bump does");
5308        }
5309
5310        #[test]
5311        fn every_freight_class_seals_on_something() {
5312            let mut st = new_state_with("x\n");
5313            let active = st.active;
5314            for freight in [
5315                a_scan(),
5316                Freight::Diagnostics {
5317                    buffer: active,
5318                    path: "a.nix".into(),
5319                    text: String::new(),
5320                },
5321                Freight::Format {
5322                    path: "a.nix".into(),
5323                    text: String::new(),
5324                },
5325            ] {
5326                let sealed = st.seal(&freight);
5327                assert!(
5328                    !sealed.as_anchor().is_empty(),
5329                    "{} sealed on nothing",
5330                    freight.label()
5331                );
5332            }
5333            let _ = &mut st;
5334        }
5335    }
5336}