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