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