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            // The ex-line has no caret of its own yet, so it reports the end —
631            // which is where an append-only line's caret always is. Stated
632            // rather than defaulted silently: giving the ex-line real caret
633            // editing is the same change applied to `ModalState`.
634            prompt_caret: prompt.map_or_else(
635                || self.modal.minibuffer().chars().count(),
636                escriba_search::Prompt::caret,
637            ),
638            count: self.match_count(),
639            message: self.messages.last().map(String::as_str),
640        }
641    }
642
643    /// `[3/17]` for the current pattern.
644    ///
645    /// While a prompt is open the count describes the PREVIEW — the answer to
646    /// "what would Enter do", which is the question being asked mid-typing.
647    /// Once committed it describes where the cursor actually is.
648    #[must_use]
649    fn match_count(&self) -> MatchCount {
650        if self.search.is_prompting() {
651            let text = self.active_text();
652            // ONE scan, four outcomes. `Incomplete` and `NoMatch` used to be
653            // the same `None`, so a half-typed character class reported
654            // `[0/0]` — telling the user their pattern matches nothing while
655            // they are still writing it.
656            return match self.search.preview(&text) {
657                escriba_search::Preview::Landed { step, total } => {
658                    MatchCount::new(step.index, total)
659                }
660                escriba_search::Preview::NoMatch => MatchCount::None,
661                escriba_search::Preview::Incomplete | escriba_search::Preview::Idle => {
662                    MatchCount::Idle
663                }
664            };
665        }
666        if self.search.pattern().is_none() {
667            return MatchCount::Idle;
668        }
669        let total = self.search.matches().len();
670        // Read THROUGH the anchor: an ordinal computed against text that has
671        // since changed reads as absent, so a stale count cannot be displayed.
672        let rev = self.text_rev();
673        self.search_at.as_ref().and_then(|a| a.get(rev)).map_or(
674            if total == 0 {
675                MatchCount::None
676            } else {
677                MatchCount::Idle
678            },
679            |&i| MatchCount::new(i, total),
680        )
681    }
682
683    /// `.` — replay the last change at the cursor.
684    ///
685    /// Two steps, because a change can be two: run the action, then re-type
686    /// whatever followed it. `cgn` + `.` is exactly this — change the next
687    /// match, then repeat that whole gesture on the one after.
688    fn repeat_last_change(&mut self) {
689        let Some(change) = self.last_change.clone() else {
690            self.messages
691                .push("E32: No previous change to repeat".to_string());
692            return;
693        };
694
695        for _ in 0..change.count.max(1) {
696            self.apply_resolved(&change.action);
697        }
698        for c in change.inserted.chars() {
699            self.apply_resolved(&Action::InsertChar(c));
700        }
701        if self.modal.mode() == Mode::Insert {
702            // A replayed change must not leave the editor in Insert — the
703            // original ended with an Esc the recording deliberately does not
704            // store, since it is punctuation rather than part of the change.
705            self.apply_resolved(&Action::ChangeMode(Mode::Normal));
706        }
707        // The replay wrote through `apply_resolved`, which re-records
708        // `last_change` from the inner action. Put the ORIGINAL back so a
709        // second `.` repeats the same change rather than a fragment of it.
710        self.last_change = Some(change);
711        self.recording_insert = false;
712    }
713
714    /// Resolve a text object to the range it names.
715    ///
716    /// `gn` uses the INCLUSIVE step, so a cursor already sitting inside a
717    /// match operates on THAT match rather than skipping to the next — which
718    /// is what makes `cgn` then `.` walk matches one at a time instead of
719    /// every other one.
720    fn resolve_object(&self, object: escriba_core::TextObject) -> Option<Range> {
721        use escriba_core::TextObject as O;
722        let at = self.cursor_char();
723        let matches = self.search.matches();
724
725        // A match CONTAINING the cursor wins outright, whichever direction the
726        // object names.
727        //
728        // Comparing only against `m.start` — which is what a `starts`-vector
729        // plus `Bound::Inclusive` does — is right only when the cursor sits on
730        // a match's FIRST character. One column further in, `start < at` and
731        // the match is rejected, so `cgn` skipped the very instance the
732        // operator was standing in and the rename silently missed it. vim
733        // operates on the containing match from every interior column, and the
734        // `starts`-only comparison cannot express "contains" because it never
735        // looks at `m.end`.
736        let idx = matches.iter().position(|m| m.contains(at)).or_else(|| {
737            let starts: Vec<usize> = matches.iter().map(|m| m.start).collect();
738            match object {
739                O::NextMatch => Bound::Inclusive.first_matching(&starts, at, true),
740                O::PrevMatch => Bound::Inclusive.first_matching(&starts, at, false),
741            }
742        })?;
743
744        let m = matches.get(idx)?;
745        let buf = self.buffers.get(self.active)?;
746        Some(Range {
747            start: buf.char_to_position(m.start),
748            end: buf.char_to_position(m.end),
749        })
750    }
751
752    fn land_on(&mut self, step: escriba_search::Step) {
753        if let Some(buf) = self.buffers.get(self.active) {
754            let pos = buf.char_to_position(step.target.start);
755            self.set_cursor(pos);
756        }
757        // The `[3/17]` numerator. `Step` has carried this index since the
758        // engine was written — `engine.rs` even names the counter as the
759        // reason it exists — and every consumer discarded it until now.
760        self.search_at = Some(Anchored::new(step.index, self.text_rev()));
761    }
762
763    /// vim's "search hit BOTTOM, continuing at TOP".
764    ///
765    /// One reporter, called by the two places a search can wrap: the shared
766    /// commit and `n`/`N`. `land_on` deliberately does NOT report, or the bare
767    /// commit would say it twice.
768    fn report_wrap(&mut self, step: &escriba_search::Step) {
769        if let Some(msg) = step.wrapped.message() {
770            self.messages.push(msg.to_string());
771        }
772    }
773
774    /// `n` / `N`. Reports vim's E486 when the pattern matches nothing, rather
775    /// than failing silently — a search that appears to do nothing is
776    /// indistinguishable from a dropped keystroke.
777    fn jump_search(&mut self, reverse: bool) {
778        // Using the matches re-lights them: `n` after an auto-clear shows you
779        // what you are walking through.
780        self.search.relight();
781        // `n` is a far jump — record where we leave from so `<C-o>` works.
782        self.jumps.push(self.cursor());
783        let at = self.cursor_char();
784        match self.search.repeat(at, reverse) {
785            Some(step) => {
786                // `n` wrapping the file says so, same as a commit does.
787                self.report_wrap(&step);
788                self.land_on(step);
789            }
790            None => {
791                let msg = self.search.pattern().map_or_else(
792                    || "E35: No previous regular expression".to_string(),
793                    |p| {
794                        let mut m = String::from("E486: Pattern not found: ");
795                        m.push_str(p.raw());
796                        m
797                    },
798                );
799                self.messages.push(msg);
800            }
801        }
802    }
803
804    /// Move the cursor to where the in-progress pattern would land, without
805    /// committing anything. vim's `incsearch`.
806    ///
807    /// A pattern that does not compile yet (`/a[`, mid-typing) previews
808    /// nothing and reports nothing — an error toast on every keystroke of a
809    /// character class would be unusable.
810    fn preview_search(&mut self) {
811        let text = self.active_text();
812        let Some(origin) = self.search.prompt().map(|p| p.origin) else {
813            return;
814        };
815        let target = match self.search.preview(&text) {
816            escriba_search::Preview::Landed { step, .. } => step.target.start,
817            // Nothing to show: back to where the search started. Covers a
818            // half-typed pattern and a pattern that finds nothing alike —
819            // both mean "there is no match to preview".
820            escriba_search::Preview::Idle
821            | escriba_search::Preview::Incomplete
822            | escriba_search::Preview::NoMatch => origin,
823        };
824        // A pattern that STOPS matching returns the cursor to the origin.
825        //
826        // Preview used to only ever move forward, so typing `ch` (a match) and
827        // then `chz` (none) left the cursor parked on the `ch` match — a
828        // preview showing a position the pattern no longer justifies, while
829        // the count beside it read `[0/0]`. Restoring is also what makes
830        // Escape's promise legible: at every keystroke the cursor is either on
831        // a real match or back where you started, never on a stale one.
832        if let Some(buf) = self.buffers.get(self.active) {
833            let pos = buf.char_to_position(target);
834            self.set_cursor(pos);
835        }
836    }
837
838    /// `d/foo<CR>` — commit the prompt and operate from the prompt's origin to
839    /// where the search lands, as ONE action.
840    ///
841    /// Split from [`Self::submit_search`] rather than sharing it because the
842    /// two want opposite things from the commit: the bare `/` MOVES the cursor
843    /// to the match, and an operated `/` must NOT — the cursor is the
844    /// operator's start point, and moving it first would leave the operator
845    /// with a zero-width range.
846    /// Commit the open search prompt. The ONE copy of the sequence.
847    ///
848    /// Reports its own failures (E486 / E35) so neither caller has to carry a
849    /// third copy of the message strings. `Accepted::Invalid` cannot reach
850    /// here — `apply_counted` rejects an uncompilable pattern at the dispatch
851    /// boundary before the FSM or this method ever sees the submit.
852    fn commit_search_prompt(&mut self) -> CommitOutcome {
853        let text = self.active_text();
854        let Some((origin, skip)) = self.search.prompt().map(|p| (p.origin, p.preview_skip()))
855        else {
856            return CommitOutcome::NoPrompt;
857        };
858
859        match self.search.accept(&text) {
860            escriba_search::Accepted::Committed | escriba_search::Accepted::ReusedPrevious => {
861                self.modal.clear_minibuffer();
862                self.modal.enter(Mode::Normal);
863                match self.search.commit_step_skipping(origin, skip) {
864                    Some(step) => {
865                        // The wrap notice belongs HERE, once, for both commit
866                        // paths. Reporting it in each caller is what let the
867                        // operated path lose it in the first place — and my
868                        // first attempt at this refactor duplicated it again
869                        // rather than moving it, which the red proof caught.
870                        self.report_wrap(&step);
871                        CommitOutcome::Landed { origin, step }
872                    }
873                    None => {
874                        self.report_pattern_not_found();
875                        CommitOutcome::NotFound
876                    }
877                }
878            }
879            escriba_search::Accepted::NothingToRepeat => {
880                self.modal.clear_minibuffer();
881                self.modal.enter(Mode::Normal);
882                self.messages
883                    .push("E35: No previous regular expression".to_string());
884                CommitOutcome::NoPrevious
885            }
886            // Unreachable: the boundary guard in `apply_counted` returns early
887            // on an uncompilable pattern, leaving the prompt open. Reported
888            // rather than `unreachable!()` — a panic in the editor's commit
889            // path is a worse failure than a duplicate message.
890            escriba_search::Accepted::Invalid(e) => {
891                let mut m = String::from("E383: Invalid search string: ");
892                m.push_str(&e.to_string());
893                self.messages.push(m);
894                CommitOutcome::NoPrompt
895            }
896        }
897    }
898
899    /// vim's E486, with the pattern named. One place, so every path that fails
900    /// to find reports identically.
901    fn report_pattern_not_found(&mut self) {
902        let mut m = String::from("E486: Pattern not found");
903        if let Some(p) = self.search.pattern() {
904            m.push_str(": ");
905            m.push_str(p.raw());
906        }
907        self.messages.push(m);
908    }
909
910    /// Bare `/foo<CR>` — commit and MOVE the cursor to the match.
911    ///
912    /// The only difference from the operated path is that this one lands;
913    /// everything else lives in `commit_search_prompt`.
914    fn submit_search(&mut self) {
915        match self.commit_search_prompt() {
916            CommitOutcome::Landed { origin, step } => {
917                if let Some(buf) = self.buffers.get(self.active) {
918                    let from = buf.char_to_position(origin);
919                    self.jumps.push(from);
920                }
921                self.land_on(step);
922            }
923            CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
924        }
925    }
926
927    /// `d/foo<CR>` — commit, then operate from the prompt's origin to where the
928    /// search lands, as ONE action.
929    ///
930    /// The cursor must NOT move to the match first: it is the operator's start
931    /// point. That is the whole reason this differs from the bare path, and
932    /// now the only reason.
933    fn submit_search_operated(&mut self, op: Operator) {
934        match self.commit_search_prompt() {
935            CommitOutcome::Landed { origin, step } => {
936                if let Some(buf) = self.buffers.get(self.active) {
937                    let from = buf.char_to_position(origin);
938                    let target = buf.char_to_position(step.target.start);
939                    // Operating over a search is itself a far jump.
940                    self.jumps.push(from);
941                    self.set_cursor(from);
942                    self.apply_operator_to(op, target);
943                }
944            }
945            CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
946        }
947    }
948
949    fn apply_resolved(&mut self, action: &Action) {
950        // Snapshot the scope inputs before the mutation so the resulting
951        // Damage covers the changed region (the S3 seal — conservative widen).
952        let lines_before = self.active_line_count();
953        // Snapshot for the dot register: the only reliable witness that this
954        // action changed text is that the buffer's revision moved.
955        let rev_before = self.text_rev();
956        let cline_before = self.cursor().line;
957        match action {
958            Action::Move(m) => self.apply_motion(*m),
959            Action::SearchOpen(dir) => {
960                // vim's `/` is the command-line with a different prompt char,
961                // so we reuse Command mode; `search.prompt` is what tells a
962                // later <CR> this is a search and not an ex-command.
963                let origin = self.cursor_char();
964                self.search.open(*dir, origin);
965                self.modal.enter(Mode::Command);
966            }
967            Action::SearchRepeat { reverse } => self.jump_search(*reverse),
968            Action::SearchWord { reverse } => {
969                let dir = if *reverse {
970                    SearchDirection::Backward
971                } else {
972                    SearchDirection::Forward
973                };
974                let (text, at) = (self.active_text(), self.cursor_char());
975                // `*` jumps, so it records too.
976                self.jumps.push(self.cursor());
977                match self.search.search_word(&text, at, dir) {
978                    Some(step) => self.land_on(step),
979                    // vim beeps and stays put when there is no word under the
980                    // cursor; a silent no-op would look like a broken key.
981                    None => self
982                        .messages
983                        .push("E348: No string under cursor".to_string()),
984                }
985            }
986            Action::ClearSearchHighlight => self.search.clear_highlight(),
987            Action::SearchSubmitOperated { op } => self.submit_search_operated(*op),
988            Action::TextObject(object) => {
989                // Bare `gn` moves onto the match. vim additionally starts a
990                // Visual selection of it; escriba's Visual plumbing does not
991                // carry a selection an operator can consume yet, so this
992                // stops at the jump rather than faking a selection that
993                // nothing would honour.
994                if let Some(range) = self.resolve_object(*object) {
995                    self.jumps.push(self.cursor());
996                    self.set_cursor(range.start);
997                } else {
998                    self.report_pattern_not_found();
999                }
1000            }
1001            Action::ApplyOperatorObject { op, object } => match self.resolve_object(*object) {
1002                Some(range) => self.apply_operator_over(*op, range),
1003                None => self.report_pattern_not_found(),
1004            },
1005            Action::RepeatLastChange => self.repeat_last_change(),
1006            Action::JumpBack => {
1007                let here = self.cursor();
1008                if let Some(pos) = self.jumps.back(here) {
1009                    self.set_cursor(pos);
1010                } else {
1011                    self.messages
1012                        .push("E662: At start of changelist".to_string());
1013                }
1014            }
1015            Action::JumpForward => {
1016                if let Some(pos) = self.jumps.forward() {
1017                    self.set_cursor(pos);
1018                } else {
1019                    self.messages.push("E663: At end of changelist".to_string());
1020                }
1021            }
1022            Action::ChangeMode(m) => {
1023                // Leaving the cmdline abandons any open search prompt and
1024                // returns the cursor home. The COMMITTED pattern survives —
1025                // cancelling a new search must not erase the old highlights.
1026                if *m == Mode::Normal && self.search.is_prompting() {
1027                    if let Some(origin) = self.search.cancel() {
1028                        if let Some(buf) = self.buffers.get(self.active) {
1029                            let pos = buf.char_to_position(origin);
1030                            self.set_cursor(pos);
1031                        }
1032                    }
1033                }
1034                self.modal.enter(*m);
1035            }
1036            Action::InsertChar(c) => self.insert_char(*c),
1037            Action::Edit(edit) => self.apply_edit(edit),
1038            Action::Undo => {
1039                if let Some(buf) = self.buffers.get_mut(self.active) {
1040                    let _ = buf.undo();
1041                }
1042                // The buffer may have shrunk — re-follow so the viewport
1043                // re-contains a now-out-of-bounds cursor.
1044                self.set_cursor(self.cursor());
1045            }
1046            Action::Redo => {
1047                if let Some(buf) = self.buffers.get_mut(self.active) {
1048                    let _ = buf.redo();
1049                }
1050                self.set_cursor(self.cursor());
1051            }
1052            Action::Save => {
1053                if let Some(buf) = self.buffers.get_mut(self.active) {
1054                    let _ = buf.save();
1055                }
1056                self.set_cursor(self.cursor());
1057            }
1058            Action::Quit => self.quit_requested = true,
1059            Action::SubmitCommand => {
1060                if self.search.is_prompting() {
1061                    self.submit_search();
1062                } else {
1063                    self.submit_command();
1064                }
1065            }
1066            Action::Command { name, args } => self.run_command(name, args),
1067            Action::ApplyOperator { op, motion } => self.apply_operator(*op, *motion),
1068            // The operator-pending FSM consumes Operator keys (begins pending);
1069            // they never reach the executor. Defensive no-op for exhaustiveness.
1070            Action::Operator(_) => {}
1071            Action::PromptCaret { to } => {
1072                if self.search.is_prompting() {
1073                    self.search.move_caret(*to);
1074                }
1075            }
1076            Action::SearchPreviewStep { forward } => {
1077                if self.search.is_prompting() {
1078                    self.search.preview_step(*forward);
1079                    self.preview_search();
1080                }
1081            }
1082            Action::PromptDelete => {
1083                if self.search.is_prompting() {
1084                    self.search.delete_at_caret();
1085                    self.preview_search();
1086                }
1087            }
1088            Action::PromptDeleteWord => {
1089                if self.search.is_prompting() {
1090                    self.search.delete_word_before_caret();
1091                    self.preview_search();
1092                }
1093            }
1094            Action::PromptClearToStart => {
1095                if self.search.is_prompting() {
1096                    self.search.clear_before_caret();
1097                    self.preview_search();
1098                }
1099            }
1100            Action::PromptBackspace => {
1101                self.prompt_backspace();
1102                // Shortening the pattern changes which matches exist, so the
1103                // preview must re-run — otherwise the cursor sits on a match
1104                // of a pattern that is no longer typed.
1105                if self.search.is_prompting() {
1106                    self.preview_search();
1107                }
1108            }
1109            Action::PromptHistory { back } => {
1110                if self.search.is_prompting() {
1111                    self.search.history_step(*back);
1112                    // No minibuffer resync: the shadow is the ex-line's store
1113                    // and nothing reads it while a search prompt is open, so
1114                    // rewriting it here was maintaining a copy for no reader.
1115                    self.preview_search();
1116                }
1117            }
1118            Action::Pending => {}
1119        }
1120        // Widen the dirty region by what this action touched (M1). Content
1121        // mutations that changed the line count run to end-of-document (every
1122        // line below shifted); an in-place edit or a cursor move is local;
1123        // arbitrary commands are conservatively Full. Never narrows.
1124        let lines_after = self.active_line_count();
1125        let cline_after = self.cursor().line;
1126        let d = match action {
1127            // A search repaints every highlight in the viewport, not just the
1128            // line the cursor left — so it must widen to Full. Treating it as a
1129            // cursor move would leave stale highlights on untouched lines.
1130            Action::SearchOpen(_)
1131            | Action::PromptHistory { .. }
1132            | Action::PromptBackspace
1133            | Action::PromptCaret { .. }
1134            | Action::SearchPreviewStep { .. }
1135            | Action::PromptDelete
1136            | Action::PromptDeleteWord
1137            | Action::PromptClearToStart
1138            | Action::SearchRepeat { .. }
1139            | Action::SearchWord { .. }
1140            | Action::ClearSearchHighlight
1141            | Action::SearchSubmitOperated { .. }
1142            // A replayed change can edit anywhere the original could, and a
1143            // match object can be anywhere in the document.
1144            | Action::RepeatLastChange
1145            | Action::TextObject(_)
1146            | Action::ApplyOperatorObject { .. }
1147            // A jump can land anywhere, so the viewport may scroll wholesale.
1148            | Action::JumpBack
1149            | Action::JumpForward => Damage::Full,
1150            Action::InsertChar(_)
1151            | Action::Edit(_)
1152            | Action::Undo
1153            | Action::Redo
1154            | Action::ApplyOperator { .. } => {
1155                if lines_after == lines_before {
1156                    Damage::span(cline_before, cline_after)
1157                } else {
1158                    Damage::Lines {
1159                        from: cline_before.min(cline_after),
1160                        to: u32::MAX,
1161                    }
1162                }
1163            }
1164            Action::Move(_) | Action::ChangeMode(_) => Damage::span(cline_before, cline_after),
1165            Action::Save => Damage::Viewport,
1166            Action::Command { .. } | Action::SubmitCommand => Damage::Full,
1167            Action::Quit | Action::Operator(_) | Action::Pending => Damage::None,
1168        };
1169        self.damage = self.damage.join(d);
1170        // Remember this change for `.`.
1171        //
1172        // Recorded from an OBSERVED MUTATION, not from the action's variant.
1173        // `text_effect()` is the wrong predicate here even though it looks
1174        // like the right one: it exists to decide cache invalidation, where
1175        // OVER-reporting is the safe direction, and the dot register needs the
1176        // opposite bias. Leaning on it meant `last_change` was set by actions
1177        // that changed no text at all, with two measured consequences:
1178        //
1179        //   `iZ<Esc>` then `/a<CR>` then `.`  — did nothing; the register held
1180        //       `SubmitCommand`, whose replay reads an already-cleared
1181        //       minibuffer.
1182        //   `iZ<Esc>` then `/q<Esc>` then `.` — TYPED `q` INTO THE BUFFER. An
1183        //       abandoned prompt left the register holding `InsertChar('q')`,
1184        //       and `.` in Normal mode routes that to the text. A corrupting
1185        //       register, not merely a lost one.
1186        //
1187        // Comparing the buffer's `TextRev` across the action answers the only
1188        // question that matters — did this actually change the text — and gets
1189        // the failed-operator case (`dgn` with no pattern) right for free.
1190        if self.recording_insert {
1191            match action {
1192                Action::InsertChar(c) => {
1193                    if let Some(lc) = self.last_change.as_mut() {
1194                        lc.inserted.push(*c);
1195                    }
1196                }
1197                // Leaving Insert ends the session; the change is now whole.
1198                Action::ChangeMode(m) if *m != Mode::Insert => self.recording_insert = false,
1199                _ => {}
1200            }
1201        } else if self.text_rev() != rev_before
1202            && !matches!(
1203                action,
1204                Action::RepeatLastChange | Action::Undo | Action::Redo
1205            )
1206        {
1207            self.last_change = Some(LastChange {
1208                action: action.clone(),
1209                count: 1,
1210                inserted: String::new(),
1211            });
1212            self.recording_insert = self.modal.mode() == Mode::Insert;
1213        }
1214
1215        // The search is over the moment you move on or edit — clear the
1216        // highlight rather than leaving the buffer as confetti until an
1217        // explicit `:noh`, which is the remap nearly every vimrc carries.
1218        // Clearing suppresses without forgetting, so `n` still works.
1219        if action.highlight_effect() == HighlightEffect::Clear {
1220            self.search.clear_highlight();
1221        }
1222        // Text changed ⇒ every match offset cached against the old text is
1223        // wrong. `SearchState::refresh` existed for exactly this and had ZERO
1224        // callers, so inserting four characters left both renderers painting
1225        // the highlight four columns off.
1226        //
1227        // Gated on the typed classifier rather than on `bump_gen` (which fires
1228        // for pure cursor moves too): re-scanning the document on every `j`
1229        // would be a per-keystroke full pass for no reason.
1230        if action.text_effect() == TextEffect::Mutates && self.search.pattern().is_some() {
1231            let text = self.active_text();
1232            self.search.refresh(&text);
1233            // NO manual invalidation of `search_at` here, deliberately. It is
1234            // `Anchored` to the text revision, so an ordinal computed against
1235            // the old text now reads as `None` on its own. This is the line
1236            // that used to have to be remembered.
1237        }
1238        // An action reached the executor ⇒ visible state may have changed.
1239        // Advance the refresh generation so the renderer repaints (and
1240        // re-highlights) exactly once. A gated-out key never reaches here, so
1241        // a key-repeat storm does not spin the renderer.
1242        self.bump_gen();
1243    }
1244
1245    /// Resolve a [`Motion`] from `from` to its target [`Position`] against the
1246    /// active buffer — **pure**: no cursor mutation, no side effects. This is
1247    /// the single motion-resolution source of truth that both [`apply_motion`]
1248    /// (move the cursor *to* the target) and [`apply_operator`] (use the target
1249    /// as the *other end* of an operated range) stand on. `None` only if there
1250    /// is no active buffer.
1251    ///
1252    /// [`apply_motion`]: Self::apply_motion
1253    /// [`apply_operator`]: Self::apply_operator
1254    fn resolve_motion(&self, from: Position, motion: Motion) -> Option<Position> {
1255        let buf = self.buffers.get(self.active)?;
1256        let pos = from;
1257        Some(match motion {
1258            // Search-as-motion: what makes `dn` / `d/foo<CR>` work. Resolved
1259            // against the committed match list, so it is `None` (motion fails,
1260            // operator aborts, buffer untouched) when nothing is committed —
1261            // never a silent move to 0, which would delete to the file start.
1262            Motion::SearchNext | Motion::SearchPrev => {
1263                let at = buf.position_to_char(pos).ok()?;
1264                let step = self
1265                    .search
1266                    .repeat(at, matches!(motion, Motion::SearchPrev))?;
1267                buf.char_to_position(step.target.start)
1268            }
1269            Motion::Left => Position::new(pos.line, pos.column.saturating_sub(1)),
1270            Motion::Right => Position::new(pos.line, pos.column.saturating_add(1)),
1271            Motion::Up => Position::new(pos.line.saturating_sub(1), pos.column),
1272            Motion::Down => Position::new(pos.line.saturating_add(1), pos.column),
1273            Motion::LineStart => Position::new(pos.line, 0),
1274            Motion::LineEnd => Position::new(pos.line, buf.line_len_chars(pos.line)),
1275            Motion::LineFirstNonBlank => first_non_blank(buf, pos.line),
1276            Motion::DocStart => Position::ZERO,
1277            Motion::DocEnd => Position::new(
1278                buf.line_count().saturating_sub(1),
1279                buf.line_len_chars(buf.line_count().saturating_sub(1)),
1280            ),
1281            Motion::WordStartNext | Motion::WordEndNext => word_next(buf, pos),
1282            Motion::WordStartPrev => word_prev(buf, pos),
1283            Motion::PageDown | Motion::HalfPageDown => {
1284                Position::new(pos.line.saturating_add(10), pos.column)
1285            }
1286            Motion::PageUp | Motion::HalfPageUp => {
1287                Position::new(pos.line.saturating_sub(10), pos.column)
1288            }
1289            Motion::GotoLine(n) => Position::new(n.saturating_sub(1), 0),
1290            // Structural Lisp motions — stubs for phase 1.B; full paredit
1291            // semantics land when caixa-ast is wired to the active buffer.
1292            Motion::ForwardSexp
1293            | Motion::BackwardSexp
1294            | Motion::UpList
1295            | Motion::DownList
1296            | Motion::BeginningOfDefun
1297            | Motion::EndOfDefun
1298            | Motion::BeginningOfSexp
1299            | Motion::EndOfSexp => pos,
1300        })
1301    }
1302
1303    fn apply_motion(&mut self, motion: Motion) {
1304        // A bare search motion is a FAR JUMP and it REPORTS — it records into
1305        // the jumplist, prints vim's "hit BOTTOM" on a wrap, and says E486
1306        // when nothing matches. `resolve_motion` can do none of that: it is
1307        // deliberately pure because the OPERATOR path calls it to find a range
1308        // without moving the cursor. So `n` routes to the one executor that
1309        // owns those side effects, and `Action::SearchRepeat` routes to the
1310        // same place — one code path, two spellings.
1311        if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
1312            self.jump_search(matches!(motion, Motion::SearchPrev));
1313            return;
1314        }
1315        let Some(pos) = self.resolve_motion(self.cursor(), motion) else {
1316            return;
1317        };
1318        // The single cursor-mutation path clamps to the buffer and scrolls
1319        // the viewport to contain the cursor on both axes.
1320        self.set_cursor(pos);
1321    }
1322
1323    /// Apply an operator over a motion — the vim `{operator}{motion}` verbs
1324    /// (`dw` delete-word, `c$` change-to-line-end, `y0` yank-to-line-start).
1325    /// Composition is explicit: the motion resolves a target via
1326    /// [`resolve_motion`](Self::resolve_motion); the operator acts over the
1327    /// `[cursor, target)` range. Register-leaving operators
1328    /// ([`Operator::leaves_register`]) capture the text first.
1329    fn apply_operator(&mut self, op: Operator, motion: Motion) {
1330        let from = self.cursor();
1331        let Some(to) = self.resolve_motion(from, motion) else {
1332            // A motion that cannot resolve aborts the operator with the buffer
1333            // untouched. A search motion says WHY — `dn` with no pattern armed
1334            // is otherwise indistinguishable from a dropped keystroke, which
1335            // is the same complaint that motivated E486 on the bare path.
1336            if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
1337                if self.search.pattern().is_none() {
1338                    self.messages
1339                        .push("E35: No previous regular expression".to_string());
1340                } else {
1341                    self.report_pattern_not_found();
1342                }
1343            }
1344            return;
1345        };
1346        self.apply_operator_to(op, to);
1347    }
1348
1349    /// Apply `op` over `[cursor, to)`.
1350    ///
1351    /// Split out of [`Self::apply_operator`] so the operated-search path can
1352    /// reach the same range machinery with a target it resolved itself — the
1353    /// alternative was a second copy of the delete/yank/register logic, which
1354    /// is how the two would drift.
1355    fn apply_operator_to(&mut self, op: Operator, to: Position) {
1356        let from = self.cursor();
1357        self.apply_operator_over(
1358            op,
1359            Range {
1360                start: from,
1361                end: to,
1362            },
1363        );
1364    }
1365
1366    /// Apply `op` over an explicit range.
1367    ///
1368    /// The object path needs this: `gn`'s extent need not begin at the cursor,
1369    /// so it cannot go through the `[cursor, target)` shape the motion path
1370    /// uses. One implementation of the delete/yank/register logic, reached two
1371    /// ways.
1372    fn apply_operator_over(&mut self, op: Operator, range: Range) {
1373        let range = range.normalized();
1374        if range.is_empty() {
1375            return;
1376        }
1377        // Capture the operated text (for the register) before mutating.
1378        let text = self
1379            .buffers
1380            .get(self.active)
1381            .and_then(|buf| buf.slice(range).ok());
1382        if op.leaves_register() {
1383            if let Some(t) = &text {
1384                self.register = Some(t.clone());
1385            }
1386        }
1387        match op {
1388            // Delete + Change remove the range; Change then enters Insert so
1389            // the operator pairs with immediate typing (`ciw`, `c$`).
1390            Operator::Delete | Operator::Change => {
1391                if let Some(buf) = self.buffers.get_mut(self.active) {
1392                    let _ = buf.apply(&Edit::delete(range));
1393                }
1394                self.set_cursor(range.start);
1395                if op == Operator::Change {
1396                    self.modal.enter(Mode::Insert);
1397                }
1398            }
1399            // Yank copies to the register without mutating the buffer; vim
1400            // leaves the cursor at the range start.
1401            Operator::Yank => {
1402                self.set_cursor(range.start);
1403            }
1404            // Indent/Format/structural operators are not yet wired — named,
1405            // not faked (no buffer mutation, register already captured for the
1406            // register-leaving ones above).
1407            _ => {
1408                self.messages
1409                    .push("operator not yet implemented".to_owned());
1410            }
1411        }
1412    }
1413
1414    /// The text last yanked or deleted into the unnamed register, if any.
1415    /// The future `p`/`P` paste reads this.
1416    #[must_use]
1417    pub fn register(&self) -> Option<&str> {
1418        self.register.as_deref()
1419    }
1420
1421    fn insert_char(&mut self, c: char) {
1422        if self.modal.mode() == Mode::Command {
1423            // A search prompt and an ex-command share Command mode (vim's
1424            // cmdline). `search.is_prompting()` is the typed discriminator —
1425            // it can only be true when `/` or `?` actually opened a prompt.
1426            if self.search.is_prompting() {
1427                // The search prompt is the SOLE store while it is open.
1428                //
1429                // This used to also `push_minibuffer(c)`, and the two stores
1430                // insert differently — `search.push` at the caret, the
1431                // minibuffer always at the end — so `/fo<Left>X` left them
1432                // reading `fXo` and `foX`. That was one of FIVE desync paths;
1433                // the caret moves, forward-delete, delete-word and
1434                // clear-to-start never touched the shadow at all.
1435                //
1436                // Deleting the write costs nothing because `status_model`
1437                // already selects the minibuffer only on the `prompt == None`
1438                // branch — the shadow is the EX-LINE's store, and while a
1439                // search prompt is open nothing reads it.
1440                self.search.push(c);
1441                self.preview_search();
1442            } else {
1443                self.modal.push_minibuffer(c);
1444            }
1445            return;
1446        }
1447        let cursor = self.cursor();
1448        let Some(buf) = self.buffers.get_mut(self.active) else {
1449            return;
1450        };
1451        let edit = Edit::insert(cursor, c.to_string());
1452        if buf.apply(&edit).is_ok() {
1453            let next = if c == '\n' {
1454                Position::new(cursor.line.saturating_add(1), 0)
1455            } else {
1456                cursor.shift_right(1)
1457            };
1458            // Route through the single cursor-mutation path so the viewport
1459            // follows the cursor (both axes) and the cursor stays clamped.
1460            self.set_cursor(next);
1461        }
1462    }
1463
1464    /// Backspace inside a prompt. Keeps the search buffer and the displayed
1465    /// minibuffer in lockstep — if only one shrank, the pattern submitted
1466    /// would differ from the text on screen.
1467    fn prompt_backspace(&mut self) -> bool {
1468        if self.modal.mode() != Mode::Command {
1469            return false;
1470        }
1471        if self.search.is_prompting() {
1472            // Backspacing past the `/` closes the prompt, as vim does. No
1473            // `pop_minibuffer` here for the same reason as `insert_char`: the
1474            // shadow is the ex-line's, and popping its TAIL when the caret is
1475            // mid-pattern was another desync path.
1476            if self.search.backspace() {
1477                self.modal.clear_minibuffer();
1478                self.modal.enter(Mode::Normal);
1479            }
1480            // Never `pop_minibuffer` on the search path: it pops the TAIL,
1481            // while `search.backspace()` removes the char before the CARET.
1482            return true;
1483        }
1484        self.modal.pop_minibuffer();
1485        true
1486    }
1487
1488    fn apply_edit(&mut self, _edit: &Edit) {
1489        // Phase 2: actually apply arbitrary edits from the keymap. For now
1490        // the only keymap-originated edits are InsertChar (handled above)
1491        // and the Backspace sentinel that escriba-keymap emits.
1492    }
1493
1494    fn submit_command(&mut self) {
1495        // Read the command line BEFORE leaving Command mode — the minibuffer
1496        // exists only in the `Command` variant, so the escape must come
1497        // after the capture.
1498        let line = self.modal.minibuffer().to_string();
1499        self.modal.escape();
1500        let (name, args) = parse_command_line(&line);
1501        if name.is_empty() {
1502            return;
1503        }
1504        self.run_command(&name, &args);
1505    }
1506
1507    fn run_command(&mut self, name: &str, args: &[String]) {
1508        // `:noh` is handled here rather than in the command registry because
1509        // it mutates SearchState, which EditContext does not expose (and
1510        // should not — the registry's contract is buffers + modal state).
1511        // Without it there is no way to turn highlights off, which makes
1512        // hlsearch actively unpleasant rather than useful.
1513        if matches!(name, "noh" | "nohl" | "nohlsearch") {
1514            self.search.clear_highlight();
1515            return;
1516        }
1517        // Lazy-activation seam (lazy.nvim `cmd =` model): a user plugin
1518        // gated on `Command: <name>` has its entry applied the first time
1519        // that command runs, BEFORE dispatch — so the activated plugin
1520        // can register the very command being invoked and it resolves on
1521        // this same call.
1522        if self.plugin_host.pending() > 0 {
1523            let pending = self.plugin_host.pending_for_command(name);
1524            for src in pending {
1525                self.apply_plugin_entry(&src);
1526            }
1527        }
1528        let active = Some(self.active);
1529        let mut quit = false;
1530        {
1531            let mut ctx = EditContext {
1532                buffers: &mut self.buffers,
1533                active,
1534                state: &mut self.modal,
1535                quit_requested: &mut quit,
1536            };
1537            let _ = self.commands.run(name, &mut ctx, args);
1538        }
1539        // The command's typed quit signal — no string sentinel, no
1540        // mode-specific buffer to clear.
1541        if quit {
1542            self.quit_requested = true;
1543        }
1544    }
1545
1546    // ── tatara-lisp runtime bridge (imperative programmability tier) ──
1547
1548    /// Capture a read snapshot of the editor for the tatara-lisp host.
1549    /// Lisp reads (`cursor-line`, `current-line`, …) answer from this.
1550    #[must_use]
1551    pub fn snapshot(&self) -> EditorSnapshot {
1552        let current_line = self
1553            .buffers
1554            .get(self.active)
1555            .and_then(|b| b.line(self.cursor().line))
1556            .map(|s| s.trim_end_matches('\n').to_string())
1557            .unwrap_or_default();
1558        let buffer_name = self
1559            .buffers
1560            .get(self.active)
1561            .and_then(|b| b.path.as_ref())
1562            .map(|p| p.display().to_string())
1563            .unwrap_or_else(|| "[scratch]".to_string());
1564        EditorSnapshot {
1565            cursor_line: i64::from(self.cursor().line),
1566            cursor_column: i64::from(self.cursor().column),
1567            current_line,
1568            mode: self.modal.mode().as_str().to_string(),
1569            buffer_name,
1570        }
1571    }
1572
1573    /// Evaluate tatara-lisp `src` against this editor: capture a
1574    /// snapshot, run it in the embedded VM, then apply the typed effects
1575    /// the program emitted. This is the imperative programmability tier
1576    /// — live Lisp that reads state and drives the editor through the
1577    /// sandboxed effect boundary.
1578    ///
1579    /// **Snapshot semantics:** the read snapshot is captured ONCE before
1580    /// eval, and effects are applied AFTER the program returns. So within
1581    /// a single `run_lisp` call a program cannot observe its own writes —
1582    /// `(insert "x") (cursor-column)` reads the pre-insert column. This
1583    /// snapshot-isolation is deliberate (it's what makes the effect
1584    /// boundary a clean sandbox seam); a program that must read its own
1585    /// effects splits the work across calls. The VM is cached
1586    /// ([`Self::lisp_vm`]) so the stdlib is installed once and top-level
1587    /// `define`s persist across calls (REPL-like).
1588    pub fn run_lisp(&mut self, src: &str) -> Result<(), VmError> {
1589        let mut host = EscribaHost::with_snapshot(self.snapshot());
1590        let vm = self.lisp_vm.get_or_insert_with(EscribaVm::new);
1591        vm.eval(src, &mut host)?;
1592        let effects = host.take_effects();
1593        self.apply_host_effects(effects);
1594        Ok(())
1595    }
1596
1597    /// Apply tatara-lisp [`HostEffect`]s to live editor state. The
1598    /// single seam where Lisp-requested mutations land — extend here +
1599    /// in `escriba-vm` to add a capability.
1600    pub fn apply_host_effects(&mut self, effects: Vec<HostEffect>) {
1601        for eff in effects {
1602            match eff {
1603                HostEffect::Message(m) => self.messages.push(m),
1604                HostEffect::RunCommand { name, args } => self.run_command(&name, &args),
1605                HostEffect::SetOption { name, value } => {
1606                    self.options.insert(name, value);
1607                }
1608                HostEffect::InsertText(text) => self.insert_text(&text),
1609            }
1610        }
1611    }
1612
1613    /// Insert a (possibly multi-line) string at the cursor and advance
1614    /// the cursor past it. Used by the `(insert …)` effect.
1615    fn insert_text(&mut self, text: &str) {
1616        if text.is_empty() {
1617            return;
1618        }
1619        let cursor = self.cursor();
1620        let Some(buf) = self.buffers.get_mut(self.active) else {
1621            return;
1622        };
1623        let edit = Edit::insert(cursor, text.to_string());
1624        if buf.apply(&edit).is_ok() {
1625            let next = if let Some(nl) = text.rfind('\n') {
1626                let added_lines = u32::try_from(text.matches('\n').count()).unwrap_or(0);
1627                let last_line_len = u32::try_from(text[nl + 1..].chars().count()).unwrap_or(0);
1628                Position::new(cursor.line + added_lines, last_line_len)
1629            } else {
1630                let n = u32::try_from(text.chars().count()).unwrap_or(0);
1631                cursor.shift_right(n)
1632            };
1633            // Route through the single cursor-mutation path so the viewport
1634            // follows the cursor (both axes) and the cursor stays clamped.
1635            self.set_cursor(next);
1636        }
1637    }
1638}
1639
1640fn first_non_blank(buf: &escriba_buffer::Buffer, line: u32) -> Position {
1641    let Some(text) = buf.line(line) else {
1642        return Position::new(line, 0);
1643    };
1644    let col = text
1645        .chars()
1646        .take_while(|c| c.is_whitespace() && *c != '\n')
1647        .count();
1648    Position::new(line, u32::try_from(col).unwrap_or(0))
1649}
1650
1651fn word_next(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
1652    let Some(text) = buf.line(pos.line) else {
1653        return pos;
1654    };
1655    let chars: Vec<char> = text.chars().collect();
1656    let start = pos.column as usize;
1657    let mut i = start;
1658    while i < chars.len() && !chars[i].is_whitespace() {
1659        i += 1;
1660    }
1661    while i < chars.len() && chars[i].is_whitespace() {
1662        i += 1;
1663    }
1664    if i >= chars.len() {
1665        // No more words on this line — jump to next line.
1666        if pos.line + 1 < buf.line_count() {
1667            return Position::new(pos.line + 1, 0);
1668        }
1669    }
1670    Position::new(pos.line, u32::try_from(i).unwrap_or(pos.column))
1671}
1672
1673fn word_prev(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
1674    let Some(text) = buf.line(pos.line) else {
1675        return pos;
1676    };
1677    let chars: Vec<char> = text.chars().collect();
1678    let mut i = (pos.column as usize).min(chars.len());
1679    while i > 0 && chars[i - 1].is_whitespace() {
1680        i -= 1;
1681    }
1682    while i > 0 && !chars[i - 1].is_whitespace() {
1683        i -= 1;
1684    }
1685    Position::new(pos.line, u32::try_from(i).unwrap_or(0))
1686}
1687
1688fn parse_command_line(line: &str) -> (String, Vec<String>) {
1689    let mut parts = line.split_whitespace();
1690    let Some(first) = parts.next() else {
1691        return (String::new(), Vec::new());
1692    };
1693    let head = first.strip_prefix(':').unwrap_or(first);
1694    let name = match head {
1695        "w" => "save",
1696        "q" => "quit",
1697        "u" => "undo",
1698        other => other,
1699    };
1700    (name.to_string(), parts.map(str::to_string).collect())
1701}
1702
1703#[cfg(test)]
1704mod tests {
1705    use super::*;
1706    use madori::event::{KeyCode, KeyEvent, Modifiers};
1707
1708    // ── search wiring (escriba-search integration) ────────────────────
1709    //
1710    // The engine is proven in escriba-search's own 61 tests. These prove the
1711    // WIRING: that keys reach it, that the cursor lands where it says, and
1712    // that a search prompt and an ex-command can share Command mode without
1713    // being confused for one another.
1714
1715    fn type_search(st: &mut EditorState, dir: SearchDirection, pat: &str) {
1716        st.apply(&Action::SearchOpen(dir));
1717        for c in pat.chars() {
1718            st.apply(&Action::InsertChar(c));
1719        }
1720        st.apply(&Action::SubmitCommand);
1721    }
1722
1723    #[test]
1724    fn slash_search_moves_the_cursor_to_the_match() {
1725        let mut st = new_state_with("alpha\nbravo\ncharlie\n");
1726        type_search(&mut st, SearchDirection::Forward, "charlie");
1727        assert_eq!(st.cursor().line, 2, "cursor lands on the matching line");
1728        assert_eq!(st.modal.mode(), Mode::Normal, "prompt closes on submit");
1729        assert_eq!(st.search.matches().len(), 1);
1730    }
1731
1732    #[test]
1733    fn n_and_N_walk_matches_in_both_directions() {
1734        let mut st = new_state_with("foo\nbar\nfoo\nbaz\nfoo\n");
1735        type_search(&mut st, SearchDirection::Forward, "foo");
1736        let first = st.cursor().line;
1737        st.apply(&Action::SearchRepeat { reverse: false });
1738        let second = st.cursor().line;
1739        assert!(second > first, "n advances ({first} -> {second})");
1740        st.apply(&Action::SearchRepeat { reverse: true });
1741        assert_eq!(st.cursor().line, first, "N comes back");
1742    }
1743
1744    #[test]
1745    fn star_searches_the_word_under_the_cursor() {
1746        let mut st = new_state_with("needle\nhaystack\nneedle\n");
1747        st.apply(&Action::SearchWord { reverse: false });
1748        assert_eq!(st.search.pattern().unwrap().raw(), r"\bneedle\b");
1749        assert_eq!(st.cursor().line, 2, "jumps to the other occurrence");
1750    }
1751
1752    #[test]
1753    fn escape_abandons_the_prompt_and_keeps_the_previous_search() {
1754        let mut st = new_state_with("foo\nbar\nfoo\n");
1755        type_search(&mut st, SearchDirection::Forward, "foo");
1756        let matches_before = st.search.matches().len();
1757
1758        st.apply(&Action::SearchOpen(SearchDirection::Forward));
1759        st.apply(&Action::InsertChar('z'));
1760        st.apply(&Action::ChangeMode(Mode::Normal));
1761
1762        assert!(!st.search.is_prompting(), "prompt gone");
1763        assert_eq!(
1764            st.search.pattern().unwrap().raw(),
1765            "foo",
1766            "old pattern survives"
1767        );
1768        assert_eq!(
1769            st.search.matches().len(),
1770            matches_before,
1771            "old highlights survive"
1772        );
1773    }
1774
1775    #[test]
1776    fn a_search_prompt_and_an_ex_command_are_not_confused() {
1777        let mut st = new_state_with("foo\n");
1778        // No `/` pressed: Command mode belongs to the ex-command line.
1779        st.apply(&Action::ChangeMode(Mode::Command));
1780        assert!(!st.search.is_prompting(), "`:` must not open a search");
1781        st.apply(&Action::InsertChar('w'));
1782        assert!(
1783            st.search.prompt().is_none(),
1784            "typed char went to the ex line"
1785        );
1786    }
1787
1788    #[test]
1789    fn a_missing_pattern_reports_instead_of_failing_silently() {
1790        let mut st = new_state_with("alpha\nbravo\n");
1791        type_search(&mut st, SearchDirection::Forward, "zzz");
1792        assert!(
1793            st.messages.iter().any(|m| m.contains("E486")),
1794            "must report not-found, got {:?}",
1795            st.messages
1796        );
1797    }
1798
1799    #[test]
1800    fn n_without_any_search_reports_rather_than_moving() {
1801        let mut st = new_state_with("alpha\nbravo\n");
1802        let before = st.cursor();
1803        st.apply(&Action::SearchRepeat { reverse: false });
1804        assert_eq!(st.cursor(), before, "cursor must not move");
1805        assert!(
1806            st.messages.iter().any(|m| m.contains("E35")),
1807            "got {:?}",
1808            st.messages
1809        );
1810    }
1811
1812    #[test]
1813    fn search_as_a_motion_composes_with_an_operator() {
1814        // The point of Motion::SearchNext: `d` + search deletes to the match.
1815        let mut st = new_state_with("alpha bravo charlie\n");
1816        type_search(&mut st, SearchDirection::Forward, "charlie");
1817        st.set_cursor(Position::new(0, 0));
1818        let target = st.resolve_motion(Position::new(0, 0), Motion::SearchNext);
1819        assert!(target.is_some(), "search must resolve as a motion");
1820        assert_eq!(target.unwrap().column, 12, "at `charlie`");
1821    }
1822
1823    #[test]
1824    fn search_motion_without_a_pattern_fails_the_motion_instead_of_moving_to_zero() {
1825        // A silent fallback to offset 0 would make `d` + search delete to the
1826        // start of the file — the worst possible failure for an operator.
1827        let st = new_state_with("alpha bravo\n");
1828        assert!(
1829            st.resolve_motion(Position::new(0, 5), Motion::SearchNext)
1830                .is_none()
1831        );
1832    }
1833
1834    #[test]
1835    fn clear_highlight_keeps_the_pattern_usable() {
1836        let mut st = new_state_with("foo\nbar\nfoo\n");
1837        type_search(&mut st, SearchDirection::Forward, "foo");
1838        st.apply(&Action::ClearSearchHighlight);
1839        assert!(st.search.highlights().is_empty(), "nothing lit");
1840        st.apply(&Action::SearchRepeat { reverse: false });
1841        assert!(st.search.pattern().is_some(), "but n still works");
1842    }
1843
1844    #[test]
1845    fn typing_previews_incrementally_before_commit() {
1846        let mut st = new_state_with("alpha\nbravo\ncharlie\n");
1847        st.apply(&Action::SearchOpen(SearchDirection::Forward));
1848        for c in "charlie".chars() {
1849            st.apply(&Action::InsertChar(c));
1850        }
1851        // incsearch: the cursor has already moved, with nothing committed.
1852        assert_eq!(st.cursor().line, 2, "preview moved the cursor");
1853        assert!(st.search.pattern().is_none(), "but nothing is committed");
1854    }
1855
1856    #[test]
1857    fn backspace_corrects_the_prompt_and_reruns_the_preview() {
1858        let mut st = new_state_with("alpha\nbravo\n");
1859        st.apply(&Action::SearchOpen(SearchDirection::Forward));
1860        for c in "bravox".chars() {
1861            st.apply(&Action::InsertChar(c));
1862        }
1863        assert_eq!(st.search.prompt().unwrap().text, "bravox");
1864        st.apply(&Action::PromptBackspace);
1865        assert_eq!(st.search.prompt().unwrap().text, "bravo", "typo corrected");
1866        assert_eq!(
1867            st.status_model().prompt_text,
1868            "bravo",
1869            "the model reads the PROMPT — the minibuffer is the ex-line's store",
1870        );
1871        assert_eq!(st.cursor().line, 1, "preview re-ran and found it");
1872    }
1873
1874    #[test]
1875    fn backspacing_past_the_slash_closes_the_prompt() {
1876        let mut st = new_state_with("alpha\n");
1877        st.apply(&Action::SearchOpen(SearchDirection::Forward));
1878        st.apply(&Action::InsertChar('a'));
1879        st.apply(&Action::PromptBackspace);
1880        st.apply(&Action::PromptBackspace);
1881        assert!(!st.search.is_prompting(), "prompt closed");
1882        assert_eq!(st.modal.mode(), Mode::Normal);
1883    }
1884
1885    #[test]
1886    fn noh_clears_highlights_and_keeps_the_pattern() {
1887        let mut st = new_state_with("foo\nbar\nfoo\n");
1888        type_search(&mut st, SearchDirection::Forward, "foo");
1889        assert!(!st.search.highlights().is_empty());
1890        st.run_command("noh", &[]);
1891        assert!(st.search.highlights().is_empty(), ":noh turns them off");
1892        assert!(st.search.pattern().is_some(), "but n still works");
1893    }
1894
1895    #[test]
1896    fn noh_accepts_the_vim_aliases() {
1897        for name in ["noh", "nohl", "nohlsearch"] {
1898            let mut st = new_state_with("foo\nfoo\n");
1899            type_search(&mut st, SearchDirection::Forward, "foo");
1900            st.run_command(name, &[]);
1901            assert!(st.search.highlights().is_empty(), "{name} must clear");
1902        }
1903    }
1904
1905    #[test]
1906    fn backspace_on_the_ex_line_does_not_touch_search_state() {
1907        let mut st = new_state_with("foo\n");
1908        st.apply(&Action::ChangeMode(Mode::Command));
1909        st.apply(&Action::InsertChar('w'));
1910        st.apply(&Action::InsertChar('q'));
1911        st.apply(&Action::PromptBackspace);
1912        assert_eq!(st.status_model().prompt_text, "w");
1913        assert!(st.search.prompt().is_none(), "no search was involved");
1914    }
1915
1916    #[test]
1917    fn up_arrow_recalls_the_previous_search() {
1918        let mut st = new_state_with("alpha\nbravo\n");
1919        type_search(&mut st, SearchDirection::Forward, "bravo");
1920        st.apply(&Action::SearchOpen(SearchDirection::Forward));
1921        st.apply(&Action::PromptHistory { back: true });
1922        assert_eq!(st.search.prompt().unwrap().text, "bravo");
1923        assert_eq!(
1924            st.status_model().prompt_text,
1925            "bravo",
1926            "display follows the prompt"
1927        );
1928    }
1929
1930    #[test]
1931    fn arrowing_back_down_restores_the_half_typed_pattern() {
1932        let mut st = new_state_with("alpha\nbravo\n");
1933        type_search(&mut st, SearchDirection::Forward, "bravo");
1934        st.apply(&Action::SearchOpen(SearchDirection::Forward));
1935        st.apply(&Action::InsertChar('a'));
1936        st.apply(&Action::PromptHistory { back: true });
1937        assert_eq!(st.search.prompt().unwrap().text, "bravo");
1938        st.apply(&Action::PromptHistory { back: false });
1939        assert_eq!(
1940            st.search.prompt().unwrap().text,
1941            "a",
1942            "the draft comes back"
1943        );
1944        assert_eq!(st.status_model().prompt_text, "a");
1945    }
1946
1947    #[test]
1948    fn history_arrows_do_nothing_on_the_ex_line() {
1949        let mut st = new_state_with("alpha\n");
1950        st.apply(&Action::ChangeMode(Mode::Command));
1951        st.apply(&Action::InsertChar('w'));
1952        st.apply(&Action::PromptHistory { back: true });
1953        assert_eq!(st.status_model().prompt_text, "w", "ex line untouched");
1954    }
1955
1956    fn new_state_with(text: &str) -> EditorState {
1957        let mut bufs = BufferSet::new();
1958        let id = bufs.scratch(text);
1959        EditorState::new_with_buffer(bufs, id)
1960    }
1961
1962    /// The refresh-seal driver (theory/ESCRIBA.md §Refresh-Seal): an applied
1963    /// action advances `edit_gen` (so the renderer repaints), and merely
1964    /// reading the generation does not. This is what lets `gpu.rs` gate the
1965    /// re-highlight/re-shape on a generation change — an idle frame observes an
1966    /// unchanged generation and reuses its cached buffer.
1967    #[test]
1968    fn edit_gen_advances_on_applied_action_not_on_read() {
1969        let mut s = new_state_with("hello\nworld\n");
1970        let g0 = s.edit_gen();
1971        s.apply(&Action::InsertChar('X'));
1972        assert_ne!(
1973            s.edit_gen(),
1974            g0,
1975            "an applied action must advance the refresh generation",
1976        );
1977        // Reading the generation is not a mutation — idle frames stay put.
1978        let g1 = s.edit_gen();
1979        assert_eq!(s.edit_gen(), g1, "reading edit_gen must not advance it");
1980    }
1981
1982    /// The M1 refresh node (theory/ESCRIBA.md §X): a mutation widens the typed
1983    /// `Damage` to cover exactly what changed — local for an in-place edit,
1984    /// to-end-of-document when the line count shifts — and the renderer drains
1985    /// it per frame. `Damage ⊇ changed` by construction; it never narrows.
1986    #[test]
1987    fn damage_tracks_edit_scope_and_drains() {
1988        let mut s = new_state_with("hello\nworld\n");
1989        assert!(s.damage().is_none(), "a fresh state has no damage");
1990
1991        s.apply(&Action::InsertChar('X')); // in-place edit on line 0
1992        assert_eq!(
1993            s.damage(),
1994            Damage::Lines { from: 0, to: 0 },
1995            "a local edit damages just its line",
1996        );
1997
1998        let drained = s.take_damage();
1999        assert_eq!(drained, Damage::Lines { from: 0, to: 0 });
2000        assert!(s.damage().is_none(), "take_damage drains to None");
2001
2002        s.apply(&Action::InsertChar('\n')); // splits line 0 → line count grows
2003        assert_eq!(
2004            s.damage(),
2005            Damage::Lines {
2006                from: 0,
2007                to: u32::MAX,
2008            },
2009            "a line-count change damages to end-of-document",
2010        );
2011    }
2012
2013    /// A state whose active window is a deliberately tiny viewport
2014    /// (`visible_lines` × `visible_columns`) so the scroll-to-contain
2015    /// invariant is exercised on small inputs.
2016    fn new_state_small_viewport(text: &str, vis_lines: u32, vis_cols: u32) -> EditorState {
2017        let mut s = new_state_with(text);
2018        for w in &mut s.layout.windows {
2019            w.viewport.visible_lines = vis_lines;
2020            w.viewport.visible_columns = vis_cols;
2021        }
2022        s
2023    }
2024
2025    /// The core regression invariant: the active window's viewport CONTAINS
2026    /// the cursor on BOTH axes. This is the operator's exact complaint —
2027    /// "typing past the bottom (or right) leaves the cursor off-screen" —
2028    /// made into a checkable property.
2029    fn assert_cursor_in_viewport(s: &EditorState, ctx: &str) {
2030        let w = s.layout.active_window().expect("active window");
2031        let v = w.viewport;
2032        let c = s.cursor();
2033        assert!(
2034            v.top_line <= c.line && c.line < v.top_line + v.visible_lines,
2035            "[{ctx}] cursor line {} not in vertical window [{}, {}); viewport={v:?}",
2036            c.line,
2037            v.top_line,
2038            v.top_line + v.visible_lines,
2039        );
2040        assert!(
2041            v.left_column <= c.column && c.column < v.left_column + v.visible_columns,
2042            "[{ctx}] cursor column {} not in horizontal window [{}, {}); viewport={v:?}",
2043            c.column,
2044            v.left_column,
2045            v.left_column + v.visible_columns,
2046        );
2047    }
2048
2049    fn press(kc: KeyCode) -> AppEvent {
2050        AppEvent::Key(KeyEvent {
2051            key: kc,
2052            pressed: true,
2053            modifiers: Modifiers::default(),
2054            text: None,
2055        })
2056    }
2057
2058    // ── operator-over-motion (the `dw`/`c$`/`y0` verbs) ──────────────
2059
2060    fn line0_len(s: &EditorState) -> u32 {
2061        s.buffers.get(s.active).unwrap().line_len_chars(0)
2062    }
2063
2064    #[test]
2065    fn delete_to_line_end_clears_line_and_fills_register() {
2066        let mut s = new_state_with("hello world");
2067        s.apply(&Action::ApplyOperator {
2068            op: Operator::Delete,
2069            motion: Motion::LineEnd,
2070        });
2071        assert_eq!(line0_len(&s), 0, "d$ deletes to end of line");
2072        assert_eq!(
2073            s.register(),
2074            Some("hello world"),
2075            "delete fills the register"
2076        );
2077        assert_eq!(
2078            s.cursor(),
2079            Position::ZERO,
2080            "cursor lands at the range start"
2081        );
2082    }
2083
2084    #[test]
2085    fn delete_over_right_motion_removes_one_char() {
2086        let mut s = new_state_with("abc");
2087        s.apply(&Action::ApplyOperator {
2088            op: Operator::Delete,
2089            motion: Motion::Right,
2090        });
2091        assert_eq!(
2092            s.buffers.get(s.active).unwrap().line(0).as_deref(),
2093            Some("bc")
2094        );
2095        assert_eq!(s.register(), Some("a"));
2096    }
2097
2098    #[test]
2099    fn change_to_line_end_deletes_and_enters_insert() {
2100        let mut s = new_state_with("hello world");
2101        assert_eq!(s.modal.mode(), Mode::Normal);
2102        s.apply(&Action::ApplyOperator {
2103            op: Operator::Change,
2104            motion: Motion::LineEnd,
2105        });
2106        assert_eq!(line0_len(&s), 0, "c$ deletes the range");
2107        assert_eq!(
2108            s.modal.mode(),
2109            Mode::Insert,
2110            "change enters Insert to type the replacement"
2111        );
2112        assert_eq!(
2113            s.register(),
2114            Some("hello world"),
2115            "change fills the register"
2116        );
2117    }
2118
2119    #[test]
2120    fn yank_to_line_end_fills_register_without_mutating() {
2121        let mut s = new_state_with("hello world");
2122        s.apply(&Action::ApplyOperator {
2123            op: Operator::Yank,
2124            motion: Motion::LineEnd,
2125        });
2126        assert_eq!(line0_len(&s), 11, "yank does not mutate the buffer");
2127        assert_eq!(s.register(), Some("hello world"), "yank fills the register");
2128        assert_eq!(s.modal.mode(), Mode::Normal, "yank stays in Normal");
2129    }
2130
2131    #[test]
2132    fn resolve_motion_is_the_shared_target_for_move_and_operator() {
2133        // The encapsulation proof: apply_motion (cursor move) and
2134        // apply_operator (range end) BOTH stand on resolve_motion — so a move
2135        // to LineEnd lands at exactly the position the operator deletes to.
2136        let mut s = new_state_with("hello world");
2137        let target = s.resolve_motion(Position::ZERO, Motion::LineEnd).unwrap();
2138        assert_eq!(target, Position::new(0, 11));
2139        s.apply_motion(Motion::LineEnd);
2140        assert_eq!(
2141            s.cursor(),
2142            target,
2143            "the move path resolves the same target the operator uses"
2144        );
2145    }
2146
2147    #[test]
2148    fn empty_motion_range_is_a_no_op() {
2149        // An operator over a zero-width motion (cursor already at line start)
2150        // mutates nothing and leaves the register untouched.
2151        let mut s = new_state_with("abc");
2152        s.apply(&Action::ApplyOperator {
2153            op: Operator::Delete,
2154            motion: Motion::LineStart,
2155        });
2156        assert_eq!(
2157            s.buffers.get(s.active).unwrap().line(0).as_deref(),
2158            Some("abc")
2159        );
2160        assert_eq!(s.register(), None);
2161    }
2162
2163    #[test]
2164    fn operator_then_motion_composes_through_the_pending_fsm() {
2165        // The full keymap→FSM→engine path: dispatching the `d` operator action
2166        // then a `$` motion composes `d$` via the zenmai operator-pending FSM —
2167        // the operator key alone does nothing until the motion arrives.
2168        let mut s = new_state_with("hello world");
2169        s.apply(&Action::Operator(Operator::Delete));
2170        assert_eq!(line0_len(&s), 11, "the operator key alone mutates nothing");
2171        s.apply(&Action::Move(Motion::LineEnd));
2172        assert_eq!(
2173            line0_len(&s),
2174            0,
2175            "d then $ composes d$ and deletes the line"
2176        );
2177        assert_eq!(s.register(), Some("hello world"));
2178    }
2179
2180    #[test]
2181    fn change_operator_through_fsm_enters_insert() {
2182        let mut s = new_state_with("hello world");
2183        s.apply(&Action::Operator(Operator::Change));
2184        s.apply(&Action::Move(Motion::LineEnd));
2185        assert_eq!(s.modal.mode(), Mode::Insert, "c$ deletes and enters Insert");
2186    }
2187
2188    #[test]
2189    fn lone_motion_after_no_operator_just_moves() {
2190        // Without a preceding operator the motion passes through unchanged.
2191        let mut s = new_state_with("hello world");
2192        s.apply(&Action::Move(Motion::LineEnd));
2193        assert_eq!(s.cursor(), Position::new(0, 11));
2194        assert_eq!(line0_len(&s), 11, "a bare motion never mutates");
2195    }
2196
2197    #[test]
2198    fn counted_operator_deletes_count_times() {
2199        // `3d` + a right-motion = `3dl` = delete 3 chars. The operator's count
2200        // flows through the FSM to the composed motion (the bug fix: previously
2201        // the count repeated the operator key and toggled the FSM).
2202        let mut s = new_state_with("abcdef");
2203        s.apply_counted(&Action::Operator(Operator::Delete), 3);
2204        assert_eq!(line0_len(&s), 6, "the operator key alone mutates nothing");
2205        s.apply(&Action::Move(Motion::Right));
2206        assert_eq!(
2207            s.buffers.get(s.active).unwrap().line(0).as_deref(),
2208            Some("def")
2209        );
2210    }
2211
2212    #[test]
2213    fn operator_and_motion_counts_multiply_end_to_end() {
2214        // `2d3l` = delete 2×3 = 6 chars.
2215        let mut s = new_state_with("abcdefgh");
2216        s.apply_counted(&Action::Operator(Operator::Delete), 2);
2217        s.apply_counted(&Action::Move(Motion::Right), 3);
2218        assert_eq!(
2219            s.buffers.get(s.active).unwrap().line(0).as_deref(),
2220            Some("gh")
2221        );
2222    }
2223
2224    #[test]
2225    fn bare_counted_motion_still_repeats_no_regression() {
2226        // `3j` still moves down 3 lines — the count passes through the FSM
2227        // unchanged when no operator is pending.
2228        let mut s = new_state_with("a\nb\nc\nd\ne");
2229        s.apply_counted(&Action::Move(Motion::Down), 3);
2230        assert_eq!(s.cursor().line, 3, "5j-style counted motion preserved");
2231    }
2232
2233    /// A monotonic clock for the key-repeat gate in tests — each `next()`
2234    /// jumps a full second past the previous, so every press it stamps is
2235    /// well outside the 80ms debounce window and therefore an INTENTIONAL
2236    /// press (never a storm tick). Used by tests that fire the *same*
2237    /// navigation key twice and assert editor logic, not debounce timing.
2238    struct SpacedClock(std::time::Instant);
2239    impl SpacedClock {
2240        fn new() -> Self {
2241            Self(std::time::Instant::now())
2242        }
2243        fn next(&mut self) -> std::time::Instant {
2244            self.0 += std::time::Duration::from_secs(1);
2245            self.0
2246        }
2247    }
2248
2249    #[test]
2250    fn hjkl_moves_cursor() {
2251        let mut s = new_state_with("hello\nworld");
2252        s.tick(&press(KeyCode::Char('l')));
2253        assert_eq!(s.cursor().column, 1);
2254        s.tick(&press(KeyCode::Char('j')));
2255        assert_eq!(s.cursor().line, 1);
2256        s.tick(&press(KeyCode::Char('h')));
2257        assert_eq!(s.cursor().column, 0);
2258    }
2259
2260    #[test]
2261    fn insert_mode_inserts_chars() {
2262        let mut s = new_state_with("");
2263        s.tick(&press(KeyCode::Char('i')));
2264        assert_eq!(s.modal.mode(), Mode::Insert);
2265        s.tick(&press(KeyCode::Char('h')));
2266        s.tick(&press(KeyCode::Char('i')));
2267        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "hi");
2268        assert_eq!(s.cursor().column, 2);
2269    }
2270
2271    #[test]
2272    fn esc_returns_to_normal() {
2273        let mut s = new_state_with("");
2274        s.tick(&press(KeyCode::Char('i')));
2275        s.tick(&press(KeyCode::Escape));
2276        assert_eq!(s.modal.mode(), Mode::Normal);
2277    }
2278
2279    #[test]
2280    fn count_prefix_repeats_motion() {
2281        let mut s = new_state_with("abcdefghij");
2282        s.tick(&press(KeyCode::Char('5')));
2283        s.tick(&press(KeyCode::Char('l')));
2284        assert_eq!(s.cursor().column, 5);
2285    }
2286
2287    #[test]
2288    fn close_event_requests_quit() {
2289        let mut s = new_state_with("");
2290        s.tick(&AppEvent::CloseRequested);
2291        assert!(s.quit_requested);
2292    }
2293
2294    #[test]
2295    fn word_next_jumps_past_whitespace() {
2296        let mut s = new_state_with("foo bar baz");
2297        // Two INTENTIONAL `w` presses, spaced past the key-repeat window so
2298        // the gate passes both (a real user's two taps are ≥80ms apart).
2299        let mut clk = SpacedClock::new();
2300        s.tick_at(&press(KeyCode::Char('w')), clk.next());
2301        assert_eq!(s.cursor().column, 4);
2302        s.tick_at(&press(KeyCode::Char('w')), clk.next());
2303        assert_eq!(s.cursor().column, 8);
2304    }
2305
2306    // ── Multi-key / leader pending-stroke ───────────────────────────
2307
2308    #[test]
2309    fn leader_sequence_holds_then_resolves() {
2310        let mut s = new_state_with("a\nbb\nccc");
2311        s.keymap.bind_sequence(
2312            Mode::Normal,
2313            vec![Key::Char(','), Key::Char('g')],
2314            Action::Move(Motion::DocEnd),
2315            "doc end",
2316        );
2317        // `,` begins the sequence — held pending, nothing applied yet.
2318        s.on_key(&Key::Char(','));
2319        assert_eq!(s.pending_keys, vec![Key::Char(',')]);
2320        assert_eq!(s.cursor(), Position::ZERO);
2321        // `g` completes `<leader>g` → DocEnd; pending clears.
2322        s.on_key(&Key::Char('g'));
2323        assert!(s.pending_keys.is_empty());
2324        assert_eq!(s.cursor().line, 2);
2325    }
2326
2327    #[test]
2328    fn two_key_gg_jumps_doc_start() {
2329        let mut s = new_state_with("a\nbb\nccc");
2330        s.keymap.bind_sequence(
2331            Mode::Normal,
2332            vec![Key::Char('g'), Key::Char('g')],
2333            Action::Move(Motion::DocStart),
2334            "doc start",
2335        );
2336        let mut clk = SpacedClock::new();
2337        s.tick_at(&press(KeyCode::Char('j')), clk.next());
2338        s.tick_at(&press(KeyCode::Char('j')), clk.next());
2339        assert_eq!(s.cursor().line, 2);
2340        s.on_key(&Key::Char('g')); // pending
2341        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2342        s.on_key(&Key::Char('g')); // resolve
2343        assert_eq!(s.cursor(), Position::ZERO);
2344    }
2345
2346    #[test]
2347    fn broken_sequence_aborts_and_clears_pending() {
2348        let mut s = new_state_with("hello");
2349        s.keymap.bind_sequence(
2350            Mode::Normal,
2351            vec![Key::Char('g'), Key::Char('g')],
2352            Action::Move(Motion::DocEnd),
2353            "doc end",
2354        );
2355        s.on_key(&Key::Char('g')); // pending [g]
2356        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2357        s.on_key(&Key::Char('x')); // breaks gg → abort; x is unbound → no-op
2358        assert!(s.pending_keys.is_empty());
2359        assert_eq!(s.cursor(), Position::ZERO);
2360    }
2361
2362    #[test]
2363    fn single_binding_wins_over_sequence_prefix() {
2364        // A key that is BOTH a complete single binding and the start of
2365        // a sequence fires the single binding immediately (no chord
2366        // timeout needed). Here `h` (move-left) also prefixes `hz`.
2367        let mut s = new_state_with("abcde");
2368        let mut clk = SpacedClock::new();
2369        s.tick_at(&press(KeyCode::Char('l')), clk.next());
2370        s.tick_at(&press(KeyCode::Char('l')), clk.next());
2371        assert_eq!(s.cursor().column, 2);
2372        s.keymap.bind_sequence(
2373            Mode::Normal,
2374            vec![Key::Char('h'), Key::Char('z')],
2375            Action::Move(Motion::DocEnd),
2376            "shadowed",
2377        );
2378        s.on_key(&Key::Char('h'));
2379        assert!(s.pending_keys.is_empty(), "single binding should not pend");
2380        assert_eq!(s.cursor().column, 1, "h moved left immediately");
2381    }
2382
2383    // ── tatara-lisp runtime bridge (imperative programmability) ─────
2384
2385    #[test]
2386    fn lisp_set_option_writes_live_options() {
2387        let mut s = new_state_with("");
2388        s.run_lisp(r#"(set-option "number" "true")"#).unwrap();
2389        assert_eq!(s.options.get("number").map(String::as_str), Some("true"));
2390    }
2391
2392    #[test]
2393    fn lisp_insert_modifies_buffer_and_advances_cursor() {
2394        let mut s = new_state_with("");
2395        s.run_lisp(r#"(insert "abc")"#).unwrap();
2396        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
2397        assert_eq!(s.cursor(), Position::new(0, 3));
2398    }
2399
2400    #[test]
2401    fn lisp_message_appends_to_messages() {
2402        let mut s = new_state_with("");
2403        s.run_lisp(r#"(message "hello from lisp")"#).unwrap();
2404        assert_eq!(s.messages, vec!["hello from lisp".to_string()]);
2405    }
2406
2407    #[test]
2408    fn lisp_reads_snapshot_and_branches_to_effect() {
2409        // Genuine programmability: Lisp reads the live cursor line and
2410        // an `if` decides which option to set.
2411        let mut s = new_state_with("one\ntwo\nthree");
2412        // cursor at line 0 → "top" branch
2413        s.run_lisp(r#"(if (= (cursor-line) 0) (set-option "pos" "top") (set-option "pos" "mid"))"#)
2414            .unwrap();
2415        assert_eq!(s.options.get("pos").map(String::as_str), Some("top"));
2416    }
2417
2418    #[test]
2419    fn lisp_run_command_effect_drives_registry() {
2420        // `(run-command "undo")` reaches the live command registry and
2421        // reverts a prior Lisp-driven insert — proving the RunCommand
2422        // effect dispatches through real editor commands.
2423        let mut s = new_state_with("");
2424        s.run_lisp(r#"(insert "abc")"#).unwrap();
2425        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
2426        s.run_lisp(r#"(run-command "undo")"#).unwrap();
2427        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "");
2428    }
2429
2430    #[test]
2431    fn lisp_run_command_quit_sets_quit_requested_via_typed_flag() {
2432        // The full imperative-quit path: (run-command "quit") routes
2433        // through the registry's typed `quit_requested` signal — no string
2434        // sentinel, and no minibuffer pollution (the editor stays in a
2435        // clean Normal state, which has no minibuffer at all).
2436        let mut s = new_state_with("");
2437        s.run_lisp(r#"(run-command "quit")"#).unwrap();
2438        assert!(s.quit_requested, "lisp-driven quit must set quit_requested");
2439        assert_eq!(
2440            s.modal.minibuffer(),
2441            "",
2442            "quit must not pollute any command line — Normal mode has no minibuffer",
2443        );
2444    }
2445
2446    // ── Lazy plugin activation (PluginHost) ────────────────────────
2447
2448    #[test]
2449    fn lazy_plugin_activates_on_command_trigger() {
2450        // A user plugin gated on `Command: LazyGo` has its entry applied
2451        // the first time that command runs — proving the lazy.nvim
2452        // `cmd =` model works end-to-end against live editor state.
2453        let mut s = new_state_with("");
2454        s.register_lazy_plugin(
2455            "user-lazy",
2456            vec![LazyTrigger::Command("LazyGo".into())],
2457            r#"(defoption :name "lazy-loaded" :value "yes")
2458               (defcmd :name "LazyGo" :description "noop" :action "editor.noop")"#,
2459        );
2460        assert_eq!(s.plugin_host.pending(), 1);
2461        assert!(
2462            s.options.get("lazy-loaded").is_none(),
2463            "entry not applied yet"
2464        );
2465
2466        // Drive the command through the public imperative path.
2467        s.run_lisp(r#"(run-command "LazyGo")"#).unwrap();
2468
2469        assert_eq!(
2470            s.options.get("lazy-loaded").map(String::as_str),
2471            Some("yes"),
2472            "the command trigger applied the plugin's entry",
2473        );
2474        assert_eq!(s.plugin_host.pending(), 0, "plugin activated exactly once");
2475    }
2476
2477    #[test]
2478    fn lazy_plugin_activates_on_filetype() {
2479        let mut s = new_state_with("");
2480        s.register_lazy_plugin(
2481            "user-rust",
2482            vec![LazyTrigger::FileType("rust".into())],
2483            r#"(defoption :name "rust-plugin" :value "on")"#,
2484        );
2485        let n = s.activate_filetype_plugins("rust");
2486        assert_eq!(n, 1);
2487        assert_eq!(s.options.get("rust-plugin").map(String::as_str), Some("on"));
2488        // A second open of the same filetype is a no-op (one-shot).
2489        assert_eq!(s.activate_filetype_plugins("rust"), 0);
2490    }
2491
2492    #[test]
2493    fn cached_vm_serves_multiple_run_lisp_calls() {
2494        let mut s = new_state_with("");
2495        s.run_lisp(r#"(message "one")"#).unwrap();
2496        assert!(
2497            s.lisp_vm.is_some(),
2498            "VM should be cached after first run_lisp"
2499        );
2500        s.run_lisp(r#"(message "two")"#).unwrap();
2501        assert_eq!(s.messages, vec!["one".to_string(), "two".to_string()]);
2502    }
2503
2504    #[test]
2505    fn lisp_define_persists_across_run_lisp_calls() {
2506        // The cached VM's top-level env persists across calls (REPL
2507        // semantics): a `define` in one call is visible in the next.
2508        let mut s = new_state_with("");
2509        s.run_lisp(r#"(define greeting "hi")"#).unwrap();
2510        s.run_lisp(r#"(message greeting)"#).unwrap();
2511        assert_eq!(s.messages, vec!["hi".to_string()]);
2512    }
2513
2514    #[test]
2515    fn snapshot_is_isolated_within_one_run_lisp_call_and_refreshes_across() {
2516        // Within ONE call a program cannot observe its own writes — the
2517        // read snapshot is captured before eval, effects apply after. A
2518        // later call sees the refreshed snapshot.
2519        let mut s = new_state_with("");
2520        s.run_lisp(
2521            r#"(insert "ab") (set-option "col" (if (= (cursor-column) 0) "stale-zero" "live"))"#,
2522        )
2523        .unwrap();
2524        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "ab");
2525        assert_eq!(
2526            s.options.get("col").map(String::as_str),
2527            Some("stale-zero"),
2528            "cursor-column within the same call reads the pre-eval snapshot",
2529        );
2530        // After the first call the cursor advanced to column 2; the next
2531        // call's snapshot reflects it.
2532        s.run_lisp(r#"(set-option "col2" (if (= (cursor-column) 2) "live-two" "other"))"#)
2533            .unwrap();
2534        assert_eq!(
2535            s.options.get("col2").map(String::as_str),
2536            Some("live-two"),
2537            "a later call sees the refreshed snapshot",
2538        );
2539    }
2540
2541    #[test]
2542    fn insert_text_effect_multiline_lands_cursor_on_last_line() {
2543        let mut s = new_state_with("");
2544        s.apply_host_effects(vec![HostEffect::InsertText("foo\nbar".to_string())]);
2545        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "foo\nbar");
2546        assert_eq!(s.cursor(), Position::new(1, 3));
2547    }
2548
2549    #[test]
2550    fn visual_mode_sequence_resolves() {
2551        let mut s = new_state_with("abc");
2552        s.modal.enter(Mode::Visual);
2553        s.keymap.bind_sequence(
2554            Mode::Visual,
2555            vec![Key::Char('g'), Key::Char('e')],
2556            Action::Move(Motion::DocEnd),
2557            "ge",
2558        );
2559        s.on_key(&Key::Char('g'));
2560        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2561        s.on_key(&Key::Char('e'));
2562        assert!(s.pending_keys.is_empty());
2563        assert_eq!(
2564            s.cursor().column,
2565            3,
2566            "ge resolved to doc-end in visual mode"
2567        );
2568    }
2569
2570    #[test]
2571    fn sequence_abort_with_bound_breaking_key_redispatches() {
2572        // gg is a sequence; `l` (move-right) is a bound single key. After
2573        // `g` pends, `l` breaks gg, aborts, and is re-dispatched fresh.
2574        let mut s = new_state_with("abcde");
2575        s.keymap.bind_sequence(
2576            Mode::Normal,
2577            vec![Key::Char('g'), Key::Char('g')],
2578            Action::Move(Motion::DocEnd),
2579            "gg",
2580        );
2581        s.on_key(&Key::Char('g'));
2582        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2583        s.on_key(&Key::Char('l'));
2584        assert!(s.pending_keys.is_empty());
2585        assert_eq!(
2586            s.cursor().column,
2587            1,
2588            "the breaking key l should re-dispatch as move-right",
2589        );
2590    }
2591
2592    // ── Viewport-follows-cursor invariant (both axes) ───────────────
2593
2594    #[test]
2595    fn viewport_contains_cursor_after_every_op() {
2596        // Tiny window: 5 visible lines × 10 visible columns. Drive a
2597        // representative scripted sequence and assert the viewport contains
2598        // the cursor after EVERY mutating step.
2599        let mut s = new_state_small_viewport("", 5, 10);
2600        assert_cursor_in_viewport(&s, "initial");
2601
2602        // Enter insert mode and type 30 newline-separated lines — this is
2603        // the exact "type past the bottom" complaint.
2604        s.tick(&press(KeyCode::Char('i')));
2605        assert_eq!(s.modal.mode(), Mode::Insert);
2606        for line in 0..30u32 {
2607            for c in "line".chars() {
2608                s.tick(&press(KeyCode::Char(c)));
2609                assert_cursor_in_viewport(&s, "typing chars");
2610            }
2611            s.tick(&press(KeyCode::Enter));
2612            assert_cursor_in_viewport(&s, &format!("newline after line {line}"));
2613        }
2614
2615        // Type a long (200-char) line — the "type past the right edge"
2616        // complaint. The cursor must stay horizontally visible the whole way.
2617        for i in 0..200u32 {
2618            s.tick(&press(KeyCode::Char('x')));
2619            assert_cursor_in_viewport(&s, &format!("long-line char {i}"));
2620        }
2621
2622        // Multi-line insert_text effect (the `(insert …)` Lisp path).
2623        s.insert_text("alpha\nbeta\ngamma delta epsilon zeta");
2624        assert_cursor_in_viewport(&s, "insert_text multiline");
2625
2626        // Back to normal mode and move in all directions / to extremes.
2627        s.tick(&press(KeyCode::Escape));
2628        assert_eq!(s.modal.mode(), Mode::Normal);
2629        for m in [
2630            Motion::DocStart,
2631            Motion::DocEnd,
2632            Motion::Down,
2633            Motion::Down,
2634            Motion::Up,
2635            Motion::Right,
2636            Motion::Right,
2637            Motion::Left,
2638            Motion::LineEnd,
2639            Motion::LineStart,
2640            Motion::GotoLine(1),
2641            Motion::GotoLine(40),
2642            Motion::PageDown,
2643            Motion::PageUp,
2644        ] {
2645            s.apply_motion(m);
2646            assert_cursor_in_viewport(&s, &format!("after motion {m:?}"));
2647        }
2648
2649        // Undo many times — the buffer shrinks; the viewport must re-follow
2650        // the (now clamped) cursor.
2651        for i in 0..50u32 {
2652            s.apply(&Action::Undo);
2653            assert_cursor_in_viewport(&s, &format!("undo {i}"));
2654        }
2655        // Redo back up.
2656        for i in 0..50u32 {
2657            s.apply(&Action::Redo);
2658            assert_cursor_in_viewport(&s, &format!("redo {i}"));
2659        }
2660    }
2661
2662    #[test]
2663    fn insert_at_eof_keeps_cursor_in_bounds() {
2664        // Inserting at the end of the buffer must leave the cursor clamped
2665        // to a valid position (and inside the viewport).
2666        let mut s = new_state_small_viewport("abc", 5, 10);
2667        s.apply_motion(Motion::DocEnd);
2668        s.tick(&press(KeyCode::Char('i')));
2669        s.tick(&press(KeyCode::Char('d')));
2670        let buf = s.buffers.get(s.active).unwrap();
2671        let clamped = buf.clamp(s.cursor());
2672        assert_eq!(
2673            s.cursor(),
2674            clamped,
2675            "cursor must be clamped in-bounds at EOF"
2676        );
2677        assert_cursor_in_viewport(&s, "insert at eof");
2678    }
2679
2680    #[test]
2681    fn count_prefix_then_sequence_repeats() {
2682        // `2` then `gj` (→ move-down) repeats the resolved action twice.
2683        let mut s = new_state_with("a\nb\nc\nd\ne");
2684        s.keymap.bind_sequence(
2685            Mode::Normal,
2686            vec![Key::Char('g'), Key::Char('j')],
2687            Action::Move(Motion::Down),
2688            "gj",
2689        );
2690        s.on_key(&Key::Char('2'));
2691        s.on_key(&Key::Char('g'));
2692        s.on_key(&Key::Char('j'));
2693        assert_eq!(s.cursor().line, 2, "count 2 should repeat the gj motion");
2694    }
2695
2696    // ── Key-repeat gate (awase::KeyRepeatGate) ──────────────────────────
2697
2698    #[test]
2699    fn held_key_repeat_storm_is_debounced_in_normal_mode() {
2700        // The audit's exact complaint: holding `j` floods motion events
2701        // and thrashes the viewport. Simulate an OS key-repeat storm — 20
2702        // identical `j` KeyDowns at 50ms intervals (typical repeat cadence)
2703        // — and assert only the gated subset (one per 80ms window) actually
2704        // moves the cursor.
2705        let mut s = new_state_with(&"x\n".repeat(40));
2706        let t0 = std::time::Instant::now();
2707        let mut delivered = 0u32;
2708        for i in 0..20u32 {
2709            let before = s.cursor().line;
2710            s.tick_at(
2711                &press(KeyCode::Char('j')),
2712                t0 + std::time::Duration::from_millis(u64::from(i) * 50),
2713            );
2714            if s.cursor().line != before {
2715                delivered += 1;
2716            }
2717        }
2718        // 20 events over ~1s at 50ms spacing, 80ms gate ⇒ ~13 pass — far
2719        // fewer than the 20 the ungated path would have applied.
2720        assert!(
2721            (10..=14).contains(&delivered),
2722            "expected the storm debounced to ~13 moves, got {delivered}",
2723        );
2724        assert!(
2725            delivered < 20,
2726            "the gate must drop SOME storm ticks, not pass all 20",
2727        );
2728    }
2729
2730    #[test]
2731    fn spaced_intentional_taps_all_pass() {
2732        // Intentional taps spaced past the debounce window must ALL reach
2733        // the editor — the gate filters storms, never deliberate input.
2734        let mut s = new_state_with(&"x\n".repeat(10));
2735        let t0 = std::time::Instant::now();
2736        for i in 0..5u32 {
2737            s.tick_at(
2738                &press(KeyCode::Char('j')),
2739                // 100ms apart — comfortably past the 80ms window.
2740                t0 + std::time::Duration::from_millis(u64::from(i) * 100),
2741            );
2742        }
2743        assert_eq!(s.cursor().line, 5, "all 5 spaced `j` taps moved the cursor");
2744    }
2745
2746    #[test]
2747    fn distinct_keys_have_independent_clocks() {
2748        // Holding `j` must not block a simultaneous `l` — the gate keys on
2749        // the Key, so independent keys have independent windows.
2750        let mut s = new_state_with("abc\ndef\nghi");
2751        let t = std::time::Instant::now();
2752        s.tick_at(&press(KeyCode::Char('j')), t);
2753        // `j` again within the window is dropped…
2754        s.tick_at(
2755            &press(KeyCode::Char('j')),
2756            t + std::time::Duration::from_millis(10),
2757        );
2758        assert_eq!(s.cursor().line, 1, "second `j` within window dropped");
2759        // …but `l` at the same instant passes (its own clock).
2760        s.tick_at(
2761            &press(KeyCode::Char('l')),
2762            t + std::time::Duration::from_millis(10),
2763        );
2764        assert_eq!(s.cursor().column, 1, "`l` is not blocked by `j`'s clock");
2765    }
2766
2767    // ── Cursors newtype is the single cursor home ──────────────────────
2768
2769    #[test]
2770    fn cursor_home_preserves_single_cursor_behavior() {
2771        // The typed `Cursors` wrapper behaves exactly like the old bare
2772        // `Position` field for single-cursor editing: the read accessor
2773        // tracks every mutation routed through `set_cursor`, and there is
2774        // exactly one caret.
2775        let mut s = new_state_with("hello\nworld\nthere");
2776        assert_eq!(s.cursor(), Position::ZERO);
2777        assert_eq!(s.cursors.count(), 1, "phase-1 holds exactly one caret");
2778
2779        s.apply_motion(Motion::Down);
2780        s.apply_motion(Motion::Right);
2781        s.apply_motion(Motion::Right);
2782        assert_eq!(s.cursor(), Position::new(1, 2));
2783        // Still a single caret after a sequence of motions.
2784        assert_eq!(s.cursors.count(), 1);
2785
2786        // The accessor is the SAME value the viewport-follow path read.
2787        let w = s.layout.active_window().unwrap();
2788        assert!(w.viewport.top_line <= s.cursor().line);
2789    }
2790
2791    #[test]
2792    fn insert_mode_is_ungated_so_repeat_typing_works() {
2793        // Holding a key to repeat-type a character is intended in Insert
2794        // mode — the gate must NOT suppress it. 10 rapid identical `x`
2795        // keystrokes at the same instant must all land as text.
2796        let mut s = new_state_with("");
2797        s.tick(&press(KeyCode::Char('i')));
2798        assert_eq!(s.modal.mode(), Mode::Insert);
2799        let t = std::time::Instant::now();
2800        for _ in 0..10 {
2801            s.tick_at(&press(KeyCode::Char('x')), t);
2802        }
2803        assert_eq!(
2804            s.buffers.get(s.active).unwrap().to_string(),
2805            "xxxxxxxxxx",
2806            "insert-mode repeat typing is ungated",
2807        );
2808    }
2809}