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