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 plugin_host;
11pub use plugin_host::{LazyTrigger, PluginHost};
12
13mod operator_pending;
14pub mod status;
15
16pub use operator_pending::{OpState, OperatorPending};
17pub use status::{PromptKind, StatusModel};
18
19use std::collections::HashMap;
20
21use awase::KeyRepeatGate;
22use escriba_buffer::BufferSet;
23use escriba_buffer::TextRev;
24use escriba_command::CommandRegistry;
25use escriba_core::{
26    Action, Anchored, Bound, BufferId, Cursors, Damage, Edit, EditGen, HighlightEffect, JumpList,
27    Mode, Motion, Operator, Position, Range, TextEffect, WindowId,
28};
29use escriba_input::{InputOutcome, translate_app_event};
30use escriba_keymap::{Key, Keymap};
31use escriba_madoguchi::{Negai, Outcome};
32use escriba_mode::ModalState;
33use escriba_search::{Direction as SearchDirection, MatchCount, SearchState};
34use escriba_ui::chrome::{ChromePalette, FleetTheme};
35use escriba_ui::splash::Splash;
36use escriba_ui::{Layout, Viewport, Window};
37use escriba_vm::{EditorSnapshot, EscribaHost, EscribaVm, VmError};
38use madori::AppEvent;
39use std::time::Instant;
40
41/// Full editor state — the single Rust value the binary hands to the
42/// renderer each frame.
43pub struct EditorState {
44    pub buffers: BufferSet,
45    pub modal: ModalState,
46    /// Search session — the committed pattern, its matches, the live `/`
47    /// prompt and history. Owns no buffer or cursor; it answers questions
48    /// about text and this runtime applies the answers.
49    pub search: SearchState,
50    pub keymap: Keymap,
51    pub commands: CommandRegistry,
52    pub layout: Layout,
53    pub active: BufferId,
54    /// The single typed home for cursor state. Phase-1 holds one primary
55    /// [`Position`]; reads go through [`Self::cursor`], writes through
56    /// [`Self::set_cursor`] → [`Cursors::set_primary`]. There is no loose
57    /// `Position` field beside an unused multi-caret type to desync.
58    cursors: Cursors,
59    pub quit_requested: bool,
60    /// Messages surfaced to the user (status line / `:messages`) — the
61    /// sink for the tatara-lisp `(message …)` effect and other feedback.
62    pub messages: Vec<String>,
63    /// Which match the cursor last landed on (0-based) — the `[3/17]`
64    /// numerator, ANCHORED to the text revision it was computed against.
65    ///
66    /// The anchor is what removes the manual invalidation this field used to
67    /// need. An ordinal indexes a match set; when the text changes the set
68    /// changes underneath it and the number silently means something else.
69    /// Reading through `Anchored::get(current_rev)` makes that a `None`, so
70    /// forgetting to clear is no longer a thing that can be forgotten.
71    search_at: Option<Anchored<usize, TextRev>>,
72    /// The last text change, for `.`.
73    ///
74    /// An action plus whatever was typed while it held Insert open. Both
75    /// halves are needed: `cw` alone is not a change, it is the FIRST HALF of
76    /// one — the text that followed is the rest, and replaying without it
77    /// would delete a word and leave the buffer in Insert.
78    last_change: Option<LastChange>,
79    /// True while an insert session belonging to `last_change` is open, so
80    /// typed characters are appended to it. Cleared on leaving Insert.
81    recording_insert: bool,
82
83    /// Where the cursor was before each far jump — `<C-o>` / `<C-i>`.
84    /// Search commits, `n`/`N` and `*`/`#` all record into it, which is what
85    /// makes a search a place you can come back from.
86    pub jumps: JumpList,
87    /// Generic editor option store (name → value). Written by the
88    /// tatara-lisp `(set-option …)` effect and the declarative
89    /// `defoption` apply path; typed accessors layer on top later.
90    pub options: HashMap<String, String>,
91    /// Cached embedded tatara-lisp runtime, built lazily on first
92    /// `run_lisp`. Caching avoids re-installing the ~175-definition full
93    /// stdlib on every call; the interpreter's top-level env also
94    /// persists across calls, giving REPL-like session semantics (an
95    /// earlier `(define …)` is visible to a later `run_lisp`).
96    lisp_vm: Option<EscribaVm>,
97    /// Keys accumulated for an in-progress multi-key sequence — e.g.
98    /// holding `[,, f]` while waiting for the final key of
99    /// `<leader>ff`. Empty when not mid-sequence. Lives on
100    /// `EditorState` (not `ModalState`) so `escriba-mode` needn't
101    /// depend on `escriba-keymap`'s `Key`.
102    pub pending_keys: Vec<Key>,
103    /// Per-key debouncer for OS key-repeat storms. Holding `j`/`l` makes
104    /// the windowing system deliver one `KeyDown` per repeat tick
105    /// (~30-50ms); without a gate those flood the motion path and thrash
106    /// the viewport. The gate lets ONE event per `min_interval` (80ms
107    /// default — ~12 intentional taps/sec still pass) reach the editor in
108    /// the navigation modes. The fleet primitive (`awase::KeyRepeatGate`,
109    /// the same one mado uses) is reused — not reinvented.
110    repeat_gate: KeyRepeatGate<Key>,
111    /// Runtime lazy-activation host for USER plugin caixas (the bundled
112    /// default catalog is applied eagerly at boot, not through here).
113    /// A command / filetype-open / event fires the matching plugins'
114    /// entries through the escriba-lisp apply paths. See [`PluginHost`].
115    pub plugin_host: PluginHost,
116    /// The unnamed register — the home for text an operator yanks or
117    /// deletes (`Operator::leaves_register`). `None` until the first
118    /// register-leaving operator runs. Phase-1 holds the single unnamed
119    /// register; named registers (`"ay`) layer on later.
120    register: Option<String>,
121    /// The operator-pending FSM (`d`/`c`/`y` then a motion → `dw`/`c$`/`y0`),
122    /// standing on the fleet `zenmai` Mealy-machine primitive. Every dispatched
123    /// action passes through it; only an operator-then-motion pair is rewritten
124    /// into an [`Action::ApplyOperator`].
125    op_pending: zenmai::Stateful<OperatorPending>,
126    /// Monotonic refresh-generation stamp — the root of the sealed refresh
127    /// tree (`theory/ESCRIBA.md` §Refresh-Seal). Bumped on every applied
128    /// action + resize; the renderer gates on it so an idle frame does zero
129    /// re-highlight / re-shape, and a stale frame is unreachable.
130    edit_gen: EditGen,
131    /// The accumulated dirty region since the renderer last drained it (M1).
132    /// Only ever widened via [`Damage::join`] at the mutation funnel, so it
133    /// always covers the changed region (`Damage ⊇ changed`); the renderer
134    /// drains it with [`take_damage`](Self::take_damage) to scope its work.
135    damage: Damage,
136    /// The theme every face paints with.
137    ///
138    /// ONE owner. Before this, `(deftheme :preset …)` parsed, validated,
139    /// resolved to a real `FleetTheme` — and then nothing consumed it,
140    /// because each renderer called `ChromePalette::prescribed()` at every
141    /// paint site. The declaration was honoured on paper only. Holding it
142    /// here means a face reads the operator's theme the same way it reads
143    /// the cursor: from the state, per frame.
144    theme: FleetTheme,
145    /// `theme` resolved to concrete colours — cached because it is a plain
146    /// `Copy` struct read many times per frame, and re-derived only in
147    /// [`set_theme`](Self::set_theme), so the two cannot disagree.
148    chrome: ChromePalette,
149    /// How deep the current command dispatch is nested.
150    ///
151    /// `Negai::RunCommand` lets a command invoke a command, which is useful
152    /// and which can also recurse forever. The budget makes the runaway
153    /// bounded and REPORTED rather than a stack overflow — the difference
154    /// between a typed refusal and the editor dying under the operator.
155    dispatch_depth: u8,
156    /// Every live result list — diagnostics, hunks, grep hits, TODOs.
157    ///
158    /// Public so a producer outside the runtime can publish into it once the
159    /// courier lands; today the only producer is the marker scan.
160    pub results: escriba_shirube::ListRegistry,
161    /// The open picker, if any.
162    ///
163    /// `Option<Picker>` on the state, exactly like `splash` — deliberately
164    /// NOT a `Mode` variant. A mode is a state keys are interpreted IN; this
165    /// is a surface that OWNS keys while it is up, which is a different
166    /// thing and composes differently with the keymap.
167    picker: Option<escriba_ui::picker::Picker>,
168    /// The git-index generation. See [`world`](Self::world) — every axis the
169    /// world can move is emitted unconditionally, so a producer anchoring on
170    /// one is not born permanently stale.
171    index_rev: escriba_shirube::IndexRev,
172    /// The external-session generation (LSP restart, debug session, test run).
173    session_gen: escriba_shirube::SessionGen,
174    /// Extension → language facts, populated from `(defmode …)`.
175    ///
176    /// The consumer `:commentstring` never had. Public so the binary's apply
177    /// pass can fill it the way it fills the keymap and the option store.
178    pub filetypes: escriba_core::FiletypeTable,
179    /// The start screen, while it is up.
180    ///
181    /// `Some` only between boot and the first keypress, and only when the
182    /// editor opened with no file. It is deliberately NOT a `Mode`: a mode
183    /// is a state keys are interpreted *in*, and the splash interprets
184    /// exactly one key before it is gone. Modelling it as `Option<Splash>`
185    /// keeps the modal state machine's variant set — and every exhaustive
186    /// match over it — untouched.
187    splash: Option<Splash>,
188}
189
190/// What the start screen did with a keypress.
191///
192/// Total, and matched exhaustively at its one call site, so a future
193/// outcome (a menu that opens a submenu, say) is a compile error rather
194/// than a key that silently falls through to the buffer.
195enum SplashKey {
196    /// No start screen is up — the key is the buffer's.
197    NotShowing,
198    /// The key selected a menu entry; run this.
199    Ran(Action),
200    /// The screen is gone and the key was not a menu key, so it still
201    /// means whatever it normally means. Anything else would make the
202    /// first keystroke after boot vanish.
203    Dismissed,
204}
205
206// ─── The counter, and the one place slips become mutations ───────────────
207
208/// `EditorState` read through the counter.
209///
210/// Borrowed, never copied: building it is free, so a command dispatch does
211/// not pay for a snapshot of the buffers.
212pub struct EditorWindow<'a> {
213    state: &'a EditorState,
214}
215
216impl escriba_madoguchi::CursorView for EditorWindow<'_> {
217    fn position(&self) -> Position {
218        self.state.cursor()
219    }
220    fn mode(&self) -> Mode {
221        self.state.modal.mode()
222    }
223}
224
225impl escriba_madoguchi::SyntaxView for EditorWindow<'_> {
226    fn filetype(&self) -> Option<&escriba_core::Filetype> {
227        let path = self.state.buffers.get(self.state.active)?.path.as_deref()?;
228        self.state.filetypes.resolve(path)
229    }
230}
231
232impl escriba_madoguchi::SearchView for EditorWindow<'_> {
233    fn pattern(&self) -> Option<&str> {
234        self.state.search.committed_pattern()
235    }
236    fn match_count(&self) -> Option<usize> {
237        // `None` means "nothing committed", which is not the same as zero
238        // matches — a distinction the status line already makes and that a
239        // handler must not have to re-derive.
240        self.state
241            .search
242            .committed_pattern()
243            .map(|_| self.state.search.match_count())
244    }
245    fn is_prompting(&self) -> bool {
246        self.state.search.is_prompting()
247    }
248}
249
250impl escriba_madoguchi::Snapshot for EditorWindow<'_> {
251    fn active(&self) -> Option<&dyn escriba_madoguchi::BufferView> {
252        self.buffer(self.state.active)
253    }
254    fn buffer(&self, id: BufferId) -> Option<&dyn escriba_madoguchi::BufferView> {
255        self.state
256            .buffers
257            .get(id)
258            .map(|b| b as &dyn escriba_madoguchi::BufferView)
259    }
260    fn buffer_ids(&self) -> Vec<BufferId> {
261        self.state.buffers.ids()
262    }
263    fn cursor(&self) -> &dyn escriba_madoguchi::CursorView {
264        self
265    }
266    fn option(&self, name: &str) -> Option<&str> {
267        self.state.options.get(name).map(String::as_str)
268    }
269    fn search(&self) -> &dyn escriba_madoguchi::SearchView {
270        self
271    }
272    fn syntax(&self) -> &dyn escriba_madoguchi::SyntaxView {
273        self
274    }
275}
276
277impl EditorState {
278    /// A read-only window onto this editor.
279    #[must_use]
280    pub fn window(&self) -> EditorWindow<'_> {
281        EditorWindow { state: self }
282    }
283
284    /// Honour an [`Outcome`] — the ONLY place slips become mutations.
285    ///
286    /// Every `&mut self` in the dispatch path lives here. A command cannot
287    /// reach editor state, so if the editor ends up in a state nobody
288    /// designed, this function is where it happened; that narrowing is the
289    /// whole return on the seam.
290    ///
291    /// A failed outcome's slips are DROPPED rather than half-applied: a
292    /// handler that reported failure has no business also mutating, and
293    /// applying part of what it asked for is how an editor reaches a state
294    /// nobody designed.
295    pub fn interpret(&mut self, outcome: Outcome) {
296        if let Some(m) = outcome.verdict.message() {
297            self.messages.push(m.to_string());
298            self.damage = self.damage.join(Damage::Viewport);
299            self.bump_gen();
300        }
301        if outcome.verdict.is_failure() {
302            return;
303        }
304        for slip in outcome.slips {
305            self.honour(slip);
306        }
307    }
308
309    /// Lower an [`Action`] to slips, when it has an exact slip equivalent.
310    ///
311    /// `None` means "editor mechanics" — 23 of the 30 variants are prompt
312    /// editing, the operator-pending FSM, motion resolution, the jumplist,
313    /// the dot register. Those are the KEYMAP's vocabulary, not the AUTHORED
314    /// one, and forcing them into `Negai` would put `PromptClearToStart` and
315    /// `SearchPreviewStep` in front of every plugin author and make the
316    /// capability question meaningless (what capability does a caret move
317    /// read?). One type serving two vocabularies is the mistake this avoids.
318    ///
319    /// The plan's M3 predicate was "apply_resolved contains zero `self.`
320    /// mutations", which would have forced exactly that. Amended: the
321    /// invariant worth having is ONE IMPLEMENTATION PER MUTATION, not one
322    /// vocabulary. See docs/backlog-plan.md §V Phase 1.
323    fn lower(action: &Action, active: BufferId) -> Option<Vec<Negai>> {
324        Some(match action {
325            Action::Quit => vec![Negai::Quit],
326            Action::ClearSearchHighlight => vec![Negai::ClearSearchHighlight],
327            Action::Save => vec![Negai::Save { buffer: active }],
328            Action::Undo => vec![Negai::Undo { buffer: active }],
329            Action::Redo => vec![Negai::Redo { buffer: active }],
330            // `apply_edit` was a STUB that did nothing, so this action was a
331            // silent no-op while `Negai::Edit` applied for real. Lowering it
332            // makes keymap-originated edits work for the first time — and
333            // nothing binds it today, so the duplication goes away at zero
334            // risk.
335            Action::Edit(edit) => vec![Negai::Edit {
336                buffer: active,
337                edit: edit.clone(),
338            }],
339            _ => return None,
340        })
341    }
342
343    /// What the world currently is, for freshness.
344    ///
345    /// One text axis per open buffer. A list sealed against this is fresh
346    /// exactly while the buffers it depends on are unchanged — and a buffer
347    /// that has since CLOSED drops out, which makes lists about it stale
348    /// rather than silently kept.
349    #[must_use]
350    pub fn world(&self) -> escriba_shirube::Anchor {
351        let mut a = escriba_shirube::Anchor::new();
352        for id in self.buffers.ids() {
353            if let Some(b) = self.buffers.get(id) {
354                a = a.on(escriba_shirube::Axis::Text(id, b.text_rev()));
355            }
356        }
357        // Every axis the world can move, ALWAYS present — not only the ones
358        // some producer happens to use today.
359        //
360        // `Anchor::is_fresh` treats an ABSENT axis as stale, deliberately:
361        // unknowable is not unchanged. The consequence, unnoticed until a
362        // recon pass went looking, is that a list anchored on an axis this
363        // function never emits is born PERMANENTLY stale — `]c` would answer
364        // "that list is out of date" forever, and nothing would say why. The
365        // two-axis model was built for git hunks and then only ever fed one
366        // axis.
367        //
368        // Emitting them unconditionally means a producer can anchor on any
369        // axis and get an honest answer. A counter that never moves reads as
370        // "unchanged", which is exactly right for a plane escriba does not
371        // track yet.
372        a = a.on(escriba_shirube::Axis::Index(self.index_rev));
373        a.on(escriba_shirube::Axis::Session(self.session_gen))
374    }
375
376    /// Where the cursor is, WITH the buffer it is in.
377    ///
378    /// Every jumplist push goes through this. A bare `Position` is what let
379    /// `<C-o>` return to the right line in the wrong file.
380    #[must_use]
381    pub fn spot(&self) -> escriba_core::Spot {
382        escriba_core::Spot::new(self.active, self.cursor())
383    }
384
385    /// Move to a `Spot`, switching buffer if it names another one.
386    ///
387    /// The read half of [`spot`](Self::spot). `<C-o>` and `<C-i>` both land
388    /// here so neither can forget the buffer.
389    fn goto_spot(&mut self, s: escriba_core::Spot) {
390        if s.buffer != self.active && self.buffers.get(s.buffer).is_some() {
391            self.active = s.buffer;
392        }
393        let clamped = self
394            .buffers
395            .get(self.active)
396            .map_or(s.pos, |b| b.clamp(s.pos));
397        self.set_cursor(clamped);
398    }
399
400    /// Advance the git-index generation — every list anchored on
401    /// `Axis::Index` goes stale.
402    ///
403    /// Not called yet; a git layer calls it after a stage/reset. Present so
404    /// the axis is WIRED rather than declared, because an axis nothing can
405    /// move is indistinguishable from an axis that does not exist.
406    pub fn bump_index_rev(&mut self) {
407        self.index_rev = escriba_shirube::IndexRev(self.index_rev.0.wrapping_add(1));
408    }
409
410    /// Advance the external-session generation — LSP restart, debug session,
411    /// test-runner invocation. See [`bump_index_rev`](Self::bump_index_rev).
412    pub fn bump_session_gen(&mut self) {
413        self.session_gen = escriba_shirube::SessionGen(self.session_gen.0.wrapping_add(1));
414    }
415
416    /// Move the cursor to the next/previous finding in `list`.
417    ///
418    /// Reports the wrap, because `n`/`N` do and a reader losing their place
419    /// in a long file is the same problem either way.
420    fn walk_list(&mut self, list: &str, forward: bool) {
421        let world = self.world();
422        let Some(result) = self.results.get(list) else {
423            let mut m = String::from("no list named ");
424            m.push_str(list);
425            self.messages.push(m);
426            return;
427        };
428        if result.is_stale(&world) {
429            self.messages
430                .push("that list is out of date — run it again".to_string());
431            return;
432        }
433        let here = (Some(self.active), self.cursor().line);
434        let Some(found) = result.step(&world, here, forward, escriba_shirube::Bound::Exclusive)
435        else {
436            let mut m = String::from("no entries in ");
437            m.push_str(list);
438            self.messages.push(m);
439            return;
440        };
441        let site = found.site.clone();
442        let msg = found.message.clone();
443        self.jump_to_site(&site);
444        self.messages.push(msg);
445    }
446
447    /// Move the cursor to a located finding's SITE — the one operation that
448    /// cannot drop the buffer half of a location.
449    ///
450    /// A `Site` is `(buffer, range)`. Every jumper before this re-derived the
451    /// move itself and clamped against `self.active`, so a finding in another
452    /// file landed on the right LINE in the WRONG file. `on_line` and
453    /// `worst_on_line` already filter by buffer, so the gutter and the walker
454    /// disagreed — latent only because the first producer scanned one buffer.
455    ///
456    /// Every future producer (diagnostics, hunks, grep hits, test failures)
457    /// is cross-file by nature, which is why this is a shared operation
458    /// rather than a fix at the one call site that has it wrong today.
459    ///
460    /// Always a FAR jump: it pushes the jumplist, so `<C-o>` returns from a
461    /// `]t` exactly as it returns from an `n`.
462    pub fn jump_to_site(&mut self, site: &escriba_shirube::Site) {
463        self.jumps.push(self.spot());
464        // Switch buffers FIRST — clamping against the wrong buffer is how the
465        // position gets silently mangled before anyone can notice.
466        if let Some(target) = site.buffer {
467            if target != self.active && self.buffers.get(target).is_some() {
468                self.active = target;
469                self.refollow_cursor();
470            }
471        }
472        let to = site.range.start;
473        let clamped = self.buffers.get(self.active).map_or(to, |b| b.clamp(to));
474        self.set_cursor(clamped);
475    }
476
477    /// Close a buffer, keeping "there is always an active buffer" true.
478    ///
479    /// The invariant is the whole reason this is not just
480    /// `self.buffers.close(id)`. `EditorState::active` is a `BufferId`, not
481    /// an `Option`, so a dangling active is not a degraded state — it is a
482    /// state where every read of the active buffer returns `None` and the
483    /// editor renders `<no buffer>` forever. Closing the last buffer opens a
484    /// scratch rather than emptying the set, which is what vim's `:bd` does
485    /// and what the type demands.
486    fn close_buffer(&mut self, id: BufferId) {
487        if self.buffers.close(id).is_none() {
488            self.messages.push("no such buffer".to_string());
489            return;
490        }
491        if self.active != id {
492            return;
493        }
494        // The active buffer went. Prefer the next one by id so repeated
495        // closes walk forward predictably rather than jumping around.
496        let next = self.buffers.ids().into_iter().find(|b| *b > id);
497        self.active = match next.or_else(|| self.buffers.ids().into_iter().next_back()) {
498            Some(b) => b,
499            None => self.buffers.scratch(""),
500        };
501        self.set_cursor(Position::ZERO);
502        if let Some(w) = self.layout.active_window_mut() {
503            w.buffer_id = self.active;
504        }
505    }
506
507    /// Move to the next or previous buffer, wrapping.
508    fn cycle_buffer(&mut self, forward: bool) {
509        let ids = self.buffers.ids();
510        if ids.len() < 2 {
511            self.messages.push("only one buffer".to_string());
512            return;
513        }
514        let at = ids.iter().position(|b| *b == self.active).unwrap_or(0);
515        let next = if forward {
516            (at + 1) % ids.len()
517        } else {
518            (at + ids.len() - 1) % ids.len()
519        };
520        self.active = ids[next];
521        self.set_cursor(Position::ZERO);
522        if let Some(w) = self.layout.active_window_mut() {
523            w.buffer_id = self.active;
524        }
525    }
526
527    /// Re-clamp the cursor and re-contain the viewport after a buffer
528    /// mutation.
529    ///
530    /// An undo can SHRINK the buffer under a cursor that was legal a moment
531    /// ago, leaving it out of bounds and its viewport scrolled past the end.
532    /// The Action executor has always done this (`self.set_cursor(self.cursor())`
533    /// after undo/redo/save); the M1 interpreter did NOT, so `u` re-followed
534    /// and `:undo` did not — two implementations of one operation, already
535    /// drifted within one milestone of being written. Naming it once is the
536    /// fix; lowering the Action arms onto the same slips is what keeps it
537    /// fixed.
538    fn refollow(&mut self) {
539        self.set_cursor(self.cursor());
540    }
541
542    /// Apply one slip and record what it damaged.
543    ///
544    /// The bookkeeping wrapper. The Action executor calls
545    /// [`honour_one`](Self::honour_one) directly because it does its own,
546    /// wider bookkeeping (the dot register, the S3 damage seal) around a
547    /// whole action.
548    fn honour(&mut self, slip: Negai) {
549        let touches_text = slip.touches_text();
550        self.honour_one(slip);
551        self.damage = self.damage.join(if touches_text {
552            Damage::Full
553        } else {
554            Damage::Viewport
555        });
556        self.bump_gen();
557    }
558
559    /// Apply one slip. THE single implementation of every mutation a slip
560    /// can ask for.
561    ///
562    /// Total over `Negai`: a new request variant is a compile error here
563    /// rather than a request silently ignored — the same failure Phase 0
564    /// removed one layer up.
565    fn honour_one(&mut self, slip: Negai) {
566        match slip {
567            Negai::Edit { buffer, edit } => {
568                if let Some(b) = self.buffers.get_mut(buffer) {
569                    let _ = b.apply(&edit);
570                }
571                self.refollow();
572            }
573            Negai::SetCursor { buffer, to } => {
574                // Clamping is the interpreter's job, exactly so that no
575                // handler has to re-implement it and get it wrong.
576                let clamped = self.buffers.get(buffer).map_or(to, |b| b.clamp(to));
577                self.set_cursor(clamped);
578            }
579            Negai::EnterMode(m) => self.modal.enter(m),
580            Negai::OpenPicker(source) => self.open_picker(source),
581            Negai::GrepProject { pattern } => self.grep_project(&pattern),
582            Negai::CycleBuffer { forward } => self.cycle_buffer(forward),
583            Negai::FocusBuffer(id) => {
584                if self.buffers.get(id).is_some() {
585                    self.active = id;
586                }
587            }
588            Negai::OpenPath(path) => match self.buffers.open(&path) {
589                Ok(id) => self.active = id,
590                Err(e) => self.messages.push(e.to_string()),
591            },
592            Negai::CloseBuffer(id) => self.close_buffer(id),
593            Negai::Save { buffer } => {
594                if let Some(b) = self.buffers.get_mut(buffer) {
595                    if let Err(e) = b.save() {
596                        self.messages.push(e.to_string());
597                    }
598                }
599                self.refollow();
600            }
601            Negai::Undo { buffer } => {
602                if let Some(b) = self.buffers.get_mut(buffer) {
603                    let _ = b.undo();
604                }
605                self.refollow();
606            }
607            Negai::Redo { buffer } => {
608                if let Some(b) = self.buffers.get_mut(buffer) {
609                    let _ = b.redo();
610                }
611                self.refollow();
612            }
613            Negai::Yank { text, .. } => self.register = Some(text),
614            Negai::ClearSearchHighlight => self.search.clear_highlight(),
615            Negai::SetOption { name, value } => {
616                self.options.insert(name, value);
617            }
618            Negai::InsertText(text) => self.insert_text(&text),
619            Negai::RunCommand { name, args } => self.run_command(&name, &args),
620            Negai::PublishFindings { list, findings } => {
621                let world = self.world();
622                self.results
623                    .publish(list, escriba_shirube::ResultList::new(findings, world));
624            }
625            Negai::WalkList { list, forward } => self.walk_list(&list, forward),
626            Negai::Message(m) => self.messages.push(m),
627            Negai::Quit => self.quit_requested = true,
628            // Both suspend the dispatch and need machinery that does not
629            // exist yet — the courier (Phase 5) and the AwaitKey resume
630            // (M3). Announced, never silently dropped: a slip that vanishes
631            // is the class Phase 0 sealed.
632            Negai::Errand(_) | Negai::AwaitKey { .. } => {
633                self.messages
634                    .push("deferred work is not wired yet".to_string());
635            }
636        }
637    }
638}
639
640/// Outcome of feeding one key to the multi-key pending-stroke loop.
641enum SeqStep {
642    /// Key consumed into an in-progress sequence; wait for the next.
643    Pending,
644    /// A full bound sequence resolved — run this action.
645    Resolved(Action),
646    /// Key is not part of any sequence; hand it to single-key dispatch.
647    Passthrough,
648}
649
650/// Keys whose HELD repeat is a viewport storm, and which the repeat gate
651/// therefore exists to debounce.
652///
653/// This is an ALLOW-LIST, and it used to be the complement — an exception list
654/// of "discrete" keys that grew three times (`n`/`N`/`*`/`#`, then `.`/`u`/
655/// `<C-r>`, then `/`/`?`/`:`), each time because a key had been silently
656/// swallowed and someone noticed. The third growth is the signal that the
657/// default was backwards: almost every key in a modal editor is a discrete,
658/// deliberate press, and only a handful are ones you HOLD.
659///
660/// Inverting it makes the failure mode safe. Forgetting to list a key here now
661/// means it is ungated — one extra keypress honoured — instead of silently
662/// dropped, and a dropped key is indistinguishable from a dead one.
663///
664/// Measured cost of the old direction: `/foo<CR>` then `/<CR>` (vim's
665/// reuse-the-previous-pattern) lost the second `/` outright, because the gate
666/// is keyed by KEY and the two presses fell inside one debounce window.
667const fn is_repeat_storm_candidate(key: &Key) -> bool {
668    matches!(
669        key,
670        // The four navigation keys a user actually holds down. `h`/`l` and
671        // `j`/`k` flood the motion path and thrash the viewport; everything
672        // else is pressed once and meant once.
673        Key::Char('h')
674            | Key::Char('j')
675            | Key::Char('k')
676            | Key::Char('l')
677            | Key::Left
678            | Key::Right
679            | Key::Up
680            | Key::Down
681    )
682}
683
684/// Turn a command failure into the sentence an operator should read.
685///
686/// The two failures mean genuinely different things and must not be reported
687/// the same way:
688///
689/// - `:flurb` — the operator typed a name that does not exist. "command not
690///   found" is exactly right; it says *you* made a typo.
691/// - `<leader>ff` bound to `picker.files` — escriba's OWN shipped config
692///   declares this, `--list-rc` counts it, and it is not built yet. Telling
693///   the operator "command not found" blames them for a gap we shipped.
694///
695/// The discriminator is the dotted form. `:action` takes action SYMBOLS
696/// (`picker.files`), never command names — that boundary is already pinned by
697/// `action_naming_a_command_is_inert_not_recursive` in escriba-command. So a
698/// dotted name that reached dispatch and resolved to nothing is a declared
699/// capability with no implementation, which is precisely what the 85 entries
700/// in `escriba/tests/action_resolution.rs` are.
701fn describe_command_failure(name: &str, e: &escriba_command::CommandError) -> String {
702    use escriba_command::CommandError as E;
703    match e {
704        // Already the right words — the registry knew it was declared.
705        E::Unhandled(_) => e.to_string(),
706        E::NotFound(n) if n.contains('.') => {
707            let mut m = String::with_capacity(n.len() + 48);
708            m.push('`');
709            m.push_str(n);
710            m.push_str("` is declared but not implemented yet");
711            m
712        }
713        _ => {
714            let _ = name;
715            e.to_string()
716        }
717    }
718}
719
720/// What committing the open search prompt did.
721///
722/// The two commit paths — bare `/` and operated `d/` — used to own private
723/// copies of the whole sequence (read origin+skip, `accept`, three-arm
724/// match, `commit_step_skipping`), and they drifted: the operated one
725/// never reported the wrap, so `d/foo<CR>` that wrapped the file was
726/// silent where `/foo<CR>` printed "search hit BOTTOM, continuing at TOP".
727///
728/// Total, and matched exhaustively at BOTH call sites, so a new outcome is
729/// a compile error in two places rather than a case one path quietly
730/// forgets. It does not make divergence impossible — the two paths
731/// genuinely differ at the landing step — it makes FORGETTING A CASE
732/// impossible, which is the failure that actually happened.
733enum CommitOutcome {
734    /// The prompt committed and a match was found.
735    Landed {
736        origin: usize,
737        step: escriba_search::Step,
738    },
739    /// Committed, but nothing matched. E486 already reported.
740    NotFound,
741    /// Nothing typed and no previous pattern. E35 already reported.
742    NoPrevious,
743    /// No prompt was open.
744    NoPrompt,
745}
746
747/// A replayable text change.
748#[derive(Debug, Clone)]
749struct LastChange {
750    /// The action that began the change.
751    action: Action,
752    /// How many times it ran.
753    count: u32,
754    /// Characters typed while the change held Insert mode open.
755    inserted: String,
756}
757
758impl EditorState {
759    /// Build a fresh editor with one buffer (scratch or file-backed).
760    pub fn new_with_buffer(initial: BufferSet, active: BufferId) -> Self {
761        let window = Window {
762            id: WindowId(1),
763            buffer_id: active,
764            viewport: Viewport {
765                top_line: 0,
766                left_column: 0,
767                visible_lines: 40,
768                visible_columns: 160,
769            },
770        };
771        Self {
772            buffers: initial,
773            modal: ModalState::new(),
774            search: SearchState::new(escriba_search::CaseMode::Smart),
775            search_at: None,
776            last_change: None,
777            recording_insert: false,
778            jumps: JumpList::new(),
779            keymap: Keymap::default_vim(),
780            commands: CommandRegistry::default_set(),
781            layout: Layout::single(window),
782            active,
783            cursors: Cursors::single(Position::ZERO),
784            quit_requested: false,
785            register: None,
786            op_pending: zenmai::Stateful::new(OpState::Resting),
787            messages: Vec::new(),
788            options: HashMap::new(),
789            lisp_vm: None,
790            pending_keys: Vec::new(),
791            repeat_gate: KeyRepeatGate::new(),
792            plugin_host: PluginHost::default(),
793            edit_gen: EditGen::default(),
794            damage: Damage::None,
795            // The FLEET default until an rc says otherwise — never a
796            // hand-written theme name, so a fleet re-point lands for free.
797            dispatch_depth: 0,
798            filetypes: escriba_core::FiletypeTable::new(),
799            results: escriba_shirube::ListRegistry::new(),
800            picker: None,
801            index_rev: escriba_shirube::IndexRev::default(),
802            session_gen: escriba_shirube::SessionGen::default(),
803            theme: FleetTheme::prescribed_default(),
804            chrome: ChromePalette::prescribed(),
805            splash: None,
806        }
807    }
808
809    /// The theme this editor is set to.
810    #[must_use]
811    pub const fn theme(&self) -> FleetTheme {
812        self.theme
813    }
814
815    /// The colours every face paints with — read once per frame.
816    #[must_use]
817    pub const fn chrome(&self) -> ChromePalette {
818        self.chrome
819    }
820
821    /// Point the editor at a theme. The wiring that makes
822    /// `(deftheme :preset …)` real.
823    ///
824    /// Bumps the refresh generation, because a theme change repaints
825    /// everything: the GPU face caches its shaped buffer against that
826    /// generation and would otherwise keep the old colours until an
827    /// unrelated edit happened to invalidate it.
828    pub fn set_theme(&mut self, theme: FleetTheme) {
829        if self.theme == theme {
830            return;
831        }
832        self.theme = theme;
833        self.chrome = ChromePalette::for_theme(theme);
834        self.damage = self.damage.join(Damage::Viewport);
835        self.bump_gen();
836    }
837
838    /// The start screen, if one is up. Renderers paint this INSTEAD of the
839    /// buffer pane; `None` is the ordinary editor.
840    #[must_use]
841    pub fn splash(&self) -> Option<&Splash> {
842        self.splash.as_ref()
843    }
844
845    /// Raise the start screen. The binary calls this at boot when no file
846    /// was named; an empty splash is refused so a face never has to render
847    /// a blank screen over a perfectly good buffer.
848    pub fn set_splash(&mut self, splash: Splash) {
849        if splash.is_empty() {
850            return;
851        }
852        self.splash = Some(splash);
853        self.damage = self.damage.join(Damage::Viewport);
854        self.bump_gen();
855    }
856
857    /// Take the start screen down. Idempotent; bumps the refresh generation
858    /// only when something actually changed, so dismissing twice does not
859    /// cost a repaint.
860    pub fn dismiss_splash(&mut self) {
861        if self.splash.take().is_some() {
862            self.damage = self.damage.join(Damage::Viewport);
863            self.bump_gen();
864        }
865    }
866
867    /// Offer `key` to the start screen.
868    ///
869    /// A menu key runs its entry; ANY other key simply takes the screen
870    /// down and is then handled normally — so the first thing an operator
871    /// types is never swallowed.
872    /// The open picker, for a face to paint.
873    #[must_use]
874    pub fn picker(&self) -> Option<&escriba_ui::picker::Picker> {
875        self.picker.as_ref()
876    }
877
878    /// Give an open picker the key.
879    ///
880    /// Runs BEFORE the keymap, and before the sequence stepper: while a
881    /// picker is up it owns every key, including ones it has no meaning for.
882    /// An overlay that let unknown keys fall through would edit the file
883    /// behind itself.
884    fn consume_picker_key(&mut self, key: &Key) -> escriba_ui::picker::Consumed {
885        use escriba_ui::picker::Consumed;
886        let Some(p) = self.picker.as_mut() else {
887            return Consumed::NotShowing;
888        };
889        let outcome = p.on_key(key);
890        match &outcome {
891            Consumed::Dismissed | Consumed::Chose(_) => {
892                self.picker = None;
893                self.bump_gen();
894            }
895            Consumed::Held => self.bump_gen(),
896            Consumed::NotShowing => {}
897        }
898        outcome
899    }
900
901    /// Lower an accepted pick into the ONE interpreter.
902    ///
903    /// The whole reason `Choice` is a closed enum: a new source must decide
904    /// here, and the compiler says so.
905    fn honour_choice(&mut self, choice: escriba_ui::picker::Choice) {
906        use escriba_ui::picker::Choice;
907        let slip = match choice {
908            Choice::Buffer(id) => Negai::FocusBuffer(id),
909            Choice::Command(name) => Negai::RunCommand {
910                name,
911                args: Vec::new(),
912            },
913            Choice::OpenFile(path) => Negai::OpenPath(path),
914            Choice::Location { path, line } => {
915                // Open FIRST, then jump: the buffer may not exist yet, and
916                // `jump_to_site` needs a BufferId. Two slips, one interpret.
917                self.interpret(Outcome::did(vec![Negai::OpenPath(path)]));
918                let site = escriba_shirube::Site::in_buffer(
919                    self.active,
920                    escriba_core::Range::new(
921                        escriba_core::Position::new(line, 0),
922                        escriba_core::Position::new(line, 1),
923                    ),
924                );
925                self.jump_to_site(&site);
926                return;
927            }
928        };
929        self.interpret(Outcome::did(vec![slip]));
930    }
931
932    /// How many files a project grep will read, and how many hits it keeps.
933    ///
934    /// BOUNDED, and the bound is here rather than hidden, because this is a
935    /// SYNCHRONOUS scan on the editor's own thread. The interpreter already
936    /// does synchronous filesystem I/O (`OpenPath`, `Save`), so the posture
937    /// is not new — but those touch one file and this walks a tree, which is
938    /// the first one big enough to freeze the editor.
939    ///
940    /// The DESTINATION is the courier: an errand that scans off-thread and
941    /// delivers results as they arrive, with no ceiling at all. This bound is
942    /// the interim that ships a working grep meanwhile, and it is a real
943    /// limit — a match past the ceiling is NOT found, and the picker says so
944    /// rather than presenting a truncated list as complete.
945    const GREP_FILE_LIMIT: usize = 2_000;
946    const GREP_HIT_LIMIT: usize = 500;
947
948    /// Walk the working directory, bounded, returning `(files, truncated)`.
949    ///
950    /// ONE walker. grep, files and project each need to enumerate the tree,
951    /// and three copies of a bounded traversal is three places to get the
952    /// ceiling, the skip-list, or the truncation report subtly different.
953    ///
954    /// Skips dotfiles, `target` and `node_modules`. That is NOT a gitignore
955    /// implementation and does not pretend to be — a real ignore crate comes
956    /// with the courier.
957    fn walk_project(limit: usize) -> (Vec<std::path::PathBuf>, bool) {
958        let mut out = Vec::new();
959        let mut truncated = false;
960        let mut stack = vec![std::path::PathBuf::from(".")];
961        while let Some(dir) = stack.pop() {
962            let Ok(entries) = std::fs::read_dir(&dir) else {
963                continue;
964            };
965            for entry in entries.flatten() {
966                let name = entry.file_name();
967                let name = name.to_string_lossy();
968                if name.starts_with('.') || name == "target" || name == "node_modules" {
969                    continue;
970                }
971                let path = entry.path();
972                if entry.file_type().is_ok_and(|t| t.is_dir()) {
973                    stack.push(path);
974                    continue;
975                }
976                if out.len() >= limit {
977                    truncated = true;
978                    return (out, truncated);
979                }
980                out.push(path);
981            }
982        }
983        (out, truncated)
984    }
985
986    /// Say plainly when a bounded scan stopped short.
987    ///
988    /// A truncated list presented as complete is the failure this codebase
989    /// keeps finding in itself; it does not get to ship one.
990    fn report_truncation(&mut self, truncated: bool) {
991        if truncated {
992            self.messages
993                .push("scan stopped at the limit — results are INCOMPLETE".to_string());
994        }
995    }
996
997    /// Scan the working directory for `pattern`, bounded.
998    fn grep_project(&mut self, pattern: &str) {
999        use escriba_ui::picker::{Choice, Picker, PickerItem, Source};
1000        if pattern.is_empty() {
1001            self.messages.push("grep: empty pattern".to_string());
1002            return;
1003        }
1004        let (files, mut truncated) = Self::walk_project(Self::GREP_FILE_LIMIT);
1005        let mut items: Vec<PickerItem<Choice>> = Vec::new();
1006        'outer: for path in files {
1007            let Ok(text) = std::fs::read_to_string(&path) else {
1008                continue; // binary or unreadable — not an error worth reporting
1009            };
1010            for (n, line) in text.lines().enumerate() {
1011                if !line.contains(pattern) {
1012                    continue;
1013                }
1014                if items.len() >= Self::GREP_HIT_LIMIT {
1015                    truncated = true;
1016                    break 'outer;
1017                }
1018                let Ok(n) = u32::try_from(n) else { break };
1019                let mut label = String::with_capacity(80);
1020                label.push_str(&path.to_string_lossy());
1021                label.push(':');
1022                label.push_str(&(n + 1).to_string());
1023                label.push_str("  ");
1024                label.push_str(line.trim());
1025                items.push(PickerItem::new(
1026                    Choice::Location {
1027                        path: path.clone(),
1028                        line: n,
1029                    },
1030                    label,
1031                ));
1032            }
1033        }
1034        if items.is_empty() {
1035            let mut m = String::from("grep: no matches for ");
1036            m.push_str(pattern);
1037            self.messages.push(m);
1038            return;
1039        }
1040        if truncated {
1041            // Stated, never silent. A truncated list presented as complete is
1042            // the failure this whole codebase keeps finding.
1043            self.messages
1044                .push("grep: stopped at the scan limit — results are INCOMPLETE".to_string());
1045        }
1046        self.picker = Some(Picker::open(Source::Grep, items));
1047        self.bump_gen();
1048    }
1049
1050    /// Build and open a picker over `source`.
1051    fn open_picker(&mut self, source: escriba_madoguchi::PickerSource) {
1052        use escriba_ui::picker::{Choice, Picker, PickerItem, Source};
1053        let (src, items) = match source {
1054            escriba_madoguchi::PickerSource::Buffers => (
1055                Source::Buffers,
1056                self.buffers
1057                    .ids()
1058                    .into_iter()
1059                    .filter_map(|id| {
1060                        let b = self.buffers.get(id)?;
1061                        let label = b.path.as_ref().map_or_else(
1062                            || String::from("[scratch]"),
1063                            |p| p.to_string_lossy().into_owned(),
1064                        );
1065                        Some(PickerItem::new(Choice::Buffer(id), label))
1066                    })
1067                    .collect::<Vec<_>>(),
1068            ),
1069            escriba_madoguchi::PickerSource::Help => (
1070                Source::Help,
1071                self.keymap
1072                    .entries_sorted()
1073                    .into_iter()
1074                    .map(|(mode, key, b)| {
1075                        // "NORMAL  gd   goto definition" — searchable by key,
1076                        // by mode, or by what it does, because a reader
1077                        // arrives from any of the three.
1078                        let mut label = String::with_capacity(48);
1079                        label.push_str(mode.as_str());
1080                        label.push_str("  ");
1081                        // `{key:?}` because there is no shared key FORMATTER
1082                        // in the fleet — awase owns the chord vocabulary but
1083                        // escriba-keymap's `Key` has no Display. That gap
1084                        // belongs to the keymap consolidation, not here, and
1085                        // inventing a fourth spelling would make it worse.
1086                        label.push_str(&format!("{key:?}"));
1087                        label.push_str("  ");
1088                        label.push_str(&b.description);
1089                        // Accepting runs the binding's action if it names a
1090                        // command; a typed Action has no name to run, so it
1091                        // reports rather than pretending.
1092                        let choice = match &b.action {
1093                            escriba_core::Action::Command { name, .. } => {
1094                                Choice::Command(name.clone())
1095                            }
1096                            other => Choice::Command(format!("{other:?}")),
1097                        };
1098                        PickerItem::new(choice, label)
1099                    })
1100                    .collect::<Vec<_>>(),
1101            ),
1102            escriba_madoguchi::PickerSource::Files => {
1103                let (files, truncated) = Self::walk_project(Self::GREP_FILE_LIMIT);
1104                self.report_truncation(truncated);
1105                (
1106                    Source::Files,
1107                    files
1108                        .into_iter()
1109                        .map(|p| {
1110                            let label = p.to_string_lossy().into_owned();
1111                            PickerItem::new(Choice::OpenFile(p), label)
1112                        })
1113                        .collect::<Vec<_>>(),
1114                )
1115            }
1116            escriba_madoguchi::PickerSource::Project => {
1117                // A project root is a directory carrying a marker. Derived
1118                // from the SAME walk rather than a second traversal — the
1119                // markers are files, so the walker already visited them.
1120                const MARKERS: &[&str] = &[
1121                    "Cargo.toml",
1122                    "flake.nix",
1123                    "package.json",
1124                    "go.mod",
1125                    "pyproject.toml",
1126                ];
1127                let (files, truncated) = Self::walk_project(Self::GREP_FILE_LIMIT);
1128                self.report_truncation(truncated);
1129                let mut roots: Vec<std::path::PathBuf> = files
1130                    .into_iter()
1131                    .filter(|p| {
1132                        p.file_name()
1133                            .is_some_and(|n| MARKERS.contains(&n.to_string_lossy().as_ref()))
1134                    })
1135                    .filter_map(|p| p.parent().map(std::path::Path::to_path_buf))
1136                    .collect();
1137                roots.sort();
1138                roots.dedup();
1139                (
1140                    Source::Project,
1141                    roots
1142                        .into_iter()
1143                        .map(|p| {
1144                            let label = p.to_string_lossy().into_owned();
1145                            PickerItem::new(Choice::OpenFile(p), label)
1146                        })
1147                        .collect::<Vec<_>>(),
1148                )
1149            }
1150            escriba_madoguchi::PickerSource::Commands => (
1151                Source::Commands,
1152                self.commands
1153                    .names()
1154                    .into_iter()
1155                    .map(|n| PickerItem::new(Choice::Command(n.to_string()), n.to_string()))
1156                    .collect::<Vec<_>>(),
1157            ),
1158        };
1159        if items.is_empty() {
1160            self.messages.push("nothing to pick from".to_string());
1161            return;
1162        }
1163        self.picker = Some(Picker::open(src, items));
1164        self.bump_gen();
1165    }
1166
1167    fn consume_splash_key(&mut self, key: &Key) -> SplashKey {
1168        let Some(splash) = self.splash.as_ref() else {
1169            return SplashKey::NotShowing;
1170        };
1171        let chosen = match key {
1172            Key::Char(c) => splash.entry_for(*c).map(|e| e.action.clone()),
1173            _ => None,
1174        };
1175        self.dismiss_splash();
1176        chosen.map_or(SplashKey::Dismissed, SplashKey::Ran)
1177    }
1178
1179    /// The current refresh generation. A renderer caches its products against
1180    /// this; equality is the freshness test (an unchanged generation ⇒ the
1181    /// last frame is still valid, so skip the re-highlight + re-shape).
1182    #[must_use]
1183    pub fn edit_gen(&self) -> EditGen {
1184        self.edit_gen
1185    }
1186
1187    /// Advance the refresh generation (a mutation happened).
1188    fn bump_gen(&mut self) {
1189        self.edit_gen = self.edit_gen.next();
1190    }
1191
1192    /// The accumulated dirty region (read-only). See [`take_damage`](Self::take_damage).
1193    #[must_use]
1194    pub fn damage(&self) -> Damage {
1195        self.damage
1196    }
1197
1198    /// Drain the accumulated dirty region, resetting to [`Damage::None`]. The
1199    /// renderer calls this once per frame to learn what to repaint, then the
1200    /// accumulator restarts — so damage never double-counts across frames.
1201    pub fn take_damage(&mut self) -> Damage {
1202        std::mem::replace(&mut self.damage, Damage::None)
1203    }
1204
1205    /// The line count of the active buffer (0 if none) — used to compute the
1206    /// [`Damage`] scope of a mutation.
1207    fn active_line_count(&self) -> u32 {
1208        self.buffers
1209            .get(self.active)
1210            .map_or(0, escriba_buffer::Buffer::line_count)
1211    }
1212
1213    /// Register a lazy USER plugin: its escriba entry is deferred until
1214    /// one of its `triggers` fires. Bundled defaults do NOT go through
1215    /// here — they are applied eagerly at boot. Empty `triggers` means
1216    /// the plugin never lazily activates (the binary applies eager
1217    /// plugins directly).
1218    pub fn register_lazy_plugin(
1219        &mut self,
1220        name: impl Into<String>,
1221        triggers: Vec<LazyTrigger>,
1222        entry_src: impl Into<String>,
1223    ) {
1224        self.plugin_host.register(name, triggers, entry_src);
1225    }
1226
1227    /// Apply a plugin entry's escriba-lisp to live state — the same
1228    /// keymap / command / option apply paths a user rc uses. Options are
1229    /// applied before keybinds so a plugin that sets `mapleader` resolves
1230    /// `<leader>` correctly. Returns the count of commands + keybinds it
1231    /// registered (best-effort; a malformed entry is skipped, not fatal).
1232    fn apply_plugin_entry(&mut self, entry_src: &str) -> usize {
1233        let Ok(plan) = escriba_lisp::apply_source(entry_src) else {
1234            return 0;
1235        };
1236        let cmd = escriba_lisp::apply_plan_to_commands(&plan, &mut self.commands);
1237        escriba_lisp::apply_plan_to_options(&plan, &mut self.options);
1238        if let Some(value) = self.options.get("mapleader") {
1239            if let Some(key) = escriba_lisp::parse_leader_key(value) {
1240                self.keymap.set_leader(key);
1241            }
1242        }
1243        let km = escriba_lisp::apply_plan_to_keymap(&plan, &mut self.keymap);
1244        (cmd.registered + km.keybinds_applied) as usize
1245    }
1246
1247    /// Fire any lazy plugin gated on a `FileType` trigger for `filetype`.
1248    /// Returns the number of plugins activated. Call when a buffer of a
1249    /// known filetype is opened.
1250    pub fn activate_filetype_plugins(&mut self, filetype: &str) -> usize {
1251        let pending = self.plugin_host.pending_for_filetype(filetype);
1252        let n = pending.len();
1253        for src in pending {
1254            self.apply_plugin_entry(&src);
1255        }
1256        n
1257    }
1258
1259    /// Fire any lazy plugin gated on an `Event` trigger for `event`.
1260    /// Returns the number of plugins activated.
1261    pub fn activate_event_plugins(&mut self, event: &str) -> usize {
1262        let pending = self.plugin_host.pending_for_event(event);
1263        let n = pending.len();
1264        for src in pending {
1265            self.apply_plugin_entry(&src);
1266        }
1267        n
1268    }
1269
1270    /// Advance one frame's worth of state given a raw madori event.
1271    ///
1272    /// Key events pass through the [`KeyRepeatGate`] first (see
1273    /// [`Self::tick_at`]); everything else is handled directly.
1274    pub fn tick(&mut self, event: &AppEvent) {
1275        self.tick_at(event, Instant::now());
1276    }
1277
1278    /// [`Self::tick`] with an explicit timestamp for the key-repeat gate —
1279    /// lets tests drive the debounce window without depending on the
1280    /// wall clock.
1281    pub fn tick_at(&mut self, event: &AppEvent, now: Instant) {
1282        match translate_app_event(event) {
1283            InputOutcome::Key(k) => {
1284                if self.gate_key(&k, now) {
1285                    self.on_key(&k);
1286                }
1287            }
1288            InputOutcome::Resized { .. } => {
1289                // Damage only. Each face owns its own geometry: the GPU
1290                // backend derives the grid in `RenderCallback::resize`, and
1291                // the ratatui face reads its area every frame. This arm used
1292                // to write `Window.rect`, which nothing ever read — so the
1293                // resize path was already doing no real work, it just looked
1294                // like it was.
1295                self.damage = self.damage.join(Damage::Viewport);
1296                self.bump_gen();
1297            }
1298            InputOutcome::Quit => self.quit_requested = true,
1299            InputOutcome::Focus(_) | InputOutcome::None => {}
1300        }
1301    }
1302
1303    /// Decide whether `key` survives the key-repeat gate at time `now`.
1304    ///
1305    /// Returns `true` when the key should be processed, `false` when it is
1306    /// an OS key-repeat storm tick that should be dropped. Gating applies
1307    /// ONLY in the navigation modes (Normal / Visual / VisualLine) — those
1308    /// are where a held `j`/`l` floods the motion path and thrashes the
1309    /// viewport. Insert and Command modes pass every key through ungated,
1310    /// because there "hold a key to repeat the character" is the intended
1311    /// behavior, not a storm to suppress.
1312    fn gate_key(&mut self, key: &Key, now: Instant) -> bool {
1313        match self.modal.mode() {
1314            Mode::Normal | Mode::Visual | Mode::VisualLine => {
1315                // The gate exists for HELD keys that flood the motion path and
1316                // thrash the viewport (`j`, `l`). It is wrong for the discrete
1317                // jumps: two `n` presses 10 ms apart mean two matches, and
1318                // swallowing the second is indistinguishable from a dead key —
1319                // the exact symptom the gate was added to prevent elsewhere.
1320                if is_repeat_storm_candidate(key) {
1321                    return self.repeat_gate.try_pass_at(*key, now);
1322                }
1323                true
1324            }
1325            Mode::Insert | Mode::Command => true,
1326        }
1327    }
1328
1329    /// Dispatch a single key through the keymap + apply the resulting action.
1330    pub fn on_key(&mut self, key: &Key) {
1331        // An open picker owns EVERY key while it is up — before the splash,
1332        // before the sequence stepper, before the keymap.
1333        match self.consume_picker_key(key) {
1334            escriba_ui::picker::Consumed::NotShowing => {}
1335            escriba_ui::picker::Consumed::Held | escriba_ui::picker::Consumed::Dismissed => return,
1336            escriba_ui::picker::Consumed::Chose(c) => {
1337                self.honour_choice(c);
1338                return;
1339            }
1340        }
1341        // The start screen owns the first keypress and nothing after it.
1342        match self.consume_splash_key(key) {
1343            SplashKey::NotShowing | SplashKey::Dismissed => {}
1344            SplashKey::Ran(action) => {
1345                self.apply(&action);
1346                return;
1347            }
1348        }
1349        // Multi-key sequence resolution runs first: a key that begins or
1350        // continues a bound sequence (`<leader>ff`, `gg`) is held or
1351        // resolved here before the single-key path sees it.
1352        match self.step_sequence(key) {
1353            SeqStep::Pending => return,
1354            SeqStep::Resolved(action) => {
1355                let count = self.modal.pending_count().unwrap_or(1);
1356                self.modal.clear_count();
1357                for _ in 0..count {
1358                    self.apply(&action);
1359                    if self.quit_requested {
1360                        return;
1361                    }
1362                }
1363                return;
1364            }
1365            SeqStep::Passthrough => {}
1366        }
1367        let counted = self.keymap.dispatch(&self.modal, key);
1368        // Count prefixes accumulate into modal state.
1369        if matches!(counted.action, Action::Pending) {
1370            if let Key::Char(c) = key {
1371                if c.is_ascii_digit() {
1372                    let d = u32::from(*c as u8 - b'0');
1373                    self.modal.append_count(d);
1374                }
1375            }
1376            return;
1377        }
1378        // The count flows through the operator-pending FSM (apply_counted), which
1379        // owns repetition: a bare motion runs count× , an operator captures its
1380        // count, and an operated motion multiplies the two. No naive outer loop.
1381        self.apply_counted(&counted.action, counted.count);
1382        // After applying, reset pending count.
1383        self.modal.clear_count();
1384    }
1385
1386    /// Advance the multi-key pending-stroke state machine for `key`.
1387    ///
1388    /// Sequences only apply in normal / visual modes — insert and
1389    /// command modes treat keys as literal text. Rules:
1390    /// - Mid-sequence: extend the pending prefix. Exact match →
1391    ///   [`SeqStep::Resolved`]; still a live prefix → [`SeqStep::Pending`];
1392    ///   otherwise abort the sequence and re-process this key fresh.
1393    /// - Not mid-sequence: if `key` begins a bound sequence AND is not
1394    ///   itself a complete single binding (single bindings win, so no
1395    ///   chord timeout is needed) → start pending. Otherwise
1396    ///   [`SeqStep::Passthrough`] to the single-key dispatcher.
1397    fn step_sequence(&mut self, key: &Key) -> SeqStep {
1398        let mode = self.modal.mode();
1399        if !matches!(mode, Mode::Normal | Mode::Visual | Mode::VisualLine) {
1400            return SeqStep::Passthrough;
1401        }
1402        if !self.pending_keys.is_empty() {
1403            let mut seq = self.pending_keys.clone();
1404            seq.push(key.clone());
1405            if let Some(b) = self.keymap.lookup_sequence(mode, &seq) {
1406                let action = b.action.clone();
1407                self.pending_keys.clear();
1408                return SeqStep::Resolved(action);
1409            }
1410            if self.keymap.is_sequence_prefix(mode, &seq) {
1411                self.pending_keys = seq;
1412                return SeqStep::Pending;
1413            }
1414            // The key broke the in-progress sequence — abort it and let
1415            // the key be re-processed as a fresh stroke below.
1416            self.pending_keys.clear();
1417        }
1418        let start = [key.clone()];
1419        if self.keymap.is_sequence_prefix(mode, &start) && self.keymap.lookup(mode, key).is_none() {
1420            self.pending_keys = start.to_vec();
1421            return SeqStep::Pending;
1422        }
1423        SeqStep::Passthrough
1424    }
1425
1426    /// The primary cursor position. The single read accessor — every
1427    /// renderer + motion path goes through it, so the underlying
1428    /// representation (today a single-cursor [`Cursors`]) can grow to
1429    /// multi-caret without changing read sites.
1430    #[must_use]
1431    pub fn cursor(&self) -> Position {
1432        self.cursors.primary()
1433    }
1434
1435    /// The **single** cursor-mutation path. Clamp the requested position to
1436    /// the active buffer's bounds, then scroll the active window's viewport
1437    /// to contain it on BOTH axes. Routing every cursor change through this
1438    /// (and through [`Cursors::set_primary`]) makes "cursor outside its
1439    /// viewport" an unrepresentable state, AND keeps cursor state in ONE
1440    /// typed home — there is no code path that advances the cursor without
1441    /// re-deriving the viewport from it, and no second `Position` field to
1442    /// fall out of sync.
1443    /// Re-assert the cursor-visibility invariant against the CURRENT
1444    /// viewport.
1445    ///
1446    /// A resize changes how much a face can show without moving the cursor,
1447    /// so nothing would otherwise re-run `scroll_to_contain` — the cursor
1448    /// would sit off-screen until the operator happened to move it. Every
1449    /// face calls this after telling the runtime its new size.
1450    pub fn refollow_cursor(&mut self) {
1451        self.set_cursor(self.cursors.primary());
1452    }
1453
1454    fn set_cursor(&mut self, pos: Position) {
1455        let clamped = if let Some(buf) = self.buffers.get(self.active) {
1456            buf.clamp(pos)
1457        } else {
1458            pos
1459        };
1460        self.cursors.set_primary(clamped);
1461        if let Some(w) = self.layout.active_window_mut() {
1462            w.viewport = w.viewport.scroll_to_contain(self.cursors.primary(), 2);
1463        }
1464    }
1465
1466    /// Dispatch one resolved action at count 1. See [`apply_counted`](Self::apply_counted).
1467    fn apply(&mut self, action: &Action) {
1468        self.apply_counted(action, 1);
1469    }
1470
1471    /// Dispatch one resolved action with its count. Routes `(action, count)`
1472    /// through the operator-pending FSM ([`OperatorPending`], on `zenmai`): most
1473    /// actions pass straight to [`apply_resolved`](Self::apply_resolved) carrying
1474    /// their count (so `5j` runs the motion 5×), an operator key is held, and an
1475    /// operator-then-motion pair is rewritten into a counted
1476    /// [`Action::ApplyOperator`] (so `3dw` deletes 3 words). The FSM owns count
1477    /// composition — there is no naive outer repeat loop.
1478    fn apply_counted(&mut self, action: &Action, count: u32) {
1479        // An uncompilable pattern must not reach the operator machine.
1480        //
1481        // `SearchState::accept` puts the prompt BACK on a compile error so the
1482        // typed text is not lost — but the FSM had already transitioned out of
1483        // `AwaitingSearch` on the way in, so the prompt survived and the
1484        // OPERATOR did not, with nothing said about it. The `d` was simply
1485        // gone, and the corrected pattern then ran as a bare search.
1486        //
1487        // The machine is a pure `(State, Event) -> (State, effects)` and
1488        // cannot observe the result of an effect, so it cannot decide this
1489        // itself. The fix is to stop handing it an event it has no business
1490        // deciding: the runtime classifies the submit first, from state it
1491        // already holds. `prompt_error` returns `None` for an EMPTY prompt, so
1492        // the bare-`/<CR>` reuse path is untouched.
1493        //
1494        // Tier-honest: parse-rejected at the boundary, not
1495        // truly-unrepresentable.
1496        if matches!(action, Action::SubmitCommand) {
1497            if let Some(e) = self.search.prompt_error() {
1498                let mut m = String::from("E383: Invalid search string: ");
1499                m.push_str(&e.to_string());
1500                self.messages.push(m);
1501                return;
1502            }
1503        }
1504
1505        for (resolved, times) in self.op_pending.dispatch((action.clone(), count)) {
1506            for _ in 0..times {
1507                self.apply_resolved(&resolved);
1508                if self.quit_requested {
1509                    return;
1510                }
1511            }
1512        }
1513    }
1514
1515    /// The active buffer's text. Search is a pure function of it.
1516    /// The active buffer's text revision — the token an offset measured
1517    /// against it should carry.
1518    #[must_use]
1519    fn text_rev(&self) -> TextRev {
1520        self.buffers
1521            .get(self.active)
1522            .map_or_else(TextRev::default, escriba_buffer::Buffer::text_rev)
1523    }
1524
1525    fn active_text(&self) -> String {
1526        self.buffers
1527            .get(self.active)
1528            .map(escriba_buffer::Buffer::to_string)
1529            .unwrap_or_default()
1530    }
1531
1532    /// The cursor as a char offset — the coordinate search speaks.
1533    fn cursor_char(&self) -> usize {
1534        self.buffers
1535            .get(self.active)
1536            .and_then(|b| b.position_to_char(self.cursor()).ok())
1537            .unwrap_or(0)
1538    }
1539
1540    /// Move the cursor onto a match and report a wrap the way vim does.
1541    /// The status line as data — what every face draws.
1542    ///
1543    /// One model, so the two faces can only disagree about styling. Before
1544    /// this existed the GPU face built its own line from a fixed `format!()`
1545    /// and drew neither the prompt nor any message, which made a fully
1546    /// working `/` look like a dead key on escriba's default renderer.
1547    #[must_use]
1548    pub fn status_model(&self) -> StatusModel<'_> {
1549        let cursor = self.cursor();
1550        let prompt = self.search.prompt();
1551
1552        let kind = match prompt.map(|p| p.direction) {
1553            Some(escriba_search::Direction::Forward) => PromptKind::SearchForward,
1554            Some(escriba_search::Direction::Backward) => PromptKind::SearchBackward,
1555            // Command mode with no search prompt open is an ex-command; the
1556            // typed `Option<Prompt>` is the discriminator, never a mode flag.
1557            None if self.modal.mode() == Mode::Command => PromptKind::Ex,
1558            None => PromptKind::None,
1559        };
1560
1561        StatusModel {
1562            mode: self.modal.mode(),
1563            line: cursor.line.saturating_add(1) as usize,
1564            column: cursor.column.saturating_add(1) as usize,
1565            prompt: kind,
1566            prompt_text: prompt
1567                .map_or_else(|| self.modal.minibuffer(), escriba_search::Prompt::text),
1568            prompt_caret: prompt.map_or_else(
1569                || self.modal.minibuffer_caret(),
1570                escriba_search::Prompt::caret,
1571            ),
1572            count: self.match_count(),
1573            message: self.messages.last().map(String::as_str),
1574        }
1575    }
1576
1577    /// `[3/17]` for the current pattern.
1578    ///
1579    /// While a prompt is open the count describes the PREVIEW — the answer to
1580    /// "what would Enter do", which is the question being asked mid-typing.
1581    /// Once committed it describes where the cursor actually is.
1582    #[must_use]
1583    fn match_count(&self) -> MatchCount {
1584        if self.search.is_prompting() {
1585            let text = self.active_text();
1586            // ONE scan, four outcomes. `Incomplete` and `NoMatch` used to be
1587            // the same `None`, so a half-typed character class reported
1588            // `[0/0]` — telling the user their pattern matches nothing while
1589            // they are still writing it.
1590            return match self.search.preview(&text) {
1591                escriba_search::Preview::Landed { step, total } => {
1592                    MatchCount::new(step.index, total)
1593                }
1594                escriba_search::Preview::NoMatch => MatchCount::None,
1595                escriba_search::Preview::Incomplete | escriba_search::Preview::Idle => {
1596                    MatchCount::Idle
1597                }
1598            };
1599        }
1600        if self.search.pattern().is_none() {
1601            return MatchCount::Idle;
1602        }
1603        let total = self.search.matches().len();
1604        // Read THROUGH the anchor: an ordinal computed against text that has
1605        // since changed reads as absent, so a stale count cannot be displayed.
1606        let rev = self.text_rev();
1607        self.search_at.as_ref().and_then(|a| a.get(rev)).map_or(
1608            if total == 0 {
1609                MatchCount::None
1610            } else {
1611                MatchCount::Idle
1612            },
1613            |&i| MatchCount::new(i, total),
1614        )
1615    }
1616
1617    /// `.` — replay the last change at the cursor.
1618    ///
1619    /// Two steps, because a change can be two: run the action, then re-type
1620    /// whatever followed it. `cgn` + `.` is exactly this — change the next
1621    /// match, then repeat that whole gesture on the one after.
1622    fn repeat_last_change(&mut self) {
1623        let Some(change) = self.last_change.clone() else {
1624            self.messages
1625                .push("E32: No previous change to repeat".to_string());
1626            return;
1627        };
1628
1629        for _ in 0..change.count.max(1) {
1630            self.apply_resolved(&change.action);
1631        }
1632        for c in change.inserted.chars() {
1633            self.apply_resolved(&Action::InsertChar(c));
1634        }
1635        if self.modal.mode() == Mode::Insert {
1636            // A replayed change must not leave the editor in Insert — the
1637            // original ended with an Esc the recording deliberately does not
1638            // store, since it is punctuation rather than part of the change.
1639            self.apply_resolved(&Action::ChangeMode(Mode::Normal));
1640        }
1641        // The replay wrote through `apply_resolved`, which re-records
1642        // `last_change` from the inner action. Put the ORIGINAL back so a
1643        // second `.` repeats the same change rather than a fragment of it.
1644        self.last_change = Some(change);
1645        self.recording_insert = false;
1646    }
1647
1648    /// Resolve a text object to the range it names.
1649    ///
1650    /// `gn` uses the INCLUSIVE step, so a cursor already sitting inside a
1651    /// match operates on THAT match rather than skipping to the next — which
1652    /// is what makes `cgn` then `.` walk matches one at a time instead of
1653    /// every other one.
1654    fn resolve_object(&self, object: escriba_core::TextObject) -> Option<Range> {
1655        use escriba_core::TextObject as O;
1656        let at = self.cursor_char();
1657        let matches = self.search.matches();
1658
1659        // A match CONTAINING the cursor wins outright, whichever direction the
1660        // object names.
1661        //
1662        // Comparing only against `m.start` — which is what a `starts`-vector
1663        // plus `Bound::Inclusive` does — is right only when the cursor sits on
1664        // a match's FIRST character. One column further in, `start < at` and
1665        // the match is rejected, so `cgn` skipped the very instance the
1666        // operator was standing in and the rename silently missed it. vim
1667        // operates on the containing match from every interior column, and the
1668        // `starts`-only comparison cannot express "contains" because it never
1669        // looks at `m.end`.
1670        let idx = matches.iter().position(|m| m.contains(at)).or_else(|| {
1671            let starts: Vec<usize> = matches.iter().map(|m| m.start).collect();
1672            match object {
1673                O::NextMatch => Bound::Inclusive.first_matching(&starts, at, true),
1674                O::PrevMatch => Bound::Inclusive.first_matching(&starts, at, false),
1675            }
1676        })?;
1677
1678        let m = matches.get(idx)?;
1679        let buf = self.buffers.get(self.active)?;
1680        Some(Range {
1681            start: buf.char_to_position(m.start),
1682            end: buf.char_to_position(m.end),
1683        })
1684    }
1685
1686    fn land_on(&mut self, step: escriba_search::Step) {
1687        if let Some(buf) = self.buffers.get(self.active) {
1688            let pos = buf.char_to_position(step.target.start);
1689            self.set_cursor(pos);
1690        }
1691        // The `[3/17]` numerator. `Step` has carried this index since the
1692        // engine was written — `engine.rs` even names the counter as the
1693        // reason it exists — and every consumer discarded it until now.
1694        self.search_at = Some(Anchored::new(step.index, self.text_rev()));
1695    }
1696
1697    /// vim's "search hit BOTTOM, continuing at TOP".
1698    ///
1699    /// One reporter, called by the two places a search can wrap: the shared
1700    /// commit and `n`/`N`. `land_on` deliberately does NOT report, or the bare
1701    /// commit would say it twice.
1702    fn report_wrap(&mut self, step: &escriba_search::Step) {
1703        if let Some(msg) = escriba_search::wrap_message(step.wrapped) {
1704            self.messages.push(msg.to_string());
1705        }
1706    }
1707
1708    /// `n` / `N`. Reports vim's E486 when the pattern matches nothing, rather
1709    /// than failing silently — a search that appears to do nothing is
1710    /// indistinguishable from a dropped keystroke.
1711    fn jump_search(&mut self, reverse: bool) {
1712        // Using the matches re-lights them: `n` after an auto-clear shows you
1713        // what you are walking through.
1714        self.search.relight();
1715        // `n` is a far jump — record where we leave from so `<C-o>` works.
1716        self.jumps.push(self.spot());
1717        let at = self.cursor_char();
1718        match self.search.repeat(at, reverse) {
1719            Some(step) => {
1720                // `n` wrapping the file says so, same as a commit does.
1721                self.report_wrap(&step);
1722                self.land_on(step);
1723            }
1724            None => {
1725                let msg = self.search.pattern().map_or_else(
1726                    || "E35: No previous regular expression".to_string(),
1727                    |p| {
1728                        let mut m = String::from("E486: Pattern not found: ");
1729                        m.push_str(p.raw());
1730                        m
1731                    },
1732                );
1733                self.messages.push(msg);
1734            }
1735        }
1736    }
1737
1738    /// Move the cursor to where the in-progress pattern would land, without
1739    /// committing anything. vim's `incsearch`.
1740    ///
1741    /// A pattern that does not compile yet (`/a[`, mid-typing) previews
1742    /// nothing and reports nothing — an error toast on every keystroke of a
1743    /// character class would be unusable.
1744    fn preview_search(&mut self) {
1745        let text = self.active_text();
1746        let Some(origin) = self.search.prompt().map(|p| p.origin) else {
1747            return;
1748        };
1749        let target = match self.search.preview(&text) {
1750            escriba_search::Preview::Landed { step, .. } => step.target.start,
1751            // Nothing to show: back to where the search started. Covers a
1752            // half-typed pattern and a pattern that finds nothing alike —
1753            // both mean "there is no match to preview".
1754            escriba_search::Preview::Idle
1755            | escriba_search::Preview::Incomplete
1756            | escriba_search::Preview::NoMatch => origin,
1757        };
1758        // A pattern that STOPS matching returns the cursor to the origin.
1759        //
1760        // Preview used to only ever move forward, so typing `ch` (a match) and
1761        // then `chz` (none) left the cursor parked on the `ch` match — a
1762        // preview showing a position the pattern no longer justifies, while
1763        // the count beside it read `[0/0]`. Restoring is also what makes
1764        // Escape's promise legible: at every keystroke the cursor is either on
1765        // a real match or back where you started, never on a stale one.
1766        if let Some(buf) = self.buffers.get(self.active) {
1767            let pos = buf.char_to_position(target);
1768            self.set_cursor(pos);
1769        }
1770    }
1771
1772    /// `d/foo<CR>` — commit the prompt and operate from the prompt's origin to
1773    /// where the search lands, as ONE action.
1774    ///
1775    /// Split from [`Self::submit_search`] rather than sharing it because the
1776    /// two want opposite things from the commit: the bare `/` MOVES the cursor
1777    /// to the match, and an operated `/` must NOT — the cursor is the
1778    /// operator's start point, and moving it first would leave the operator
1779    /// with a zero-width range.
1780    /// Commit the open search prompt. The ONE copy of the sequence.
1781    ///
1782    /// Reports its own failures (E486 / E35) so neither caller has to carry a
1783    /// third copy of the message strings. `Accepted::Invalid` cannot reach
1784    /// here — `apply_counted` rejects an uncompilable pattern at the dispatch
1785    /// boundary before the FSM or this method ever sees the submit.
1786    fn commit_search_prompt(&mut self) -> CommitOutcome {
1787        let text = self.active_text();
1788        let Some((origin, skip)) = self.search.prompt().map(|p| (p.origin, p.preview_skip()))
1789        else {
1790            return CommitOutcome::NoPrompt;
1791        };
1792
1793        match self.search.accept(&text) {
1794            escriba_search::Accepted::Committed | escriba_search::Accepted::ReusedPrevious => {
1795                self.modal.clear_minibuffer();
1796                self.modal.enter(Mode::Normal);
1797                match self.search.commit_step_skipping(origin, skip) {
1798                    Some(step) => {
1799                        // The wrap notice belongs HERE, once, for both commit
1800                        // paths. Reporting it in each caller is what let the
1801                        // operated path lose it in the first place — and my
1802                        // first attempt at this refactor duplicated it again
1803                        // rather than moving it, which the red proof caught.
1804                        self.report_wrap(&step);
1805                        CommitOutcome::Landed { origin, step }
1806                    }
1807                    None => {
1808                        self.report_pattern_not_found();
1809                        CommitOutcome::NotFound
1810                    }
1811                }
1812            }
1813            escriba_search::Accepted::NothingToRepeat => {
1814                self.modal.clear_minibuffer();
1815                self.modal.enter(Mode::Normal);
1816                self.messages
1817                    .push("E35: No previous regular expression".to_string());
1818                CommitOutcome::NoPrevious
1819            }
1820            // Unreachable: the boundary guard in `apply_counted` returns early
1821            // on an uncompilable pattern, leaving the prompt open. Reported
1822            // rather than `unreachable!()` — a panic in the editor's commit
1823            // path is a worse failure than a duplicate message.
1824            escriba_search::Accepted::Invalid(e) => {
1825                let mut m = String::from("E383: Invalid search string: ");
1826                m.push_str(&e.to_string());
1827                self.messages.push(m);
1828                CommitOutcome::NoPrompt
1829            }
1830        }
1831    }
1832
1833    /// vim's E486, with the pattern named. One place, so every path that fails
1834    /// to find reports identically.
1835    fn report_pattern_not_found(&mut self) {
1836        let mut m = String::from("E486: Pattern not found");
1837        if let Some(p) = self.search.pattern() {
1838            m.push_str(": ");
1839            m.push_str(p.raw());
1840        }
1841        self.messages.push(m);
1842    }
1843
1844    /// Bare `/foo<CR>` — commit and MOVE the cursor to the match.
1845    ///
1846    /// The only difference from the operated path is that this one lands;
1847    /// everything else lives in `commit_search_prompt`.
1848    fn submit_search(&mut self) {
1849        match self.commit_search_prompt() {
1850            CommitOutcome::Landed { origin, step } => {
1851                if let Some(buf) = self.buffers.get(self.active) {
1852                    let from = buf.char_to_position(origin);
1853                    self.jumps.push(escriba_core::Spot::new(self.active, from));
1854                }
1855                self.land_on(step);
1856            }
1857            CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
1858        }
1859    }
1860
1861    /// `d/foo<CR>` — commit, then operate from the prompt's origin to where the
1862    /// search lands, as ONE action.
1863    ///
1864    /// The cursor must NOT move to the match first: it is the operator's start
1865    /// point. That is the whole reason this differs from the bare path, and
1866    /// now the only reason.
1867    fn submit_search_operated(&mut self, op: Operator) {
1868        match self.commit_search_prompt() {
1869            CommitOutcome::Landed { origin, step } => {
1870                if let Some(buf) = self.buffers.get(self.active) {
1871                    let from = buf.char_to_position(origin);
1872                    let target = buf.char_to_position(step.target.start);
1873                    // Operating over a search is itself a far jump.
1874                    self.jumps.push(escriba_core::Spot::new(self.active, from));
1875                    self.set_cursor(from);
1876                    self.apply_operator_to(op, target);
1877                }
1878            }
1879            CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
1880        }
1881    }
1882
1883    fn apply_resolved(&mut self, action: &Action) {
1884        // Snapshot the scope inputs before the mutation so the resulting
1885        // Damage covers the changed region (the S3 seal — conservative widen).
1886        let lines_before = self.active_line_count();
1887        // Snapshot for the dot register: the only reliable witness that this
1888        // action changed text is that the buffer's revision moved.
1889        let rev_before = self.text_rev();
1890        let cline_before = self.cursor().line;
1891        match action {
1892            // Every action with an exact slip equivalent goes through the
1893            // interpreter, so "undo" has ONE implementation rather than one
1894            // per entry point. These had already drifted: the executor
1895            // re-followed the viewport after undo and the M1 interpreter did
1896            // not, so `u` and `:undo` behaved differently within a milestone
1897            // of each other.
1898            // Listed EXPLICITLY rather than behind a `if lower(..).is_some()`
1899            // guard: a guard arm does not count toward exhaustiveness, so the
1900            // guarded form silently gave up the total match — the compiler
1901            // said so, and it was right. `lowering_and_dispatch_agree` pins
1902            // that this list and `lower` stay the same set.
1903            Action::Quit
1904            | Action::ClearSearchHighlight
1905            | Action::Save
1906            | Action::Undo
1907            | Action::Redo
1908            | Action::Edit(_) => {
1909                for slip in Self::lower(action, self.active).unwrap_or_default() {
1910                    self.honour_one(slip);
1911                }
1912            }
1913            Action::Move(m) => self.apply_motion(*m),
1914            Action::SearchOpen(dir) => {
1915                // vim's `/` is the command-line with a different prompt char,
1916                // so we reuse Command mode; `search.prompt` is what tells a
1917                // later <CR> this is a search and not an ex-command.
1918                let origin = self.cursor_char();
1919                self.search.open(*dir, origin);
1920                self.modal.enter(Mode::Command);
1921            }
1922            Action::SearchRepeat { reverse } => self.jump_search(*reverse),
1923            Action::SearchWord { reverse } => {
1924                let dir = if *reverse {
1925                    SearchDirection::Backward
1926                } else {
1927                    SearchDirection::Forward
1928                };
1929                let (text, at) = (self.active_text(), self.cursor_char());
1930                // `*` jumps, so it records too.
1931                self.jumps.push(self.spot());
1932                match self.search.search_word(&text, at, dir) {
1933                    Some(step) => self.land_on(step),
1934                    // vim beeps and stays put when there is no word under the
1935                    // cursor; a silent no-op would look like a broken key.
1936                    None => self
1937                        .messages
1938                        .push("E348: No string under cursor".to_string()),
1939                }
1940            }
1941            Action::SearchSubmitOperated { op } => self.submit_search_operated(*op),
1942            Action::TextObject(object) => {
1943                // Bare `gn` moves onto the match. vim additionally starts a
1944                // Visual selection of it; escriba's Visual plumbing does not
1945                // carry a selection an operator can consume yet, so this
1946                // stops at the jump rather than faking a selection that
1947                // nothing would honour.
1948                if let Some(range) = self.resolve_object(*object) {
1949                    self.jumps.push(self.spot());
1950                    self.set_cursor(range.start);
1951                } else {
1952                    self.report_pattern_not_found();
1953                }
1954            }
1955            Action::ApplyOperatorObject { op, object } => match self.resolve_object(*object) {
1956                Some(range) => self.apply_operator_over(*op, range),
1957                None => self.report_pattern_not_found(),
1958            },
1959            Action::RepeatLastChange => self.repeat_last_change(),
1960            Action::JumpBack => {
1961                let here = self.spot();
1962                if let Some(spot) = self.jumps.back(here) {
1963                    self.goto_spot(spot);
1964                } else {
1965                    self.messages
1966                        .push("E662: At start of changelist".to_string());
1967                }
1968            }
1969            Action::JumpForward => {
1970                if let Some(spot) = self.jumps.forward() {
1971                    self.goto_spot(spot);
1972                } else {
1973                    self.messages.push("E663: At end of changelist".to_string());
1974                }
1975            }
1976            Action::ChangeMode(m) => {
1977                // Leaving the cmdline abandons any open search prompt and
1978                // returns the cursor home. The COMMITTED pattern survives —
1979                // cancelling a new search must not erase the old highlights.
1980                if *m == Mode::Normal && self.search.is_prompting() {
1981                    if let Some(origin) = self.search.cancel() {
1982                        if let Some(buf) = self.buffers.get(self.active) {
1983                            let pos = buf.char_to_position(origin);
1984                            self.set_cursor(pos);
1985                        }
1986                    }
1987                }
1988                self.modal.enter(*m);
1989            }
1990            Action::InsertChar(c) => self.insert_char(*c),
1991
1992            Action::SubmitCommand => {
1993                if self.search.is_prompting() {
1994                    self.submit_search();
1995                } else {
1996                    self.submit_command();
1997                }
1998            }
1999            Action::Command { name, args } => self.run_command(name, args),
2000            Action::ApplyOperator { op, motion } => self.apply_operator(*op, *motion),
2001            // The operator-pending FSM consumes Operator keys (begins pending);
2002            // they never reach the executor. Defensive no-op for exhaustiveness.
2003            Action::Operator(_) => {}
2004            Action::PromptCaret { to } => {
2005                // Both prompts have a caret now, and the same keys move it.
2006                if self.search.is_prompting() {
2007                    self.search.move_caret(*to);
2008                } else {
2009                    self.modal.move_minibuffer_caret(*to);
2010                }
2011            }
2012            Action::SearchPreviewStep { forward } => {
2013                if self.search.is_prompting() {
2014                    self.search.preview_step(*forward);
2015                    self.preview_search();
2016                }
2017            }
2018            Action::PromptDelete => {
2019                if self.search.is_prompting() {
2020                    self.search.delete_at_caret();
2021                    self.preview_search();
2022                } else {
2023                    self.modal.delete_minibuffer_at_caret();
2024                }
2025            }
2026            Action::PromptDeleteWord => {
2027                if self.search.is_prompting() {
2028                    self.search.delete_word_before_caret();
2029                    self.preview_search();
2030                }
2031            }
2032            Action::PromptClearToStart => {
2033                if self.search.is_prompting() {
2034                    self.search.clear_before_caret();
2035                    self.preview_search();
2036                }
2037            }
2038            Action::PromptBackspace => {
2039                self.prompt_backspace();
2040                // Shortening the pattern changes which matches exist, so the
2041                // preview must re-run — otherwise the cursor sits on a match
2042                // of a pattern that is no longer typed.
2043                if self.search.is_prompting() {
2044                    self.preview_search();
2045                }
2046            }
2047            Action::PromptHistory { back } => {
2048                if self.search.is_prompting() {
2049                    self.search.history_step(*back);
2050                    // No minibuffer resync: the shadow is the ex-line's store
2051                    // and nothing reads it while a search prompt is open, so
2052                    // rewriting it here was maintaining a copy for no reader.
2053                    self.preview_search();
2054                }
2055            }
2056            Action::Pending => {}
2057        }
2058        // Widen the dirty region by what this action touched (M1). Content
2059        // mutations that changed the line count run to end-of-document (every
2060        // line below shifted); an in-place edit or a cursor move is local;
2061        // arbitrary commands are conservatively Full. Never narrows.
2062        let lines_after = self.active_line_count();
2063        let cline_after = self.cursor().line;
2064        let d = match action {
2065            // A search repaints every highlight in the viewport, not just the
2066            // line the cursor left — so it must widen to Full. Treating it as a
2067            // cursor move would leave stale highlights on untouched lines.
2068            Action::SearchOpen(_)
2069            | Action::PromptHistory { .. }
2070            | Action::PromptBackspace
2071            | Action::PromptCaret { .. }
2072            | Action::SearchPreviewStep { .. }
2073            | Action::PromptDelete
2074            | Action::PromptDeleteWord
2075            | Action::PromptClearToStart
2076            | Action::SearchRepeat { .. }
2077            | Action::SearchWord { .. }
2078            | Action::ClearSearchHighlight
2079            | Action::SearchSubmitOperated { .. }
2080            // A replayed change can edit anywhere the original could, and a
2081            // match object can be anywhere in the document.
2082            | Action::RepeatLastChange
2083            | Action::TextObject(_)
2084            | Action::ApplyOperatorObject { .. }
2085            // A jump can land anywhere, so the viewport may scroll wholesale.
2086            | Action::JumpBack
2087            | Action::JumpForward => Damage::Full,
2088            Action::InsertChar(_)
2089            | Action::Edit(_)
2090            | Action::Undo
2091            | Action::Redo
2092            | Action::ApplyOperator { .. } => {
2093                if lines_after == lines_before {
2094                    Damage::span(cline_before, cline_after)
2095                } else {
2096                    Damage::Lines {
2097                        from: cline_before.min(cline_after),
2098                        to: u32::MAX,
2099                    }
2100                }
2101            }
2102            Action::Move(_) | Action::ChangeMode(_) => Damage::span(cline_before, cline_after),
2103            Action::Save => Damage::Viewport,
2104            Action::Command { .. } | Action::SubmitCommand => Damage::Full,
2105            Action::Quit | Action::Operator(_) | Action::Pending => Damage::None,
2106        };
2107        self.damage = self.damage.join(d);
2108        // Remember this change for `.`.
2109        //
2110        // Recorded from an OBSERVED MUTATION, not from the action's variant.
2111        // `text_effect()` is the wrong predicate here even though it looks
2112        // like the right one: it exists to decide cache invalidation, where
2113        // OVER-reporting is the safe direction, and the dot register needs the
2114        // opposite bias. Leaning on it meant `last_change` was set by actions
2115        // that changed no text at all, with two measured consequences:
2116        //
2117        //   `iZ<Esc>` then `/a<CR>` then `.`  — did nothing; the register held
2118        //       `SubmitCommand`, whose replay reads an already-cleared
2119        //       minibuffer.
2120        //   `iZ<Esc>` then `/q<Esc>` then `.` — TYPED `q` INTO THE BUFFER. An
2121        //       abandoned prompt left the register holding `InsertChar('q')`,
2122        //       and `.` in Normal mode routes that to the text. A corrupting
2123        //       register, not merely a lost one.
2124        //
2125        // Comparing the buffer's `TextRev` across the action answers the only
2126        // question that matters — did this actually change the text — and gets
2127        // the failed-operator case (`dgn` with no pattern) right for free.
2128        if self.recording_insert {
2129            match action {
2130                Action::InsertChar(c) => {
2131                    if let Some(lc) = self.last_change.as_mut() {
2132                        lc.inserted.push(*c);
2133                    }
2134                }
2135                // Leaving Insert ends the session; the change is now whole.
2136                Action::ChangeMode(m) if *m != Mode::Insert => self.recording_insert = false,
2137                _ => {}
2138            }
2139        } else if self.text_rev() != rev_before
2140            && !matches!(
2141                action,
2142                Action::RepeatLastChange | Action::Undo | Action::Redo
2143            )
2144        {
2145            self.last_change = Some(LastChange {
2146                action: action.clone(),
2147                count: 1,
2148                inserted: String::new(),
2149            });
2150            self.recording_insert = self.modal.mode() == Mode::Insert;
2151        }
2152
2153        // The search is over the moment you move on or edit — clear the
2154        // highlight rather than leaving the buffer as confetti until an
2155        // explicit `:noh`, which is the remap nearly every vimrc carries.
2156        // Clearing suppresses without forgetting, so `n` still works.
2157        if action.highlight_effect() == HighlightEffect::Clear {
2158            self.search.clear_highlight();
2159        }
2160        // Text changed ⇒ every match offset cached against the old text is
2161        // wrong. `SearchState::refresh` existed for exactly this and had ZERO
2162        // callers, so inserting four characters left both renderers painting
2163        // the highlight four columns off.
2164        //
2165        // Gated on the typed classifier rather than on `bump_gen` (which fires
2166        // for pure cursor moves too): re-scanning the document on every `j`
2167        // would be a per-keystroke full pass for no reason.
2168        if action.text_effect() == TextEffect::Mutates && self.search.pattern().is_some() {
2169            let text = self.active_text();
2170            self.search.refresh(&text);
2171            // NO manual invalidation of `search_at` here, deliberately. It is
2172            // `Anchored` to the text revision, so an ordinal computed against
2173            // the old text now reads as `None` on its own. This is the line
2174            // that used to have to be remembered.
2175        }
2176        // An action reached the executor ⇒ visible state may have changed.
2177        // Advance the refresh generation so the renderer repaints (and
2178        // re-highlights) exactly once. A gated-out key never reaches here, so
2179        // a key-repeat storm does not spin the renderer.
2180        self.bump_gen();
2181    }
2182
2183    /// Resolve a [`Motion`] from `from` to its target [`Position`] against the
2184    /// active buffer — **pure**: no cursor mutation, no side effects. This is
2185    /// the single motion-resolution source of truth that both [`apply_motion`]
2186    /// (move the cursor *to* the target) and [`apply_operator`] (use the target
2187    /// as the *other end* of an operated range) stand on. `None` only if there
2188    /// is no active buffer.
2189    ///
2190    /// [`apply_motion`]: Self::apply_motion
2191    /// [`apply_operator`]: Self::apply_operator
2192    fn resolve_motion(&self, from: Position, motion: Motion) -> Option<Position> {
2193        let buf = self.buffers.get(self.active)?;
2194        let pos = from;
2195        Some(match motion {
2196            // Search-as-motion: what makes `dn` / `d/foo<CR>` work. Resolved
2197            // against the committed match list, so it is `None` (motion fails,
2198            // operator aborts, buffer untouched) when nothing is committed —
2199            // never a silent move to 0, which would delete to the file start.
2200            Motion::SearchNext | Motion::SearchPrev => {
2201                let at = buf.position_to_char(pos).ok()?;
2202                let step = self
2203                    .search
2204                    .repeat(at, matches!(motion, Motion::SearchPrev))?;
2205                buf.char_to_position(step.target.start)
2206            }
2207            Motion::Left => Position::new(pos.line, pos.column.saturating_sub(1)),
2208            Motion::Right => Position::new(pos.line, pos.column.saturating_add(1)),
2209            Motion::Up => Position::new(pos.line.saturating_sub(1), pos.column),
2210            Motion::Down => Position::new(pos.line.saturating_add(1), pos.column),
2211            Motion::LineStart => Position::new(pos.line, 0),
2212            Motion::LineEnd => Position::new(pos.line, buf.line_len_chars(pos.line)),
2213            Motion::LineFirstNonBlank => first_non_blank(buf, pos.line),
2214            Motion::DocStart => Position::ZERO,
2215            Motion::DocEnd => Position::new(
2216                buf.line_count().saturating_sub(1),
2217                buf.line_len_chars(buf.line_count().saturating_sub(1)),
2218            ),
2219            Motion::WordStartNext | Motion::WordEndNext => word_next(buf, pos),
2220            Motion::WordStartPrev => word_prev(buf, pos),
2221            Motion::PageDown | Motion::HalfPageDown => {
2222                Position::new(pos.line.saturating_add(10), pos.column)
2223            }
2224            Motion::PageUp | Motion::HalfPageUp => {
2225                Position::new(pos.line.saturating_sub(10), pos.column)
2226            }
2227            Motion::GotoLine(n) => Position::new(n.saturating_sub(1), 0),
2228            // Structural Lisp motions — stubs for phase 1.B; full paredit
2229            // semantics land when caixa-ast is wired to the active buffer.
2230            Motion::ForwardSexp
2231            | Motion::BackwardSexp
2232            | Motion::UpList
2233            | Motion::DownList
2234            | Motion::BeginningOfDefun
2235            | Motion::EndOfDefun
2236            | Motion::BeginningOfSexp
2237            | Motion::EndOfSexp => pos,
2238        })
2239    }
2240
2241    fn apply_motion(&mut self, motion: Motion) {
2242        // A bare search motion is a FAR JUMP and it REPORTS — it records into
2243        // the jumplist, prints vim's "hit BOTTOM" on a wrap, and says E486
2244        // when nothing matches. `resolve_motion` can do none of that: it is
2245        // deliberately pure because the OPERATOR path calls it to find a range
2246        // without moving the cursor. So `n` routes to the one executor that
2247        // owns those side effects, and `Action::SearchRepeat` routes to the
2248        // same place — one code path, two spellings.
2249        if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
2250            self.jump_search(matches!(motion, Motion::SearchPrev));
2251            return;
2252        }
2253        let Some(pos) = self.resolve_motion(self.cursor(), motion) else {
2254            return;
2255        };
2256        // The single cursor-mutation path clamps to the buffer and scrolls
2257        // the viewport to contain the cursor on both axes.
2258        self.set_cursor(pos);
2259    }
2260
2261    /// Apply an operator over a motion — the vim `{operator}{motion}` verbs
2262    /// (`dw` delete-word, `c$` change-to-line-end, `y0` yank-to-line-start).
2263    /// Composition is explicit: the motion resolves a target via
2264    /// [`resolve_motion`](Self::resolve_motion); the operator acts over the
2265    /// `[cursor, target)` range. Register-leaving operators
2266    /// ([`Operator::leaves_register`]) capture the text first.
2267    fn apply_operator(&mut self, op: Operator, motion: Motion) {
2268        let from = self.cursor();
2269        let Some(to) = self.resolve_motion(from, motion) else {
2270            // A motion that cannot resolve aborts the operator with the buffer
2271            // untouched. A search motion says WHY — `dn` with no pattern armed
2272            // is otherwise indistinguishable from a dropped keystroke, which
2273            // is the same complaint that motivated E486 on the bare path.
2274            if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
2275                if self.search.pattern().is_none() {
2276                    self.messages
2277                        .push("E35: No previous regular expression".to_string());
2278                } else {
2279                    self.report_pattern_not_found();
2280                }
2281            }
2282            return;
2283        };
2284        self.apply_operator_to(op, to);
2285    }
2286
2287    /// Apply `op` over `[cursor, to)`.
2288    ///
2289    /// Split out of [`Self::apply_operator`] so the operated-search path can
2290    /// reach the same range machinery with a target it resolved itself — the
2291    /// alternative was a second copy of the delete/yank/register logic, which
2292    /// is how the two would drift.
2293    fn apply_operator_to(&mut self, op: Operator, to: Position) {
2294        let from = self.cursor();
2295        self.apply_operator_over(
2296            op,
2297            Range {
2298                start: from,
2299                end: to,
2300            },
2301        );
2302    }
2303
2304    /// Apply `op` over an explicit range.
2305    ///
2306    /// The object path needs this: `gn`'s extent need not begin at the cursor,
2307    /// so it cannot go through the `[cursor, target)` shape the motion path
2308    /// uses. One implementation of the delete/yank/register logic, reached two
2309    /// ways.
2310    fn apply_operator_over(&mut self, op: Operator, range: Range) {
2311        let range = range.normalized();
2312        if range.is_empty() {
2313            return;
2314        }
2315        // Capture the operated text (for the register) before mutating.
2316        let text = self
2317            .buffers
2318            .get(self.active)
2319            .and_then(|buf| buf.slice(range).ok());
2320        if op.leaves_register() {
2321            if let Some(t) = &text {
2322                self.register = Some(t.clone());
2323            }
2324        }
2325        match op {
2326            // Delete + Change remove the range; Change then enters Insert so
2327            // the operator pairs with immediate typing (`ciw`, `c$`).
2328            Operator::Delete | Operator::Change => {
2329                if let Some(buf) = self.buffers.get_mut(self.active) {
2330                    let _ = buf.apply(&Edit::delete(range));
2331                }
2332                self.set_cursor(range.start);
2333                if op == Operator::Change {
2334                    self.modal.enter(Mode::Insert);
2335                }
2336            }
2337            // Yank copies to the register without mutating the buffer; vim
2338            // leaves the cursor at the range start.
2339            Operator::Yank => {
2340                self.set_cursor(range.start);
2341            }
2342            // Indent/Format/structural operators are not yet wired — named,
2343            // not faked (no buffer mutation, register already captured for the
2344            // register-leaving ones above).
2345            _ => {
2346                self.messages
2347                    .push("operator not yet implemented".to_owned());
2348            }
2349        }
2350    }
2351
2352    /// The text last yanked or deleted into the unnamed register, if any.
2353    /// The future `p`/`P` paste reads this.
2354    #[must_use]
2355    pub fn register(&self) -> Option<&str> {
2356        self.register.as_deref()
2357    }
2358
2359    fn insert_char(&mut self, c: char) {
2360        if self.modal.mode() == Mode::Command {
2361            // A search prompt and an ex-command share Command mode (vim's
2362            // cmdline). `search.is_prompting()` is the typed discriminator —
2363            // it can only be true when `/` or `?` actually opened a prompt.
2364            if self.search.is_prompting() {
2365                // The search prompt is the SOLE store while it is open.
2366                //
2367                // This used to also `push_minibuffer(c)`, and the two stores
2368                // insert differently — `search.push` at the caret, the
2369                // minibuffer always at the end — so `/fo<Left>X` left them
2370                // reading `fXo` and `foX`. That was one of FIVE desync paths;
2371                // the caret moves, forward-delete, delete-word and
2372                // clear-to-start never touched the shadow at all.
2373                //
2374                // Deleting the write costs nothing because `status_model`
2375                // already selects the minibuffer only on the `prompt == None`
2376                // branch — the shadow is the EX-LINE's store, and while a
2377                // search prompt is open nothing reads it.
2378                self.search.push(c);
2379                self.preview_search();
2380            } else {
2381                self.modal.push_minibuffer(c);
2382            }
2383            return;
2384        }
2385        let cursor = self.cursor();
2386        let Some(buf) = self.buffers.get_mut(self.active) else {
2387            return;
2388        };
2389        let edit = Edit::insert(cursor, c.to_string());
2390        if buf.apply(&edit).is_ok() {
2391            let next = if c == '\n' {
2392                Position::new(cursor.line.saturating_add(1), 0)
2393            } else {
2394                cursor.shift_right(1)
2395            };
2396            // Route through the single cursor-mutation path so the viewport
2397            // follows the cursor (both axes) and the cursor stays clamped.
2398            self.set_cursor(next);
2399        }
2400    }
2401
2402    /// Backspace inside a prompt. Keeps the search buffer and the displayed
2403    /// minibuffer in lockstep — if only one shrank, the pattern submitted
2404    /// would differ from the text on screen.
2405    fn prompt_backspace(&mut self) -> bool {
2406        if self.modal.mode() != Mode::Command {
2407            return false;
2408        }
2409        if self.search.is_prompting() {
2410            // Backspacing past the `/` closes the prompt, as vim does. No
2411            // `pop_minibuffer` here for the same reason as `insert_char`: the
2412            // shadow is the ex-line's, and popping its TAIL when the caret is
2413            // mid-pattern was another desync path.
2414            if self.search.backspace() {
2415                self.modal.clear_minibuffer();
2416                self.modal.enter(Mode::Normal);
2417            }
2418            // Never `pop_minibuffer` on the search path: it pops the TAIL,
2419            // while `search.backspace()` removes the char before the CARET.
2420            return true;
2421        }
2422        self.modal.pop_minibuffer();
2423        true
2424    }
2425
2426    fn submit_command(&mut self) {
2427        // Read the command line BEFORE leaving Command mode — the minibuffer
2428        // exists only in the `Command` variant, so the escape must come
2429        // after the capture.
2430        let line = self.modal.minibuffer().to_string();
2431        self.modal.escape();
2432        let (name, args) = parse_command_line(&line);
2433        if name.is_empty() {
2434            return;
2435        }
2436        self.run_command(&name, &args);
2437    }
2438
2439    fn run_command(&mut self, name: &str, args: &[String]) {
2440        // Bound the command -> RunCommand slip -> command cycle. Refused and
2441        // reported, never a stack overflow: an editor that dies under the
2442        // operator loses their buffer, and a script that loops is a mistake
2443        // they should be told about, not punished for.
2444        if self.dispatch_depth >= Self::MAX_DISPATCH_DEPTH {
2445            let mut m = String::from("command recursion too deep at `");
2446            m.push_str(name);
2447            m.push_str("` — refusing");
2448            self.messages.push(m);
2449            self.damage = self.damage.join(Damage::Viewport);
2450            self.bump_gen();
2451            return;
2452        }
2453        self.dispatch_depth += 1;
2454        self.run_command_inner(name, args);
2455        self.dispatch_depth -= 1;
2456    }
2457
2458    /// How many nested command dispatches are allowed. Deep enough that no
2459    /// legitimate script notices, shallow enough to fail fast.
2460    const MAX_DISPATCH_DEPTH: u8 = 8;
2461
2462    fn run_command_inner(&mut self, name: &str, args: &[String]) {
2463        // Lazy-activation seam (lazy.nvim `cmd =` model): a user plugin
2464        // gated on `Command: <name>` has its entry applied the first time
2465        // that command runs, BEFORE dispatch — so the activated plugin
2466        // can register the very command being invoked and it resolves on
2467        // this same call.
2468        if self.plugin_host.pending() > 0 {
2469            let pending = self.plugin_host.pending_for_command(name);
2470            for src in pending {
2471                self.apply_plugin_entry(&src);
2472            }
2473        }
2474        // Read through the counter, then interpret. Two immutable borrows of
2475        // `self` (the window and the registry) coexist; the `&mut` comes
2476        // afterwards, once the outcome is owned. That sequencing IS the
2477        // seam: there is no moment where a command body and `&mut self` are
2478        // live at the same time.
2479        let outcome = {
2480            let window = self.window();
2481            self.commands.run(name, &window, args)
2482        };
2483        match outcome {
2484            Ok(o) => self.interpret(o),
2485            // Reported, never fatal (Phase 0). A failed command must not
2486            // take the editor down, but it must not be invisible either.
2487            Err(e) => {
2488                self.messages.push(describe_command_failure(name, &e));
2489                self.damage = self.damage.join(Damage::Viewport);
2490                self.bump_gen();
2491            }
2492        }
2493    }
2494
2495    // ── tatara-lisp runtime bridge (imperative programmability tier) ──
2496
2497    /// Capture a read snapshot of the editor for the tatara-lisp host.
2498    /// Lisp reads (`cursor-line`, `current-line`, …) answer from this.
2499    #[must_use]
2500    pub fn snapshot(&self) -> EditorSnapshot {
2501        let current_line = self
2502            .buffers
2503            .get(self.active)
2504            .and_then(|b| b.line(self.cursor().line))
2505            .map(|s| s.trim_end_matches('\n').to_string())
2506            .unwrap_or_default();
2507        let buffer_name = self
2508            .buffers
2509            .get(self.active)
2510            .and_then(|b| b.path.as_ref())
2511            .map(|p| p.display().to_string())
2512            .unwrap_or_else(|| "[scratch]".to_string());
2513        EditorSnapshot {
2514            cursor_line: i64::from(self.cursor().line),
2515            cursor_column: i64::from(self.cursor().column),
2516            current_line,
2517            mode: self.modal.mode().as_str().to_string(),
2518            buffer_name,
2519        }
2520    }
2521
2522    /// Evaluate tatara-lisp `src` against this editor: capture a
2523    /// snapshot, run it in the embedded VM, then apply the typed effects
2524    /// the program emitted. This is the imperative programmability tier
2525    /// — live Lisp that reads state and drives the editor through the
2526    /// sandboxed effect boundary.
2527    ///
2528    /// **Snapshot semantics:** the read snapshot is captured ONCE before
2529    /// eval, and effects are applied AFTER the program returns. So within
2530    /// a single `run_lisp` call a program cannot observe its own writes —
2531    /// `(insert "x") (cursor-column)` reads the pre-insert column. This
2532    /// snapshot-isolation is deliberate (it's what makes the effect
2533    /// boundary a clean sandbox seam); a program that must read its own
2534    /// effects splits the work across calls. The VM is cached
2535    /// ([`Self::lisp_vm`]) so the stdlib is installed once and top-level
2536    /// `define`s persist across calls (REPL-like).
2537    pub fn run_lisp(&mut self, src: &str) -> Result<(), VmError> {
2538        let mut host = EscribaHost::with_snapshot(self.snapshot());
2539        let vm = self.lisp_vm.get_or_insert_with(EscribaVm::new);
2540        vm.eval(src, &mut host)?;
2541        let effects = host.take_effects();
2542        self.apply_host_effects(effects);
2543        Ok(())
2544    }
2545
2546    /// Apply tatara-lisp effects to live editor state.
2547    ///
2548    /// A thin adapter now. It used to be `apply_host_effects`, a THIRD
2549    /// implementation of message-push / option-insert / insert-text beside
2550    /// the Action executor and the slip interpreter — the same duplication
2551    /// that let `u` and `:undo` drift apart in M3. The VM emits slips; this
2552    /// hands them to the one interpreter.
2553    pub fn apply_host_effects(&mut self, effects: Vec<Negai>) {
2554        self.interpret(Outcome::did(effects));
2555    }
2556
2557    /// Insert a (possibly multi-line) string at the cursor and advance
2558    /// the cursor past it. Used by the `(insert …)` effect.
2559    fn insert_text(&mut self, text: &str) {
2560        if text.is_empty() {
2561            return;
2562        }
2563        let cursor = self.cursor();
2564        let Some(buf) = self.buffers.get_mut(self.active) else {
2565            return;
2566        };
2567        let edit = Edit::insert(cursor, text.to_string());
2568        if buf.apply(&edit).is_ok() {
2569            let next = if let Some(nl) = text.rfind('\n') {
2570                let added_lines = u32::try_from(text.matches('\n').count()).unwrap_or(0);
2571                let last_line_len = u32::try_from(text[nl + 1..].chars().count()).unwrap_or(0);
2572                Position::new(cursor.line + added_lines, last_line_len)
2573            } else {
2574                let n = u32::try_from(text.chars().count()).unwrap_or(0);
2575                cursor.shift_right(n)
2576            };
2577            // Route through the single cursor-mutation path so the viewport
2578            // follows the cursor (both axes) and the cursor stays clamped.
2579            self.set_cursor(next);
2580        }
2581    }
2582}
2583
2584fn first_non_blank(buf: &escriba_buffer::Buffer, line: u32) -> Position {
2585    let Some(text) = buf.line(line) else {
2586        return Position::new(line, 0);
2587    };
2588    let col = text
2589        .chars()
2590        .take_while(|c| c.is_whitespace() && *c != '\n')
2591        .count();
2592    Position::new(line, u32::try_from(col).unwrap_or(0))
2593}
2594
2595fn word_next(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
2596    let Some(text) = buf.line(pos.line) else {
2597        return pos;
2598    };
2599    let chars: Vec<char> = text.chars().collect();
2600    let start = pos.column as usize;
2601    let mut i = start;
2602    while i < chars.len() && !chars[i].is_whitespace() {
2603        i += 1;
2604    }
2605    while i < chars.len() && chars[i].is_whitespace() {
2606        i += 1;
2607    }
2608    if i >= chars.len() {
2609        // No more words on this line — jump to next line.
2610        if pos.line + 1 < buf.line_count() {
2611            return Position::new(pos.line + 1, 0);
2612        }
2613    }
2614    Position::new(pos.line, u32::try_from(i).unwrap_or(pos.column))
2615}
2616
2617fn word_prev(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
2618    let Some(text) = buf.line(pos.line) else {
2619        return pos;
2620    };
2621    let chars: Vec<char> = text.chars().collect();
2622    let mut i = (pos.column as usize).min(chars.len());
2623    while i > 0 && chars[i - 1].is_whitespace() {
2624        i -= 1;
2625    }
2626    while i > 0 && !chars[i - 1].is_whitespace() {
2627        i -= 1;
2628    }
2629    Position::new(pos.line, u32::try_from(i).unwrap_or(0))
2630}
2631
2632fn parse_command_line(line: &str) -> (String, Vec<String>) {
2633    let mut parts = line.split_whitespace();
2634    let Some(first) = parts.next() else {
2635        return (String::new(), Vec::new());
2636    };
2637    let head = first.strip_prefix(':').unwrap_or(first);
2638    let name = match head {
2639        "w" => "save",
2640        "q" => "quit",
2641        "u" => "undo",
2642        other => other,
2643    };
2644    (name.to_string(), parts.map(str::to_string).collect())
2645}
2646
2647#[cfg(test)]
2648mod tests {
2649    use super::*;
2650    use madori::event::{KeyCode, KeyEvent, Modifiers};
2651
2652    // ── search wiring (escriba-search integration) ────────────────────
2653    //
2654    // The engine is proven in escriba-search's own 61 tests. These prove the
2655    // WIRING: that keys reach it, that the cursor lands where it says, and
2656    // that a search prompt and an ex-command can share Command mode without
2657    // being confused for one another.
2658
2659    fn type_search(st: &mut EditorState, dir: SearchDirection, pat: &str) {
2660        st.apply(&Action::SearchOpen(dir));
2661        for c in pat.chars() {
2662            st.apply(&Action::InsertChar(c));
2663        }
2664        st.apply(&Action::SubmitCommand);
2665    }
2666
2667    #[test]
2668    fn slash_search_moves_the_cursor_to_the_match() {
2669        let mut st = new_state_with("alpha\nbravo\ncharlie\n");
2670        type_search(&mut st, SearchDirection::Forward, "charlie");
2671        assert_eq!(st.cursor().line, 2, "cursor lands on the matching line");
2672        assert_eq!(st.modal.mode(), Mode::Normal, "prompt closes on submit");
2673        assert_eq!(st.search.matches().len(), 1);
2674    }
2675
2676    #[test]
2677    // `N` is a DIFFERENT vim key from `n` — see escriba-search.
2678    #[allow(non_snake_case)]
2679    fn n_and_N_walk_matches_in_both_directions() {
2680        let mut st = new_state_with("foo\nbar\nfoo\nbaz\nfoo\n");
2681        type_search(&mut st, SearchDirection::Forward, "foo");
2682        let first = st.cursor().line;
2683        st.apply(&Action::SearchRepeat { reverse: false });
2684        let second = st.cursor().line;
2685        assert!(second > first, "n advances ({first} -> {second})");
2686        st.apply(&Action::SearchRepeat { reverse: true });
2687        assert_eq!(st.cursor().line, first, "N comes back");
2688    }
2689
2690    #[test]
2691    fn star_searches_the_word_under_the_cursor() {
2692        let mut st = new_state_with("needle\nhaystack\nneedle\n");
2693        st.apply(&Action::SearchWord { reverse: false });
2694        assert_eq!(st.search.pattern().unwrap().raw(), r"\bneedle\b");
2695        assert_eq!(st.cursor().line, 2, "jumps to the other occurrence");
2696    }
2697
2698    #[test]
2699    fn escape_abandons_the_prompt_and_keeps_the_previous_search() {
2700        let mut st = new_state_with("foo\nbar\nfoo\n");
2701        type_search(&mut st, SearchDirection::Forward, "foo");
2702        let matches_before = st.search.matches().len();
2703
2704        st.apply(&Action::SearchOpen(SearchDirection::Forward));
2705        st.apply(&Action::InsertChar('z'));
2706        st.apply(&Action::ChangeMode(Mode::Normal));
2707
2708        assert!(!st.search.is_prompting(), "prompt gone");
2709        assert_eq!(
2710            st.search.pattern().unwrap().raw(),
2711            "foo",
2712            "old pattern survives"
2713        );
2714        assert_eq!(
2715            st.search.matches().len(),
2716            matches_before,
2717            "old highlights survive"
2718        );
2719    }
2720
2721    #[test]
2722    fn a_search_prompt_and_an_ex_command_are_not_confused() {
2723        let mut st = new_state_with("foo\n");
2724        // No `/` pressed: Command mode belongs to the ex-command line.
2725        st.apply(&Action::ChangeMode(Mode::Command));
2726        assert!(!st.search.is_prompting(), "`:` must not open a search");
2727        st.apply(&Action::InsertChar('w'));
2728        assert!(
2729            st.search.prompt().is_none(),
2730            "typed char went to the ex line"
2731        );
2732    }
2733
2734    #[test]
2735    fn a_missing_pattern_reports_instead_of_failing_silently() {
2736        let mut st = new_state_with("alpha\nbravo\n");
2737        type_search(&mut st, SearchDirection::Forward, "zzz");
2738        assert!(
2739            st.messages.iter().any(|m| m.contains("E486")),
2740            "must report not-found, got {:?}",
2741            st.messages
2742        );
2743    }
2744
2745    #[test]
2746    fn n_without_any_search_reports_rather_than_moving() {
2747        let mut st = new_state_with("alpha\nbravo\n");
2748        let before = st.cursor();
2749        st.apply(&Action::SearchRepeat { reverse: false });
2750        assert_eq!(st.cursor(), before, "cursor must not move");
2751        assert!(
2752            st.messages.iter().any(|m| m.contains("E35")),
2753            "got {:?}",
2754            st.messages
2755        );
2756    }
2757
2758    #[test]
2759    fn search_as_a_motion_composes_with_an_operator() {
2760        // The point of Motion::SearchNext: `d` + search deletes to the match.
2761        let mut st = new_state_with("alpha bravo charlie\n");
2762        type_search(&mut st, SearchDirection::Forward, "charlie");
2763        st.set_cursor(Position::new(0, 0));
2764        let target = st.resolve_motion(Position::new(0, 0), Motion::SearchNext);
2765        assert!(target.is_some(), "search must resolve as a motion");
2766        assert_eq!(target.unwrap().column, 12, "at `charlie`");
2767    }
2768
2769    #[test]
2770    fn search_motion_without_a_pattern_fails_the_motion_instead_of_moving_to_zero() {
2771        // A silent fallback to offset 0 would make `d` + search delete to the
2772        // start of the file — the worst possible failure for an operator.
2773        let st = new_state_with("alpha bravo\n");
2774        assert!(
2775            st.resolve_motion(Position::new(0, 5), Motion::SearchNext)
2776                .is_none()
2777        );
2778    }
2779
2780    #[test]
2781    fn clear_highlight_keeps_the_pattern_usable() {
2782        let mut st = new_state_with("foo\nbar\nfoo\n");
2783        type_search(&mut st, SearchDirection::Forward, "foo");
2784        st.apply(&Action::ClearSearchHighlight);
2785        assert!(st.search.highlights().is_empty(), "nothing lit");
2786        st.apply(&Action::SearchRepeat { reverse: false });
2787        assert!(st.search.pattern().is_some(), "but n still works");
2788    }
2789
2790    #[test]
2791    fn typing_previews_incrementally_before_commit() {
2792        let mut st = new_state_with("alpha\nbravo\ncharlie\n");
2793        st.apply(&Action::SearchOpen(SearchDirection::Forward));
2794        for c in "charlie".chars() {
2795            st.apply(&Action::InsertChar(c));
2796        }
2797        // incsearch: the cursor has already moved, with nothing committed.
2798        assert_eq!(st.cursor().line, 2, "preview moved the cursor");
2799        assert!(st.search.pattern().is_none(), "but nothing is committed");
2800    }
2801
2802    #[test]
2803    fn backspace_corrects_the_prompt_and_reruns_the_preview() {
2804        let mut st = new_state_with("alpha\nbravo\n");
2805        st.apply(&Action::SearchOpen(SearchDirection::Forward));
2806        for c in "bravox".chars() {
2807            st.apply(&Action::InsertChar(c));
2808        }
2809        assert_eq!(st.search.prompt().unwrap().text(), "bravox");
2810        st.apply(&Action::PromptBackspace);
2811        assert_eq!(
2812            st.search.prompt().unwrap().text(),
2813            "bravo",
2814            "typo corrected"
2815        );
2816        assert_eq!(
2817            st.status_model().prompt_text,
2818            "bravo",
2819            "the model reads the PROMPT — the minibuffer is the ex-line's store",
2820        );
2821        assert_eq!(st.cursor().line, 1, "preview re-ran and found it");
2822    }
2823
2824    #[test]
2825    fn backspacing_past_the_slash_closes_the_prompt() {
2826        let mut st = new_state_with("alpha\n");
2827        st.apply(&Action::SearchOpen(SearchDirection::Forward));
2828        st.apply(&Action::InsertChar('a'));
2829        st.apply(&Action::PromptBackspace);
2830        st.apply(&Action::PromptBackspace);
2831        assert!(!st.search.is_prompting(), "prompt closed");
2832        assert_eq!(st.modal.mode(), Mode::Normal);
2833    }
2834
2835    #[test]
2836    fn noh_clears_highlights_and_keeps_the_pattern() {
2837        let mut st = new_state_with("foo\nbar\nfoo\n");
2838        type_search(&mut st, SearchDirection::Forward, "foo");
2839        assert!(!st.search.highlights().is_empty());
2840        st.run_command("noh", &[]);
2841        assert!(st.search.highlights().is_empty(), ":noh turns them off");
2842        assert!(st.search.pattern().is_some(), "but n still works");
2843    }
2844
2845    #[test]
2846    fn noh_accepts_the_vim_aliases() {
2847        for name in ["noh", "nohl", "nohlsearch"] {
2848            let mut st = new_state_with("foo\nfoo\n");
2849            type_search(&mut st, SearchDirection::Forward, "foo");
2850            st.run_command(name, &[]);
2851            assert!(st.search.highlights().is_empty(), "{name} must clear");
2852        }
2853    }
2854
2855    #[test]
2856    fn backspace_on_the_ex_line_does_not_touch_search_state() {
2857        let mut st = new_state_with("foo\n");
2858        st.apply(&Action::ChangeMode(Mode::Command));
2859        st.apply(&Action::InsertChar('w'));
2860        st.apply(&Action::InsertChar('q'));
2861        st.apply(&Action::PromptBackspace);
2862        assert_eq!(st.status_model().prompt_text, "w");
2863        assert!(st.search.prompt().is_none(), "no search was involved");
2864    }
2865
2866    #[test]
2867    fn up_arrow_recalls_the_previous_search() {
2868        let mut st = new_state_with("alpha\nbravo\n");
2869        type_search(&mut st, SearchDirection::Forward, "bravo");
2870        st.apply(&Action::SearchOpen(SearchDirection::Forward));
2871        st.apply(&Action::PromptHistory { back: true });
2872        assert_eq!(st.search.prompt().unwrap().text(), "bravo");
2873        assert_eq!(
2874            st.status_model().prompt_text,
2875            "bravo",
2876            "display follows the prompt"
2877        );
2878    }
2879
2880    #[test]
2881    fn arrowing_back_down_restores_the_half_typed_pattern() {
2882        let mut st = new_state_with("alpha\nbravo\n");
2883        type_search(&mut st, SearchDirection::Forward, "bravo");
2884        st.apply(&Action::SearchOpen(SearchDirection::Forward));
2885        st.apply(&Action::InsertChar('a'));
2886        st.apply(&Action::PromptHistory { back: true });
2887        assert_eq!(st.search.prompt().unwrap().text(), "bravo");
2888        st.apply(&Action::PromptHistory { back: false });
2889        assert_eq!(
2890            st.search.prompt().unwrap().text(),
2891            "a",
2892            "the draft comes back"
2893        );
2894        assert_eq!(st.status_model().prompt_text, "a");
2895    }
2896
2897    #[test]
2898    fn history_arrows_do_nothing_on_the_ex_line() {
2899        let mut st = new_state_with("alpha\n");
2900        st.apply(&Action::ChangeMode(Mode::Command));
2901        st.apply(&Action::InsertChar('w'));
2902        st.apply(&Action::PromptHistory { back: true });
2903        assert_eq!(st.status_model().prompt_text, "w", "ex line untouched");
2904    }
2905
2906    fn new_state_with(text: &str) -> EditorState {
2907        let mut bufs = BufferSet::new();
2908        let id = bufs.scratch(text);
2909        EditorState::new_with_buffer(bufs, id)
2910    }
2911
2912    /// The refresh-seal driver (theory/ESCRIBA.md §Refresh-Seal): an applied
2913    /// action advances `edit_gen` (so the renderer repaints), and merely
2914    /// reading the generation does not. This is what lets `gpu.rs` gate the
2915    /// re-highlight/re-shape on a generation change — an idle frame observes an
2916    /// unchanged generation and reuses its cached buffer.
2917    #[test]
2918    fn edit_gen_advances_on_applied_action_not_on_read() {
2919        let mut s = new_state_with("hello\nworld\n");
2920        let g0 = s.edit_gen();
2921        s.apply(&Action::InsertChar('X'));
2922        assert_ne!(
2923            s.edit_gen(),
2924            g0,
2925            "an applied action must advance the refresh generation",
2926        );
2927        // Reading the generation is not a mutation — idle frames stay put.
2928        let g1 = s.edit_gen();
2929        assert_eq!(s.edit_gen(), g1, "reading edit_gen must not advance it");
2930    }
2931
2932    /// The M1 refresh node (theory/ESCRIBA.md §X): a mutation widens the typed
2933    /// `Damage` to cover exactly what changed — local for an in-place edit,
2934    /// to-end-of-document when the line count shifts — and the renderer drains
2935    /// it per frame. `Damage ⊇ changed` by construction; it never narrows.
2936    #[test]
2937    fn damage_tracks_edit_scope_and_drains() {
2938        let mut s = new_state_with("hello\nworld\n");
2939        assert!(s.damage().is_none(), "a fresh state has no damage");
2940
2941        s.apply(&Action::InsertChar('X')); // in-place edit on line 0
2942        assert_eq!(
2943            s.damage(),
2944            Damage::Lines { from: 0, to: 0 },
2945            "a local edit damages just its line",
2946        );
2947
2948        let drained = s.take_damage();
2949        assert_eq!(drained, Damage::Lines { from: 0, to: 0 });
2950        assert!(s.damage().is_none(), "take_damage drains to None");
2951
2952        s.apply(&Action::InsertChar('\n')); // splits line 0 → line count grows
2953        assert_eq!(
2954            s.damage(),
2955            Damage::Lines {
2956                from: 0,
2957                to: u32::MAX,
2958            },
2959            "a line-count change damages to end-of-document",
2960        );
2961    }
2962
2963    /// A state whose active window is a deliberately tiny viewport
2964    /// (`visible_lines` × `visible_columns`) so the scroll-to-contain
2965    /// invariant is exercised on small inputs.
2966    fn new_state_small_viewport(text: &str, vis_lines: u32, vis_cols: u32) -> EditorState {
2967        let mut s = new_state_with(text);
2968        for w in s.layout.windows_mut() {
2969            w.viewport.visible_lines = vis_lines;
2970            w.viewport.visible_columns = vis_cols;
2971        }
2972        s
2973    }
2974
2975    /// The core regression invariant: the active window's viewport CONTAINS
2976    /// the cursor on BOTH axes. This is the operator's exact complaint —
2977    /// "typing past the bottom (or right) leaves the cursor off-screen" —
2978    /// made into a checkable property.
2979    fn assert_cursor_in_viewport(s: &EditorState, ctx: &str) {
2980        let w = s.layout.active_window().expect("active window");
2981        let v = w.viewport;
2982        let c = s.cursor();
2983        assert!(
2984            v.top_line <= c.line && c.line < v.top_line + v.visible_lines,
2985            "[{ctx}] cursor line {} not in vertical window [{}, {}); viewport={v:?}",
2986            c.line,
2987            v.top_line,
2988            v.top_line + v.visible_lines,
2989        );
2990        assert!(
2991            v.left_column <= c.column && c.column < v.left_column + v.visible_columns,
2992            "[{ctx}] cursor column {} not in horizontal window [{}, {}); viewport={v:?}",
2993            c.column,
2994            v.left_column,
2995            v.left_column + v.visible_columns,
2996        );
2997    }
2998
2999    fn press(kc: KeyCode) -> AppEvent {
3000        AppEvent::Key(KeyEvent {
3001            key: kc,
3002            pressed: true,
3003            modifiers: Modifiers::default(),
3004            text: None,
3005        })
3006    }
3007
3008    // ── operator-over-motion (the `dw`/`c$`/`y0` verbs) ──────────────
3009
3010    fn line0_len(s: &EditorState) -> u32 {
3011        s.buffers.get(s.active).unwrap().line_len_chars(0)
3012    }
3013
3014    #[test]
3015    fn delete_to_line_end_clears_line_and_fills_register() {
3016        let mut s = new_state_with("hello world");
3017        s.apply(&Action::ApplyOperator {
3018            op: Operator::Delete,
3019            motion: Motion::LineEnd,
3020        });
3021        assert_eq!(line0_len(&s), 0, "d$ deletes to end of line");
3022        assert_eq!(
3023            s.register(),
3024            Some("hello world"),
3025            "delete fills the register"
3026        );
3027        assert_eq!(
3028            s.cursor(),
3029            Position::ZERO,
3030            "cursor lands at the range start"
3031        );
3032    }
3033
3034    #[test]
3035    fn delete_over_right_motion_removes_one_char() {
3036        let mut s = new_state_with("abc");
3037        s.apply(&Action::ApplyOperator {
3038            op: Operator::Delete,
3039            motion: Motion::Right,
3040        });
3041        assert_eq!(
3042            s.buffers.get(s.active).unwrap().line(0).as_deref(),
3043            Some("bc")
3044        );
3045        assert_eq!(s.register(), Some("a"));
3046    }
3047
3048    #[test]
3049    fn change_to_line_end_deletes_and_enters_insert() {
3050        let mut s = new_state_with("hello world");
3051        assert_eq!(s.modal.mode(), Mode::Normal);
3052        s.apply(&Action::ApplyOperator {
3053            op: Operator::Change,
3054            motion: Motion::LineEnd,
3055        });
3056        assert_eq!(line0_len(&s), 0, "c$ deletes the range");
3057        assert_eq!(
3058            s.modal.mode(),
3059            Mode::Insert,
3060            "change enters Insert to type the replacement"
3061        );
3062        assert_eq!(
3063            s.register(),
3064            Some("hello world"),
3065            "change fills the register"
3066        );
3067    }
3068
3069    #[test]
3070    fn yank_to_line_end_fills_register_without_mutating() {
3071        let mut s = new_state_with("hello world");
3072        s.apply(&Action::ApplyOperator {
3073            op: Operator::Yank,
3074            motion: Motion::LineEnd,
3075        });
3076        assert_eq!(line0_len(&s), 11, "yank does not mutate the buffer");
3077        assert_eq!(s.register(), Some("hello world"), "yank fills the register");
3078        assert_eq!(s.modal.mode(), Mode::Normal, "yank stays in Normal");
3079    }
3080
3081    #[test]
3082    fn resolve_motion_is_the_shared_target_for_move_and_operator() {
3083        // The encapsulation proof: apply_motion (cursor move) and
3084        // apply_operator (range end) BOTH stand on resolve_motion — so a move
3085        // to LineEnd lands at exactly the position the operator deletes to.
3086        let mut s = new_state_with("hello world");
3087        let target = s.resolve_motion(Position::ZERO, Motion::LineEnd).unwrap();
3088        assert_eq!(target, Position::new(0, 11));
3089        s.apply_motion(Motion::LineEnd);
3090        assert_eq!(
3091            s.cursor(),
3092            target,
3093            "the move path resolves the same target the operator uses"
3094        );
3095    }
3096
3097    #[test]
3098    fn empty_motion_range_is_a_no_op() {
3099        // An operator over a zero-width motion (cursor already at line start)
3100        // mutates nothing and leaves the register untouched.
3101        let mut s = new_state_with("abc");
3102        s.apply(&Action::ApplyOperator {
3103            op: Operator::Delete,
3104            motion: Motion::LineStart,
3105        });
3106        assert_eq!(
3107            s.buffers.get(s.active).unwrap().line(0).as_deref(),
3108            Some("abc")
3109        );
3110        assert_eq!(s.register(), None);
3111    }
3112
3113    #[test]
3114    fn operator_then_motion_composes_through_the_pending_fsm() {
3115        // The full keymap→FSM→engine path: dispatching the `d` operator action
3116        // then a `$` motion composes `d$` via the zenmai operator-pending FSM —
3117        // the operator key alone does nothing until the motion arrives.
3118        let mut s = new_state_with("hello world");
3119        s.apply(&Action::Operator(Operator::Delete));
3120        assert_eq!(line0_len(&s), 11, "the operator key alone mutates nothing");
3121        s.apply(&Action::Move(Motion::LineEnd));
3122        assert_eq!(
3123            line0_len(&s),
3124            0,
3125            "d then $ composes d$ and deletes the line"
3126        );
3127        assert_eq!(s.register(), Some("hello world"));
3128    }
3129
3130    #[test]
3131    fn change_operator_through_fsm_enters_insert() {
3132        let mut s = new_state_with("hello world");
3133        s.apply(&Action::Operator(Operator::Change));
3134        s.apply(&Action::Move(Motion::LineEnd));
3135        assert_eq!(s.modal.mode(), Mode::Insert, "c$ deletes and enters Insert");
3136    }
3137
3138    #[test]
3139    fn lone_motion_after_no_operator_just_moves() {
3140        // Without a preceding operator the motion passes through unchanged.
3141        let mut s = new_state_with("hello world");
3142        s.apply(&Action::Move(Motion::LineEnd));
3143        assert_eq!(s.cursor(), Position::new(0, 11));
3144        assert_eq!(line0_len(&s), 11, "a bare motion never mutates");
3145    }
3146
3147    #[test]
3148    fn counted_operator_deletes_count_times() {
3149        // `3d` + a right-motion = `3dl` = delete 3 chars. The operator's count
3150        // flows through the FSM to the composed motion (the bug fix: previously
3151        // the count repeated the operator key and toggled the FSM).
3152        let mut s = new_state_with("abcdef");
3153        s.apply_counted(&Action::Operator(Operator::Delete), 3);
3154        assert_eq!(line0_len(&s), 6, "the operator key alone mutates nothing");
3155        s.apply(&Action::Move(Motion::Right));
3156        assert_eq!(
3157            s.buffers.get(s.active).unwrap().line(0).as_deref(),
3158            Some("def")
3159        );
3160    }
3161
3162    #[test]
3163    fn operator_and_motion_counts_multiply_end_to_end() {
3164        // `2d3l` = delete 2×3 = 6 chars.
3165        let mut s = new_state_with("abcdefgh");
3166        s.apply_counted(&Action::Operator(Operator::Delete), 2);
3167        s.apply_counted(&Action::Move(Motion::Right), 3);
3168        assert_eq!(
3169            s.buffers.get(s.active).unwrap().line(0).as_deref(),
3170            Some("gh")
3171        );
3172    }
3173
3174    #[test]
3175    fn bare_counted_motion_still_repeats_no_regression() {
3176        // `3j` still moves down 3 lines — the count passes through the FSM
3177        // unchanged when no operator is pending.
3178        let mut s = new_state_with("a\nb\nc\nd\ne");
3179        s.apply_counted(&Action::Move(Motion::Down), 3);
3180        assert_eq!(s.cursor().line, 3, "5j-style counted motion preserved");
3181    }
3182
3183    /// A monotonic clock for the key-repeat gate in tests — each `next()`
3184    /// jumps a full second past the previous, so every press it stamps is
3185    /// well outside the 80ms debounce window and therefore an INTENTIONAL
3186    /// press (never a storm tick). Used by tests that fire the *same*
3187    /// navigation key twice and assert editor logic, not debounce timing.
3188    struct SpacedClock(std::time::Instant);
3189    impl SpacedClock {
3190        fn new() -> Self {
3191            Self(std::time::Instant::now())
3192        }
3193        fn next(&mut self) -> std::time::Instant {
3194            self.0 += std::time::Duration::from_secs(1);
3195            self.0
3196        }
3197    }
3198
3199    #[test]
3200    fn hjkl_moves_cursor() {
3201        let mut s = new_state_with("hello\nworld");
3202        s.tick(&press(KeyCode::Char('l')));
3203        assert_eq!(s.cursor().column, 1);
3204        s.tick(&press(KeyCode::Char('j')));
3205        assert_eq!(s.cursor().line, 1);
3206        s.tick(&press(KeyCode::Char('h')));
3207        assert_eq!(s.cursor().column, 0);
3208    }
3209
3210    #[test]
3211    fn insert_mode_inserts_chars() {
3212        let mut s = new_state_with("");
3213        s.tick(&press(KeyCode::Char('i')));
3214        assert_eq!(s.modal.mode(), Mode::Insert);
3215        s.tick(&press(KeyCode::Char('h')));
3216        s.tick(&press(KeyCode::Char('i')));
3217        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "hi");
3218        assert_eq!(s.cursor().column, 2);
3219    }
3220
3221    #[test]
3222    fn esc_returns_to_normal() {
3223        let mut s = new_state_with("");
3224        s.tick(&press(KeyCode::Char('i')));
3225        s.tick(&press(KeyCode::Escape));
3226        assert_eq!(s.modal.mode(), Mode::Normal);
3227    }
3228
3229    #[test]
3230    fn count_prefix_repeats_motion() {
3231        let mut s = new_state_with("abcdefghij");
3232        s.tick(&press(KeyCode::Char('5')));
3233        s.tick(&press(KeyCode::Char('l')));
3234        assert_eq!(s.cursor().column, 5);
3235    }
3236
3237    #[test]
3238    fn close_event_requests_quit() {
3239        let mut s = new_state_with("");
3240        s.tick(&AppEvent::CloseRequested);
3241        assert!(s.quit_requested);
3242    }
3243
3244    #[test]
3245    fn word_next_jumps_past_whitespace() {
3246        let mut s = new_state_with("foo bar baz");
3247        // Two INTENTIONAL `w` presses, spaced past the key-repeat window so
3248        // the gate passes both (a real user's two taps are ≥80ms apart).
3249        let mut clk = SpacedClock::new();
3250        s.tick_at(&press(KeyCode::Char('w')), clk.next());
3251        assert_eq!(s.cursor().column, 4);
3252        s.tick_at(&press(KeyCode::Char('w')), clk.next());
3253        assert_eq!(s.cursor().column, 8);
3254    }
3255
3256    // ── Multi-key / leader pending-stroke ───────────────────────────
3257
3258    #[test]
3259    fn leader_sequence_holds_then_resolves() {
3260        let mut s = new_state_with("a\nbb\nccc");
3261        s.keymap.bind_sequence(
3262            Mode::Normal,
3263            vec![Key::Char(','), Key::Char('g')],
3264            Action::Move(Motion::DocEnd),
3265            "doc end",
3266        );
3267        // `,` begins the sequence — held pending, nothing applied yet.
3268        s.on_key(&Key::Char(','));
3269        assert_eq!(s.pending_keys, vec![Key::Char(',')]);
3270        assert_eq!(s.cursor(), Position::ZERO);
3271        // `g` completes `<leader>g` → DocEnd; pending clears.
3272        s.on_key(&Key::Char('g'));
3273        assert!(s.pending_keys.is_empty());
3274        assert_eq!(s.cursor().line, 2);
3275    }
3276
3277    #[test]
3278    fn two_key_gg_jumps_doc_start() {
3279        let mut s = new_state_with("a\nbb\nccc");
3280        s.keymap.bind_sequence(
3281            Mode::Normal,
3282            vec![Key::Char('g'), Key::Char('g')],
3283            Action::Move(Motion::DocStart),
3284            "doc start",
3285        );
3286        let mut clk = SpacedClock::new();
3287        s.tick_at(&press(KeyCode::Char('j')), clk.next());
3288        s.tick_at(&press(KeyCode::Char('j')), clk.next());
3289        assert_eq!(s.cursor().line, 2);
3290        s.on_key(&Key::Char('g')); // pending
3291        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
3292        s.on_key(&Key::Char('g')); // resolve
3293        assert_eq!(s.cursor(), Position::ZERO);
3294    }
3295
3296    #[test]
3297    fn broken_sequence_aborts_and_clears_pending() {
3298        let mut s = new_state_with("hello");
3299        s.keymap.bind_sequence(
3300            Mode::Normal,
3301            vec![Key::Char('g'), Key::Char('g')],
3302            Action::Move(Motion::DocEnd),
3303            "doc end",
3304        );
3305        s.on_key(&Key::Char('g')); // pending [g]
3306        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
3307        s.on_key(&Key::Char('x')); // breaks gg → abort; x is unbound → no-op
3308        assert!(s.pending_keys.is_empty());
3309        assert_eq!(s.cursor(), Position::ZERO);
3310    }
3311
3312    #[test]
3313    fn single_binding_wins_over_sequence_prefix() {
3314        // A key that is BOTH a complete single binding and the start of
3315        // a sequence fires the single binding immediately (no chord
3316        // timeout needed). Here `h` (move-left) also prefixes `hz`.
3317        let mut s = new_state_with("abcde");
3318        let mut clk = SpacedClock::new();
3319        s.tick_at(&press(KeyCode::Char('l')), clk.next());
3320        s.tick_at(&press(KeyCode::Char('l')), clk.next());
3321        assert_eq!(s.cursor().column, 2);
3322        s.keymap.bind_sequence(
3323            Mode::Normal,
3324            vec![Key::Char('h'), Key::Char('z')],
3325            Action::Move(Motion::DocEnd),
3326            "shadowed",
3327        );
3328        s.on_key(&Key::Char('h'));
3329        assert!(s.pending_keys.is_empty(), "single binding should not pend");
3330        assert_eq!(s.cursor().column, 1, "h moved left immediately");
3331    }
3332
3333    // ── tatara-lisp runtime bridge (imperative programmability) ─────
3334
3335    #[test]
3336    fn lisp_set_option_writes_live_options() {
3337        let mut s = new_state_with("");
3338        s.run_lisp(r#"(set-option "number" "true")"#).unwrap();
3339        assert_eq!(s.options.get("number").map(String::as_str), Some("true"));
3340    }
3341
3342    #[test]
3343    fn lisp_insert_modifies_buffer_and_advances_cursor() {
3344        let mut s = new_state_with("");
3345        s.run_lisp(r#"(insert "abc")"#).unwrap();
3346        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
3347        assert_eq!(s.cursor(), Position::new(0, 3));
3348    }
3349
3350    #[test]
3351    fn lisp_message_appends_to_messages() {
3352        let mut s = new_state_with("");
3353        s.run_lisp(r#"(message "hello from lisp")"#).unwrap();
3354        assert_eq!(s.messages, vec!["hello from lisp".to_string()]);
3355    }
3356
3357    #[test]
3358    fn lisp_reads_snapshot_and_branches_to_effect() {
3359        // Genuine programmability: Lisp reads the live cursor line and
3360        // an `if` decides which option to set.
3361        let mut s = new_state_with("one\ntwo\nthree");
3362        // cursor at line 0 → "top" branch
3363        s.run_lisp(r#"(if (= (cursor-line) 0) (set-option "pos" "top") (set-option "pos" "mid"))"#)
3364            .unwrap();
3365        assert_eq!(s.options.get("pos").map(String::as_str), Some("top"));
3366    }
3367
3368    #[test]
3369    fn lisp_run_command_effect_drives_registry() {
3370        // `(run-command "undo")` reaches the live command registry and
3371        // reverts a prior Lisp-driven insert — proving the RunCommand
3372        // effect dispatches through real editor commands.
3373        let mut s = new_state_with("");
3374        s.run_lisp(r#"(insert "abc")"#).unwrap();
3375        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
3376        s.run_lisp(r#"(run-command "undo")"#).unwrap();
3377        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "");
3378    }
3379
3380    #[test]
3381    fn lisp_run_command_quit_sets_quit_requested_via_typed_flag() {
3382        // The full imperative-quit path: (run-command "quit") routes
3383        // through the registry's typed `quit_requested` signal — no string
3384        // sentinel, and no minibuffer pollution (the editor stays in a
3385        // clean Normal state, which has no minibuffer at all).
3386        let mut s = new_state_with("");
3387        s.run_lisp(r#"(run-command "quit")"#).unwrap();
3388        assert!(s.quit_requested, "lisp-driven quit must set quit_requested");
3389        assert_eq!(
3390            s.modal.minibuffer(),
3391            "",
3392            "quit must not pollute any command line — Normal mode has no minibuffer",
3393        );
3394    }
3395
3396    // ── Lazy plugin activation (PluginHost) ────────────────────────
3397
3398    #[test]
3399    fn lazy_plugin_activates_on_command_trigger() {
3400        // A user plugin gated on `Command: LazyGo` has its entry applied
3401        // the first time that command runs — proving the lazy.nvim
3402        // `cmd =` model works end-to-end against live editor state.
3403        let mut s = new_state_with("");
3404        s.register_lazy_plugin(
3405            "user-lazy",
3406            vec![LazyTrigger::Command("LazyGo".into())],
3407            r#"(defoption :name "lazy-loaded" :value "yes")
3408               (defcmd :name "LazyGo" :description "noop" :action "editor.noop")"#,
3409        );
3410        assert_eq!(s.plugin_host.pending(), 1);
3411        assert!(
3412            s.options.get("lazy-loaded").is_none(),
3413            "entry not applied yet"
3414        );
3415
3416        // Drive the command through the public imperative path.
3417        s.run_lisp(r#"(run-command "LazyGo")"#).unwrap();
3418
3419        assert_eq!(
3420            s.options.get("lazy-loaded").map(String::as_str),
3421            Some("yes"),
3422            "the command trigger applied the plugin's entry",
3423        );
3424        assert_eq!(s.plugin_host.pending(), 0, "plugin activated exactly once");
3425    }
3426
3427    #[test]
3428    fn lazy_plugin_activates_on_filetype() {
3429        let mut s = new_state_with("");
3430        s.register_lazy_plugin(
3431            "user-rust",
3432            vec![LazyTrigger::FileType("rust".into())],
3433            r#"(defoption :name "rust-plugin" :value "on")"#,
3434        );
3435        let n = s.activate_filetype_plugins("rust");
3436        assert_eq!(n, 1);
3437        assert_eq!(s.options.get("rust-plugin").map(String::as_str), Some("on"));
3438        // A second open of the same filetype is a no-op (one-shot).
3439        assert_eq!(s.activate_filetype_plugins("rust"), 0);
3440    }
3441
3442    #[test]
3443    fn cached_vm_serves_multiple_run_lisp_calls() {
3444        let mut s = new_state_with("");
3445        s.run_lisp(r#"(message "one")"#).unwrap();
3446        assert!(
3447            s.lisp_vm.is_some(),
3448            "VM should be cached after first run_lisp"
3449        );
3450        s.run_lisp(r#"(message "two")"#).unwrap();
3451        assert_eq!(s.messages, vec!["one".to_string(), "two".to_string()]);
3452    }
3453
3454    #[test]
3455    fn lisp_define_persists_across_run_lisp_calls() {
3456        // The cached VM's top-level env persists across calls (REPL
3457        // semantics): a `define` in one call is visible in the next.
3458        let mut s = new_state_with("");
3459        s.run_lisp(r#"(define greeting "hi")"#).unwrap();
3460        s.run_lisp(r#"(message greeting)"#).unwrap();
3461        assert_eq!(s.messages, vec!["hi".to_string()]);
3462    }
3463
3464    #[test]
3465    fn snapshot_is_isolated_within_one_run_lisp_call_and_refreshes_across() {
3466        // Within ONE call a program cannot observe its own writes — the
3467        // read snapshot is captured before eval, effects apply after. A
3468        // later call sees the refreshed snapshot.
3469        let mut s = new_state_with("");
3470        s.run_lisp(
3471            r#"(insert "ab") (set-option "col" (if (= (cursor-column) 0) "stale-zero" "live"))"#,
3472        )
3473        .unwrap();
3474        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "ab");
3475        assert_eq!(
3476            s.options.get("col").map(String::as_str),
3477            Some("stale-zero"),
3478            "cursor-column within the same call reads the pre-eval snapshot",
3479        );
3480        // After the first call the cursor advanced to column 2; the next
3481        // call's snapshot reflects it.
3482        s.run_lisp(r#"(set-option "col2" (if (= (cursor-column) 2) "live-two" "other"))"#)
3483            .unwrap();
3484        assert_eq!(
3485            s.options.get("col2").map(String::as_str),
3486            Some("live-two"),
3487            "a later call sees the refreshed snapshot",
3488        );
3489    }
3490
3491    #[test]
3492    fn insert_text_effect_multiline_lands_cursor_on_last_line() {
3493        let mut s = new_state_with("");
3494        s.apply_host_effects(vec![Negai::InsertText("foo\nbar".to_string())]);
3495        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "foo\nbar");
3496        assert_eq!(s.cursor(), Position::new(1, 3));
3497    }
3498
3499    #[test]
3500    fn visual_mode_sequence_resolves() {
3501        let mut s = new_state_with("abc");
3502        s.modal.enter(Mode::Visual);
3503        s.keymap.bind_sequence(
3504            Mode::Visual,
3505            vec![Key::Char('g'), Key::Char('e')],
3506            Action::Move(Motion::DocEnd),
3507            "ge",
3508        );
3509        s.on_key(&Key::Char('g'));
3510        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
3511        s.on_key(&Key::Char('e'));
3512        assert!(s.pending_keys.is_empty());
3513        assert_eq!(
3514            s.cursor().column,
3515            3,
3516            "ge resolved to doc-end in visual mode"
3517        );
3518    }
3519
3520    #[test]
3521    fn sequence_abort_with_bound_breaking_key_redispatches() {
3522        // gg is a sequence; `l` (move-right) is a bound single key. After
3523        // `g` pends, `l` breaks gg, aborts, and is re-dispatched fresh.
3524        let mut s = new_state_with("abcde");
3525        s.keymap.bind_sequence(
3526            Mode::Normal,
3527            vec![Key::Char('g'), Key::Char('g')],
3528            Action::Move(Motion::DocEnd),
3529            "gg",
3530        );
3531        s.on_key(&Key::Char('g'));
3532        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
3533        s.on_key(&Key::Char('l'));
3534        assert!(s.pending_keys.is_empty());
3535        assert_eq!(
3536            s.cursor().column,
3537            1,
3538            "the breaking key l should re-dispatch as move-right",
3539        );
3540    }
3541
3542    // ── Viewport-follows-cursor invariant (both axes) ───────────────
3543
3544    #[test]
3545    fn viewport_contains_cursor_after_every_op() {
3546        // Tiny window: 5 visible lines × 10 visible columns. Drive a
3547        // representative scripted sequence and assert the viewport contains
3548        // the cursor after EVERY mutating step.
3549        let mut s = new_state_small_viewport("", 5, 10);
3550        assert_cursor_in_viewport(&s, "initial");
3551
3552        // Enter insert mode and type 30 newline-separated lines — this is
3553        // the exact "type past the bottom" complaint.
3554        s.tick(&press(KeyCode::Char('i')));
3555        assert_eq!(s.modal.mode(), Mode::Insert);
3556        for line in 0..30u32 {
3557            for c in "line".chars() {
3558                s.tick(&press(KeyCode::Char(c)));
3559                assert_cursor_in_viewport(&s, "typing chars");
3560            }
3561            s.tick(&press(KeyCode::Enter));
3562            assert_cursor_in_viewport(&s, &format!("newline after line {line}"));
3563        }
3564
3565        // Type a long (200-char) line — the "type past the right edge"
3566        // complaint. The cursor must stay horizontally visible the whole way.
3567        for i in 0..200u32 {
3568            s.tick(&press(KeyCode::Char('x')));
3569            assert_cursor_in_viewport(&s, &format!("long-line char {i}"));
3570        }
3571
3572        // Multi-line insert_text effect (the `(insert …)` Lisp path).
3573        s.insert_text("alpha\nbeta\ngamma delta epsilon zeta");
3574        assert_cursor_in_viewport(&s, "insert_text multiline");
3575
3576        // Back to normal mode and move in all directions / to extremes.
3577        s.tick(&press(KeyCode::Escape));
3578        assert_eq!(s.modal.mode(), Mode::Normal);
3579        for m in [
3580            Motion::DocStart,
3581            Motion::DocEnd,
3582            Motion::Down,
3583            Motion::Down,
3584            Motion::Up,
3585            Motion::Right,
3586            Motion::Right,
3587            Motion::Left,
3588            Motion::LineEnd,
3589            Motion::LineStart,
3590            Motion::GotoLine(1),
3591            Motion::GotoLine(40),
3592            Motion::PageDown,
3593            Motion::PageUp,
3594        ] {
3595            s.apply_motion(m);
3596            assert_cursor_in_viewport(&s, &format!("after motion {m:?}"));
3597        }
3598
3599        // Undo many times — the buffer shrinks; the viewport must re-follow
3600        // the (now clamped) cursor.
3601        for i in 0..50u32 {
3602            s.apply(&Action::Undo);
3603            assert_cursor_in_viewport(&s, &format!("undo {i}"));
3604        }
3605        // Redo back up.
3606        for i in 0..50u32 {
3607            s.apply(&Action::Redo);
3608            assert_cursor_in_viewport(&s, &format!("redo {i}"));
3609        }
3610    }
3611
3612    #[test]
3613    fn insert_at_eof_keeps_cursor_in_bounds() {
3614        // Inserting at the end of the buffer must leave the cursor clamped
3615        // to a valid position (and inside the viewport).
3616        let mut s = new_state_small_viewport("abc", 5, 10);
3617        s.apply_motion(Motion::DocEnd);
3618        s.tick(&press(KeyCode::Char('i')));
3619        s.tick(&press(KeyCode::Char('d')));
3620        let buf = s.buffers.get(s.active).unwrap();
3621        let clamped = buf.clamp(s.cursor());
3622        assert_eq!(
3623            s.cursor(),
3624            clamped,
3625            "cursor must be clamped in-bounds at EOF"
3626        );
3627        assert_cursor_in_viewport(&s, "insert at eof");
3628    }
3629
3630    #[test]
3631    fn count_prefix_then_sequence_repeats() {
3632        // `2` then `gj` (→ move-down) repeats the resolved action twice.
3633        let mut s = new_state_with("a\nb\nc\nd\ne");
3634        s.keymap.bind_sequence(
3635            Mode::Normal,
3636            vec![Key::Char('g'), Key::Char('j')],
3637            Action::Move(Motion::Down),
3638            "gj",
3639        );
3640        s.on_key(&Key::Char('2'));
3641        s.on_key(&Key::Char('g'));
3642        s.on_key(&Key::Char('j'));
3643        assert_eq!(s.cursor().line, 2, "count 2 should repeat the gj motion");
3644    }
3645
3646    // ── Key-repeat gate (awase::KeyRepeatGate) ──────────────────────────
3647
3648    #[test]
3649    fn held_key_repeat_storm_is_debounced_in_normal_mode() {
3650        // The audit's exact complaint: holding `j` floods motion events
3651        // and thrashes the viewport. Simulate an OS key-repeat storm — 20
3652        // identical `j` KeyDowns at 50ms intervals (typical repeat cadence)
3653        // — and assert only the gated subset (one per 80ms window) actually
3654        // moves the cursor.
3655        let mut s = new_state_with(&"x\n".repeat(40));
3656        let t0 = std::time::Instant::now();
3657        let mut delivered = 0u32;
3658        for i in 0..20u32 {
3659            let before = s.cursor().line;
3660            s.tick_at(
3661                &press(KeyCode::Char('j')),
3662                t0 + std::time::Duration::from_millis(u64::from(i) * 50),
3663            );
3664            if s.cursor().line != before {
3665                delivered += 1;
3666            }
3667        }
3668        // 20 events over ~1s at 50ms spacing, 80ms gate ⇒ ~13 pass — far
3669        // fewer than the 20 the ungated path would have applied.
3670        assert!(
3671            (10..=14).contains(&delivered),
3672            "expected the storm debounced to ~13 moves, got {delivered}",
3673        );
3674        assert!(
3675            delivered < 20,
3676            "the gate must drop SOME storm ticks, not pass all 20",
3677        );
3678    }
3679
3680    #[test]
3681    fn spaced_intentional_taps_all_pass() {
3682        // Intentional taps spaced past the debounce window must ALL reach
3683        // the editor — the gate filters storms, never deliberate input.
3684        let mut s = new_state_with(&"x\n".repeat(10));
3685        let t0 = std::time::Instant::now();
3686        for i in 0..5u32 {
3687            s.tick_at(
3688                &press(KeyCode::Char('j')),
3689                // 100ms apart — comfortably past the 80ms window.
3690                t0 + std::time::Duration::from_millis(u64::from(i) * 100),
3691            );
3692        }
3693        assert_eq!(s.cursor().line, 5, "all 5 spaced `j` taps moved the cursor");
3694    }
3695
3696    #[test]
3697    fn distinct_keys_have_independent_clocks() {
3698        // Holding `j` must not block a simultaneous `l` — the gate keys on
3699        // the Key, so independent keys have independent windows.
3700        let mut s = new_state_with("abc\ndef\nghi");
3701        let t = std::time::Instant::now();
3702        s.tick_at(&press(KeyCode::Char('j')), t);
3703        // `j` again within the window is dropped…
3704        s.tick_at(
3705            &press(KeyCode::Char('j')),
3706            t + std::time::Duration::from_millis(10),
3707        );
3708        assert_eq!(s.cursor().line, 1, "second `j` within window dropped");
3709        // …but `l` at the same instant passes (its own clock).
3710        s.tick_at(
3711            &press(KeyCode::Char('l')),
3712            t + std::time::Duration::from_millis(10),
3713        );
3714        assert_eq!(s.cursor().column, 1, "`l` is not blocked by `j`'s clock");
3715    }
3716
3717    // ── Cursors newtype is the single cursor home ──────────────────────
3718
3719    #[test]
3720    fn cursor_home_preserves_single_cursor_behavior() {
3721        // The typed `Cursors` wrapper behaves exactly like the old bare
3722        // `Position` field for single-cursor editing: the read accessor
3723        // tracks every mutation routed through `set_cursor`, and there is
3724        // exactly one caret.
3725        let mut s = new_state_with("hello\nworld\nthere");
3726        assert_eq!(s.cursor(), Position::ZERO);
3727        assert_eq!(s.cursors.count(), 1, "phase-1 holds exactly one caret");
3728
3729        s.apply_motion(Motion::Down);
3730        s.apply_motion(Motion::Right);
3731        s.apply_motion(Motion::Right);
3732        assert_eq!(s.cursor(), Position::new(1, 2));
3733        // Still a single caret after a sequence of motions.
3734        assert_eq!(s.cursors.count(), 1);
3735
3736        // The accessor is the SAME value the viewport-follow path read.
3737        let w = s.layout.active_window().unwrap();
3738        assert!(w.viewport.top_line <= s.cursor().line);
3739    }
3740
3741    #[test]
3742    fn insert_mode_is_ungated_so_repeat_typing_works() {
3743        // Holding a key to repeat-type a character is intended in Insert
3744        // mode — the gate must NOT suppress it. 10 rapid identical `x`
3745        // keystrokes at the same instant must all land as text.
3746        let mut s = new_state_with("");
3747        s.tick(&press(KeyCode::Char('i')));
3748        assert_eq!(s.modal.mode(), Mode::Insert);
3749        let t = std::time::Instant::now();
3750        for _ in 0..10 {
3751            s.tick_at(&press(KeyCode::Char('x')), t);
3752        }
3753        assert_eq!(
3754            s.buffers.get(s.active).unwrap().to_string(),
3755            "xxxxxxxxxx",
3756            "insert-mode repeat typing is ungated",
3757        );
3758    }
3759}