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