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