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