Skip to main content

hjkl_engine/
editor.rs

1//! Editor — the public sqeel-vim type, layered over `hjkl_buffer::Buffer`.
2//!
3//! This file owns the public Editor API — construction, content access,
4//! mouse and goto helpers, the (buffer-level) undo stack, and insert-mode
5//! session bookkeeping. All vim-specific keyboard handling lives in
6//! [`vim`] and communicates with Editor through a small internal API
7//! exposed via `pub(super)` fields and helper methods.
8
9use crate::input::Input;
10#[cfg(feature = "crossterm")]
11use crate::input::Key;
12use crate::vim::{self, VimState};
13use crate::{KeybindingMode, VimMode};
14#[cfg(feature = "crossterm")]
15use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
16#[cfg(feature = "ratatui")]
17use ratatui::layout::Rect;
18use std::sync::atomic::{AtomicU16, Ordering};
19
20/// Convert a SPEC [`crate::types::Style`] to a [`ratatui::style::Style`].
21///
22/// Lossless within the styles each library represents. Lives behind the
23/// `ratatui` feature so wasm / no_std consumers that opt out don't pay
24/// for the dep. Use the engine-native [`crate::types::Style`] +
25/// [`Editor::intern_engine_style`] surface from feature-disabled hosts.
26#[cfg(feature = "ratatui")]
27pub(crate) fn engine_style_to_ratatui(s: crate::types::Style) -> ratatui::style::Style {
28    use crate::types::Attrs;
29    use ratatui::style::{Color as RColor, Modifier as RMod, Style as RStyle};
30    let mut out = RStyle::default();
31    if let Some(c) = s.fg {
32        out = out.fg(RColor::Rgb(c.0, c.1, c.2));
33    }
34    if let Some(c) = s.bg {
35        out = out.bg(RColor::Rgb(c.0, c.1, c.2));
36    }
37    let mut m = RMod::empty();
38    if s.attrs.contains(Attrs::BOLD) {
39        m |= RMod::BOLD;
40    }
41    if s.attrs.contains(Attrs::ITALIC) {
42        m |= RMod::ITALIC;
43    }
44    if s.attrs.contains(Attrs::UNDERLINE) {
45        m |= RMod::UNDERLINED;
46    }
47    if s.attrs.contains(Attrs::REVERSE) {
48        m |= RMod::REVERSED;
49    }
50    if s.attrs.contains(Attrs::DIM) {
51        m |= RMod::DIM;
52    }
53    if s.attrs.contains(Attrs::STRIKE) {
54        m |= RMod::CROSSED_OUT;
55    }
56    out.add_modifier(m)
57}
58
59/// Inverse of [`engine_style_to_ratatui`]. Lossy for ratatui colors
60/// the engine doesn't model (Indexed, named ANSI) — flattens to
61/// nearest RGB. Behind the `ratatui` feature.
62#[cfg(feature = "ratatui")]
63pub(crate) fn ratatui_style_to_engine(s: ratatui::style::Style) -> crate::types::Style {
64    use crate::types::{Attrs, Color, Style};
65    use ratatui::style::{Color as RColor, Modifier as RMod};
66    fn c(rc: RColor) -> Color {
67        match rc {
68            RColor::Rgb(r, g, b) => Color(r, g, b),
69            RColor::Black => Color(0, 0, 0),
70            RColor::Red => Color(205, 49, 49),
71            RColor::Green => Color(13, 188, 121),
72            RColor::Yellow => Color(229, 229, 16),
73            RColor::Blue => Color(36, 114, 200),
74            RColor::Magenta => Color(188, 63, 188),
75            RColor::Cyan => Color(17, 168, 205),
76            RColor::Gray => Color(229, 229, 229),
77            RColor::DarkGray => Color(102, 102, 102),
78            RColor::LightRed => Color(241, 76, 76),
79            RColor::LightGreen => Color(35, 209, 139),
80            RColor::LightYellow => Color(245, 245, 67),
81            RColor::LightBlue => Color(59, 142, 234),
82            RColor::LightMagenta => Color(214, 112, 214),
83            RColor::LightCyan => Color(41, 184, 219),
84            RColor::White => Color(255, 255, 255),
85            _ => Color(0, 0, 0),
86        }
87    }
88    let mut attrs = Attrs::empty();
89    if s.add_modifier.contains(RMod::BOLD) {
90        attrs |= Attrs::BOLD;
91    }
92    if s.add_modifier.contains(RMod::ITALIC) {
93        attrs |= Attrs::ITALIC;
94    }
95    if s.add_modifier.contains(RMod::UNDERLINED) {
96        attrs |= Attrs::UNDERLINE;
97    }
98    if s.add_modifier.contains(RMod::REVERSED) {
99        attrs |= Attrs::REVERSE;
100    }
101    if s.add_modifier.contains(RMod::DIM) {
102        attrs |= Attrs::DIM;
103    }
104    if s.add_modifier.contains(RMod::CROSSED_OUT) {
105        attrs |= Attrs::STRIKE;
106    }
107    Style {
108        fg: s.fg.map(c),
109        bg: s.bg.map(c),
110        attrs,
111    }
112}
113
114/// Map a [`hjkl_buffer::Edit`] to one or more SPEC
115/// [`crate::types::Edit`] (`EditOp`) records.
116///
117/// Most buffer edits map to a single EditOp. Block ops
118/// ([`hjkl_buffer::Edit::InsertBlock`] /
119/// [`hjkl_buffer::Edit::DeleteBlockChunks`]) emit one EditOp per row
120/// touched — they edit non-contiguous cells and a single
121/// `range..range` can't represent the rectangle.
122///
123/// Returns an empty vec when the edit isn't representable (no buffer
124/// variant currently fails this check).
125fn edit_to_editops(edit: &hjkl_buffer::Edit) -> Vec<crate::types::Edit> {
126    use crate::types::{Edit as Op, Pos};
127    use hjkl_buffer::Edit as B;
128    let to_pos = |p: hjkl_buffer::Position| Pos {
129        line: p.row as u32,
130        col: p.col as u32,
131    };
132    match edit {
133        B::InsertChar { at, ch } => vec![Op {
134            range: to_pos(*at)..to_pos(*at),
135            replacement: ch.to_string(),
136        }],
137        B::InsertStr { at, text } => vec![Op {
138            range: to_pos(*at)..to_pos(*at),
139            replacement: text.clone(),
140        }],
141        B::DeleteRange { start, end, .. } => vec![Op {
142            range: to_pos(*start)..to_pos(*end),
143            replacement: String::new(),
144        }],
145        B::Replace { start, end, with } => vec![Op {
146            range: to_pos(*start)..to_pos(*end),
147            replacement: with.clone(),
148        }],
149        B::JoinLines {
150            row,
151            count,
152            with_space,
153        } => {
154            // Joining `count` rows after `row` collapses
155            // [(row+1, 0) .. (row+count, EOL)] into the joined
156            // sentinel. The replacement is either an empty string
157            // (gJ) or " " between segments (J).
158            let start = Pos {
159                line: *row as u32 + 1,
160                col: 0,
161            };
162            let end = Pos {
163                line: (*row + *count) as u32,
164                col: u32::MAX, // covers to EOL of the last source row
165            };
166            vec![Op {
167                range: start..end,
168                replacement: if *with_space {
169                    " ".into()
170                } else {
171                    String::new()
172                },
173            }]
174        }
175        B::SplitLines {
176            row,
177            cols,
178            inserted_space: _,
179        } => {
180            // SplitLines reverses a JoinLines: insert a `\n`
181            // (and optional dropped space) at each col on `row`.
182            cols.iter()
183                .map(|c| {
184                    let p = Pos {
185                        line: *row as u32,
186                        col: *c as u32,
187                    };
188                    Op {
189                        range: p..p,
190                        replacement: "\n".into(),
191                    }
192                })
193                .collect()
194        }
195        B::InsertBlock { at, chunks } => {
196            // One EditOp per row in the block — non-contiguous edits.
197            chunks
198                .iter()
199                .enumerate()
200                .map(|(i, chunk)| {
201                    let p = Pos {
202                        line: at.row as u32 + i as u32,
203                        col: at.col as u32,
204                    };
205                    Op {
206                        range: p..p,
207                        replacement: chunk.clone(),
208                    }
209                })
210                .collect()
211        }
212        B::DeleteBlockChunks { at, widths } => {
213            // One EditOp per row, deleting `widths[i]` chars at
214            // `(at.row + i, at.col)`.
215            widths
216                .iter()
217                .enumerate()
218                .map(|(i, w)| {
219                    let start = Pos {
220                        line: at.row as u32 + i as u32,
221                        col: at.col as u32,
222                    };
223                    let end = Pos {
224                        line: at.row as u32 + i as u32,
225                        col: at.col as u32 + *w as u32,
226                    };
227                    Op {
228                        range: start..end,
229                        replacement: String::new(),
230                    }
231                })
232                .collect()
233        }
234    }
235}
236
237/// Sum of bytes from the start of the buffer to the start of `row`.
238/// Walks lines + their separating `\n` bytes — matches the canonical
239/// `lines().join("\n")` byte rendering used by syntax tooling.
240#[inline]
241fn buffer_byte_of_row(buf: &hjkl_buffer::Buffer, row: usize) -> usize {
242    let n = buf.row_count();
243    let row = row.min(n);
244    let mut acc = 0usize;
245    for r in 0..row {
246        acc += buf.line(r).map(str::len).unwrap_or(0);
247        if r + 1 < n {
248            acc += 1; // separator '\n'
249        }
250    }
251    acc
252}
253
254/// Convert an `hjkl_buffer::Position` (char-indexed col) into byte
255/// coordinates `(byte_within_buffer, (row, col_byte))` against the
256/// **pre-edit** buffer.
257fn position_to_byte_coords(
258    buf: &hjkl_buffer::Buffer,
259    pos: hjkl_buffer::Position,
260) -> (usize, (u32, u32)) {
261    let row = pos.row.min(buf.row_count().saturating_sub(1));
262    let line = buf.line(row).unwrap_or("");
263    let col_byte = pos.byte_offset(line);
264    let byte = buffer_byte_of_row(buf, row) + col_byte;
265    (byte, (row as u32, col_byte as u32))
266}
267
268/// Compute the byte position after inserting `text` starting at
269/// `start_byte` / `start_pos`. Returns `(end_byte, end_position)`.
270fn advance_by_text(text: &str, start_byte: usize, start_pos: (u32, u32)) -> (usize, (u32, u32)) {
271    let new_end_byte = start_byte + text.len();
272    let newlines = text.bytes().filter(|&b| b == b'\n').count();
273    let end_pos = if newlines == 0 {
274        (start_pos.0, start_pos.1 + text.len() as u32)
275    } else {
276        // Bytes after the last newline determine the trailing column.
277        let last_nl = text.rfind('\n').unwrap();
278        let tail_bytes = (text.len() - last_nl - 1) as u32;
279        (start_pos.0 + newlines as u32, tail_bytes)
280    };
281    (new_end_byte, end_pos)
282}
283
284/// Translate a single `hjkl_buffer::Edit` into one or more
285/// [`crate::types::ContentEdit`] records using the **pre-edit** buffer
286/// state for byte/position lookups. Block ops fan out to one entry per
287/// touched row (matches `edit_to_editops`).
288fn content_edits_from_buffer_edit(
289    buf: &hjkl_buffer::Buffer,
290    edit: &hjkl_buffer::Edit,
291) -> Vec<crate::types::ContentEdit> {
292    use hjkl_buffer::Edit as B;
293    use hjkl_buffer::Position;
294
295    let mut out: Vec<crate::types::ContentEdit> = Vec::new();
296
297    match edit {
298        B::InsertChar { at, ch } => {
299            let (start_byte, start_pos) = position_to_byte_coords(buf, *at);
300            let new_end_byte = start_byte + ch.len_utf8();
301            let new_end_pos = (start_pos.0, start_pos.1 + ch.len_utf8() as u32);
302            out.push(crate::types::ContentEdit {
303                start_byte,
304                old_end_byte: start_byte,
305                new_end_byte,
306                start_position: start_pos,
307                old_end_position: start_pos,
308                new_end_position: new_end_pos,
309            });
310        }
311        B::InsertStr { at, text } => {
312            let (start_byte, start_pos) = position_to_byte_coords(buf, *at);
313            let (new_end_byte, new_end_pos) = advance_by_text(text, start_byte, start_pos);
314            out.push(crate::types::ContentEdit {
315                start_byte,
316                old_end_byte: start_byte,
317                new_end_byte,
318                start_position: start_pos,
319                old_end_position: start_pos,
320                new_end_position: new_end_pos,
321            });
322        }
323        B::DeleteRange { start, end, kind } => {
324            let (start, end) = if start <= end {
325                (*start, *end)
326            } else {
327                (*end, *start)
328            };
329            match kind {
330                hjkl_buffer::MotionKind::Char => {
331                    let (start_byte, start_pos) = position_to_byte_coords(buf, start);
332                    let (old_end_byte, old_end_pos) = position_to_byte_coords(buf, end);
333                    out.push(crate::types::ContentEdit {
334                        start_byte,
335                        old_end_byte,
336                        new_end_byte: start_byte,
337                        start_position: start_pos,
338                        old_end_position: old_end_pos,
339                        new_end_position: start_pos,
340                    });
341                }
342                hjkl_buffer::MotionKind::Line => {
343                    // Linewise delete drops rows [start.row..=end.row]. Map
344                    // to a span from start of `start.row` through start of
345                    // (end.row + 1). The buffer's own `do_delete_range`
346                    // collapses to row `start.row` after dropping.
347                    let lo = start.row;
348                    let hi = end.row.min(buf.row_count().saturating_sub(1));
349                    let start_byte = buffer_byte_of_row(buf, lo);
350                    let next_row_byte = if hi + 1 < buf.row_count() {
351                        buffer_byte_of_row(buf, hi + 1)
352                    } else {
353                        // No row after; clamp to end-of-buffer byte.
354                        buffer_byte_of_row(buf, buf.row_count())
355                            + buf
356                                .line(buf.row_count().saturating_sub(1))
357                                .map(str::len)
358                                .unwrap_or(0)
359                    };
360                    out.push(crate::types::ContentEdit {
361                        start_byte,
362                        old_end_byte: next_row_byte,
363                        new_end_byte: start_byte,
364                        start_position: (lo as u32, 0),
365                        old_end_position: ((hi + 1) as u32, 0),
366                        new_end_position: (lo as u32, 0),
367                    });
368                }
369                hjkl_buffer::MotionKind::Block => {
370                    // Block delete removes a rectangle of chars per row.
371                    // Fan out to one ContentEdit per row.
372                    let (left_col, right_col) = (start.col.min(end.col), start.col.max(end.col));
373                    for row in start.row..=end.row {
374                        let row_start_pos = Position::new(row, left_col);
375                        let row_end_pos = Position::new(row, right_col + 1);
376                        let (sb, sp) = position_to_byte_coords(buf, row_start_pos);
377                        let (eb, ep) = position_to_byte_coords(buf, row_end_pos);
378                        if eb <= sb {
379                            continue;
380                        }
381                        out.push(crate::types::ContentEdit {
382                            start_byte: sb,
383                            old_end_byte: eb,
384                            new_end_byte: sb,
385                            start_position: sp,
386                            old_end_position: ep,
387                            new_end_position: sp,
388                        });
389                    }
390                }
391            }
392        }
393        B::Replace { start, end, with } => {
394            let (start, end) = if start <= end {
395                (*start, *end)
396            } else {
397                (*end, *start)
398            };
399            let (start_byte, start_pos) = position_to_byte_coords(buf, start);
400            let (old_end_byte, old_end_pos) = position_to_byte_coords(buf, end);
401            let (new_end_byte, new_end_pos) = advance_by_text(with, start_byte, start_pos);
402            out.push(crate::types::ContentEdit {
403                start_byte,
404                old_end_byte,
405                new_end_byte,
406                start_position: start_pos,
407                old_end_position: old_end_pos,
408                new_end_position: new_end_pos,
409            });
410        }
411        B::JoinLines {
412            row,
413            count,
414            with_space,
415        } => {
416            // Joining `count` rows after `row` collapses the bytes
417            // between EOL of `row` and EOL of `row + count` into either
418            // an empty string (gJ) or a single space per join (J — but
419            // only when both sides are non-empty; we approximate with
420            // a single space for simplicity).
421            let row = (*row).min(buf.row_count().saturating_sub(1));
422            let last_join_row = (row + count).min(buf.row_count().saturating_sub(1));
423            let line = buf.line(row).unwrap_or("");
424            let row_eol_byte = buffer_byte_of_row(buf, row) + line.len();
425            let row_eol_col = line.len() as u32;
426            let next_row_after = last_join_row + 1;
427            let old_end_byte = if next_row_after < buf.row_count() {
428                buffer_byte_of_row(buf, next_row_after).saturating_sub(1)
429            } else {
430                buffer_byte_of_row(buf, buf.row_count())
431                    + buf
432                        .line(buf.row_count().saturating_sub(1))
433                        .map(str::len)
434                        .unwrap_or(0)
435            };
436            let last_line = buf.line(last_join_row).unwrap_or("");
437            let old_end_pos = (last_join_row as u32, last_line.len() as u32);
438            let replacement_len = if *with_space { 1 } else { 0 };
439            let new_end_byte = row_eol_byte + replacement_len;
440            let new_end_pos = (row as u32, row_eol_col + replacement_len as u32);
441            out.push(crate::types::ContentEdit {
442                start_byte: row_eol_byte,
443                old_end_byte,
444                new_end_byte,
445                start_position: (row as u32, row_eol_col),
446                old_end_position: old_end_pos,
447                new_end_position: new_end_pos,
448            });
449        }
450        B::SplitLines {
451            row,
452            cols,
453            inserted_space,
454        } => {
455            // Splits insert "\n" (or "\n " inverse) at each col on `row`.
456            // The buffer applies all splits left-to-right via the
457            // do_split_lines path; we emit one ContentEdit per col,
458            // each treated as an insert at that col on `row`. Note: the
459            // buffer state during emission is *pre-edit*, so all cols
460            // index into the same pre-edit row.
461            let row = (*row).min(buf.row_count().saturating_sub(1));
462            let line = buf.line(row).unwrap_or("");
463            let row_byte = buffer_byte_of_row(buf, row);
464            let insert = if *inserted_space { "\n " } else { "\n" };
465            for &c in cols {
466                let pos = Position::new(row, c);
467                let col_byte = pos.byte_offset(line);
468                let start_byte = row_byte + col_byte;
469                let start_pos = (row as u32, col_byte as u32);
470                let (new_end_byte, new_end_pos) = advance_by_text(insert, start_byte, start_pos);
471                out.push(crate::types::ContentEdit {
472                    start_byte,
473                    old_end_byte: start_byte,
474                    new_end_byte,
475                    start_position: start_pos,
476                    old_end_position: start_pos,
477                    new_end_position: new_end_pos,
478                });
479            }
480        }
481        B::InsertBlock { at, chunks } => {
482            // One ContentEdit per chunk; each lands at `(at.row + i,
483            // at.col)` in the pre-edit buffer.
484            for (i, chunk) in chunks.iter().enumerate() {
485                let pos = Position::new(at.row + i, at.col);
486                let (start_byte, start_pos) = position_to_byte_coords(buf, pos);
487                let (new_end_byte, new_end_pos) = advance_by_text(chunk, start_byte, start_pos);
488                out.push(crate::types::ContentEdit {
489                    start_byte,
490                    old_end_byte: start_byte,
491                    new_end_byte,
492                    start_position: start_pos,
493                    old_end_position: start_pos,
494                    new_end_position: new_end_pos,
495                });
496            }
497        }
498        B::DeleteBlockChunks { at, widths } => {
499            for (i, w) in widths.iter().enumerate() {
500                let row = at.row + i;
501                let start_pos = Position::new(row, at.col);
502                let end_pos = Position::new(row, at.col + *w);
503                let (sb, sp) = position_to_byte_coords(buf, start_pos);
504                let (eb, ep) = position_to_byte_coords(buf, end_pos);
505                if eb <= sb {
506                    continue;
507                }
508                out.push(crate::types::ContentEdit {
509                    start_byte: sb,
510                    old_end_byte: eb,
511                    new_end_byte: sb,
512                    start_position: sp,
513                    old_end_position: ep,
514                    new_end_position: sp,
515                });
516            }
517        }
518    }
519
520    out
521}
522
523/// Where the cursor should land in the viewport after a `z`-family
524/// scroll (`zz` / `zt` / `zb`).
525#[derive(Debug, Clone, Copy, PartialEq, Eq)]
526pub(super) enum CursorScrollTarget {
527    Center,
528    Top,
529    Bottom,
530}
531
532// ── Trait-surface cast helpers ────────────────────────────────────
533//
534// 0.0.42 (Patch C-δ.7): the helpers introduced in 0.0.41 were
535// promoted to [`crate::buf_helpers`] so `vim.rs` free fns can route
536// their reaches through the same primitives. Re-import via
537// `use` so the editor body keeps its terse call shape.
538
539use crate::buf_helpers::{
540    apply_buffer_edit, buf_cursor_pos, buf_cursor_rc, buf_cursor_row, buf_line, buf_line_chars,
541    buf_lines_to_vec, buf_row_count, buf_set_cursor_rc,
542};
543
544pub struct Editor<
545    B: crate::types::Buffer = hjkl_buffer::Buffer,
546    H: crate::types::Host = crate::types::DefaultHost,
547> {
548    pub keybinding_mode: KeybindingMode,
549    /// Set when the user yanks/cuts; caller drains this to write to OS clipboard.
550    pub last_yank: Option<String>,
551    /// All vim-specific state (mode, pending operator, count, dot-repeat, ...).
552    /// Internal — exposed via Editor accessor methods
553    /// ([`Editor::buffer_mark`], [`Editor::last_jump_back`],
554    /// [`Editor::last_edit_pos`], [`Editor::take_lsp_intent`], …).
555    pub(crate) vim: VimState,
556    /// Undo history: each entry is (lines, cursor) before the edit.
557    /// Internal — managed by [`Editor::push_undo`] / [`Editor::restore`]
558    /// / [`Editor::pop_last_undo`].
559    pub(crate) undo_stack: Vec<(Vec<String>, (usize, usize))>,
560    /// Redo history: entries pushed when undoing.
561    pub(super) redo_stack: Vec<(Vec<String>, (usize, usize))>,
562    /// Set whenever the buffer content changes; cleared by `take_dirty`.
563    pub(super) content_dirty: bool,
564    /// Cached snapshot of `lines().join("\n") + "\n"` wrapped in an Arc
565    /// so repeated `content_arc()` calls within the same un-mutated
566    /// window are free (ref-count bump instead of a full-buffer join).
567    /// Invalidated by every [`mark_content_dirty`] call.
568    pub(super) cached_content: Option<std::sync::Arc<String>>,
569    /// Last rendered viewport height (text rows only, no chrome). Written
570    /// by the draw path via [`set_viewport_height`] so the scroll helpers
571    /// can clamp the cursor to stay visible without plumbing the height
572    /// through every call.
573    pub(super) viewport_height: AtomicU16,
574    /// Pending LSP intent set by a normal-mode chord (e.g. `gd` for
575    /// goto-definition). The host app drains this each step and fires
576    /// the matching request against its own LSP client.
577    pub(super) pending_lsp: Option<LspIntent>,
578    /// Pending [`crate::types::FoldOp`]s raised by `z…` keystrokes,
579    /// the `:fold*` Ex commands, or the edit pipeline's
580    /// "edits-inside-a-fold open it" invalidation. Drained by hosts
581    /// via [`Editor::take_fold_ops`]; the engine also applies each op
582    /// locally through [`crate::buffer_impl::BufferFoldProviderMut`]
583    /// so the in-tree buffer fold storage stays in sync without host
584    /// cooperation. Introduced in 0.0.38 (Patch C-δ.4).
585    pub(super) pending_fold_ops: Vec<crate::types::FoldOp>,
586    /// Buffer storage.
587    ///
588    /// 0.1.0 (Patch C-δ): generic over `B: Buffer` per SPEC §"Editor
589    /// surface". Default `B = hjkl_buffer::Buffer`. The vim FSM body
590    /// and `Editor::mutate_edit` are concrete on `hjkl_buffer::Buffer`
591    /// for 0.1.0 — see `crate::buf_helpers::apply_buffer_edit`.
592    pub(super) buffer: B,
593    /// Style intern table for the migration buffer's opaque
594    /// `Span::style` ids. Phase 7d-ii-a wiring — `apply_window_spans`
595    /// produces `(start, end, Style)` tuples for the textarea; we
596    /// translate those to `hjkl_buffer::Span` by interning the
597    /// `Style` here and storing the table index. The render path's
598    /// `StyleResolver` looks the style back up by id.
599    ///
600    /// Behind the `ratatui` feature; non-ratatui hosts use the
601    /// engine-native [`crate::types::Style`] surface via
602    /// [`Editor::intern_engine_style`] (which lives on a parallel
603    /// engine-side table when ratatui is off).
604    #[cfg(feature = "ratatui")]
605    pub(super) style_table: Vec<ratatui::style::Style>,
606    /// Engine-native style intern table. Used directly by
607    /// [`Editor::intern_engine_style`] when the `ratatui` feature is
608    /// off; when it's on, the table is derived from `style_table` via
609    /// [`ratatui_style_to_engine`] / [`engine_style_to_ratatui`].
610    #[cfg(not(feature = "ratatui"))]
611    pub(super) engine_style_table: Vec<crate::types::Style>,
612    /// Vim-style register bank — `"`, `"0`–`"9`, `"a`–`"z`. Sources
613    /// every `p` / `P` via the active selector (default unnamed).
614    /// Internal — read via [`Editor::registers`]; mutated by yank /
615    /// delete / paste FSM paths and by [`Editor::seed_yank`].
616    pub(crate) registers: crate::registers::Registers,
617    /// Per-row syntax styling, kept here so the host can do
618    /// incremental window updates (see `apply_window_spans` in
619    /// the host). Same `(start_byte, end_byte, Style)` tuple shape
620    /// the textarea used to host. The Buffer-side opaque-id spans are
621    /// derived from this on every install. Behind the `ratatui`
622    /// feature.
623    #[cfg(feature = "ratatui")]
624    pub styled_spans: Vec<Vec<(usize, usize, ratatui::style::Style)>>,
625    /// Per-editor settings tweakable via `:set`. Exposed by reference
626    /// so handlers (indent, search) read the live value rather than a
627    /// snapshot taken at startup. Read via [`Editor::settings`];
628    /// mutate via [`Editor::settings_mut`].
629    pub(crate) settings: Settings,
630    /// Unified named-marks map. Lowercase letters (`'a`–`'z`) are
631    /// per-Editor / "buffer-scope-equivalent" — set by `m{a-z}`, read
632    /// by `'{a-z}` / `` `{a-z} ``. Uppercase letters (`'A`–`'Z`) are
633    /// "file marks" that survive [`Editor::set_content`] calls so
634    /// they persist across tab swaps within the same Editor.
635    ///
636    /// 0.0.36: consolidated from three former storages:
637    /// - `hjkl_buffer::Buffer::marks` (deleted; was unused dead code).
638    /// - `vim::VimState::marks` (lowercase) (deleted).
639    /// - `Editor::file_marks` (uppercase) (replaced by this map).
640    ///
641    /// `BTreeMap` so iteration is deterministic for snapshot tests
642    /// and the `:marks` ex command. Mark-shift on edits is handled
643    /// by [`Editor::shift_marks_after_edit`].
644    pub(crate) marks: std::collections::BTreeMap<char, (usize, usize)>,
645    /// Block ranges (`(start_row, end_row)` inclusive) the host has
646    /// extracted from a syntax tree. `:foldsyntax` reads these to
647    /// populate folds. The host refreshes them on every re-parse via
648    /// [`Editor::set_syntax_fold_ranges`]; ex commands read them via
649    /// [`Editor::syntax_fold_ranges`].
650    pub(crate) syntax_fold_ranges: Vec<(usize, usize)>,
651    /// Pending edit log drained by [`Editor::take_changes`]. Each entry
652    /// is a SPEC [`crate::types::Edit`] mapped from the underlying
653    /// `hjkl_buffer::Edit` operation. Compound ops (JoinLines,
654    /// SplitLines, InsertBlock, DeleteBlockChunks) emit a single
655    /// best-effort EditOp covering the touched range; hosts wanting
656    /// per-cell deltas should diff their own snapshot of `lines()`.
657    /// Sealed at 0.1.0 trait extraction.
658    /// Drained by [`Editor::take_changes`].
659    pub(crate) change_log: Vec<crate::types::Edit>,
660    /// Vim's "sticky column" (curswant). `None` before the first
661    /// motion — the next vertical motion bootstraps from the live
662    /// cursor column. Horizontal motions refresh this to the new
663    /// column; vertical motions read it back so bouncing through a
664    /// shorter row doesn't drag the cursor to col 0. Hoisted out of
665    /// `hjkl_buffer::Buffer` (and `VimState`) in 0.0.28 — Editor is
666    /// the single owner now. Buffer motion methods that need it
667    /// take a `&mut Option<usize>` parameter.
668    pub(crate) sticky_col: Option<usize>,
669    /// Host adapter for clipboard, cursor-shape, time, viewport, and
670    /// search-prompt / cancellation side-channels.
671    ///
672    /// 0.1.0 (Patch C-δ): generic over `H: Host` per SPEC §"Editor
673    /// surface". Default `H = DefaultHost`. The pre-0.1.0 `EngineHost`
674    /// dyn-shim is gone — every method now dispatches through `H`'s
675    /// `Host` trait surface directly.
676    pub(crate) host: H,
677    /// Last public mode the cursor-shape emitter saw. Drives
678    /// [`Editor::emit_cursor_shape_if_changed`] so `Host::emit_cursor_shape`
679    /// fires exactly once per mode transition without sprinkling the
680    /// call across every `vim.mode = ...` site.
681    pub(crate) last_emitted_mode: crate::VimMode,
682    /// Search FSM state (pattern + per-row match cache + wrapscan).
683    /// 0.0.35: relocated out of `hjkl_buffer::Buffer` per
684    /// `DESIGN_33_METHOD_CLASSIFICATION.md` step 1.
685    /// 0.0.37: the buffer-side bridge (`Buffer::search_pattern`) is
686    /// gone; `BufferView` now takes the active regex as a `&Regex`
687    /// parameter, sourced from `Editor::search_state().pattern`.
688    pub(crate) search_state: crate::search::SearchState,
689    /// Per-row syntax span overlay. Source of truth for the host's
690    /// renderer ([`hjkl_buffer::BufferView::spans`]). Populated by
691    /// [`Editor::install_syntax_spans`] /
692    /// [`Editor::install_ratatui_syntax_spans`] (and, in due course,
693    /// by `Host::syntax_highlights` once the engine drives that path
694    /// directly).
695    ///
696    /// 0.0.37: lifted out of `hjkl_buffer::Buffer` per step 3 of
697    /// `DESIGN_33_METHOD_CLASSIFICATION.md`. The buffer-side cache +
698    /// `Buffer::set_spans` / `Buffer::spans` accessors are gone.
699    pub(crate) buffer_spans: Vec<Vec<hjkl_buffer::Span>>,
700    /// Pending `ContentEdit` records emitted by `mutate_edit`. Drained by
701    /// hosts via [`Editor::take_content_edits`] for fan-in to a syntax
702    /// tree (or any other content-change observer that needs byte-level
703    /// position deltas). Edges are byte-indexed and `(row, col_byte)`.
704    pub(crate) pending_content_edits: Vec<crate::types::ContentEdit>,
705    /// Pending "reset" flag set when the entire buffer is replaced
706    /// (e.g. `set_content` / `restore`). Supersedes any queued
707    /// `pending_content_edits` on the same frame: hosts call
708    /// [`Editor::take_content_reset`] before draining edits.
709    pub(crate) pending_content_reset: bool,
710    /// Row range touched by the most recent `auto_indent_rows` call.
711    /// `(top_row, bot_row)` inclusive. Set by the engine after every
712    /// auto-indent operation; drained (and cleared) by the host via
713    /// [`Editor::take_last_indent_range`] so it can display a brief
714    /// visual flash over the reindented rows.
715    pub(crate) last_indent_range: Option<(usize, usize)>,
716}
717
718/// Vim-style options surfaced by `:set`. New fields land here as
719/// individual ex commands gain `:set` plumbing.
720#[derive(Debug, Clone)]
721pub struct Settings {
722    /// Spaces per shift step for `>>` / `<<` / `Ctrl-T` / `Ctrl-D`.
723    pub shiftwidth: usize,
724    /// Visual width of a `\t` character. Stored for future render
725    /// hookup; not yet consumed by the buffer renderer.
726    pub tabstop: usize,
727    /// When true, `/` / `?` patterns and `:s/.../.../` ignore case
728    /// without an explicit `i` flag.
729    pub ignore_case: bool,
730    /// When true *and* `ignore_case` is true, an uppercase letter in
731    /// the pattern flips that search back to case-sensitive. Matches
732    /// vim's `:set smartcase`. Default `false`.
733    pub smartcase: bool,
734    /// Wrap searches past buffer ends. Matches vim's `:set wrapscan`.
735    /// Default `true`.
736    pub wrapscan: bool,
737    /// Wrap column for `gq{motion}` text reflow. Vim's default is 79.
738    pub textwidth: usize,
739    /// When `true`, the Tab key in insert mode inserts `tabstop` spaces
740    /// instead of a literal `\t`. Matches vim's `:set expandtab`.
741    /// Default `false`.
742    pub expandtab: bool,
743    /// Soft tab stop in spaces. When `> 0`, Tab inserts spaces to the
744    /// next softtabstop boundary (when `expandtab`), and Backspace at the
745    /// end of a softtabstop-aligned space run deletes the entire run as
746    /// if it were one tab. `0` disables. Matches vim's `:set softtabstop`.
747    pub softtabstop: usize,
748    /// Soft-wrap mode the renderer + scroll math + `gj` / `gk` use.
749    /// Default is [`hjkl_buffer::Wrap::None`] — long lines extend
750    /// past the right edge and `top_col` clips the left side.
751    /// `:set wrap` flips to char-break wrap; `:set linebreak` flips
752    /// to word-break wrap; `:set nowrap` resets.
753    pub wrap: hjkl_buffer::Wrap,
754    /// When true, the engine drops every edit before it touches the
755    /// buffer — undo, dirty flag, and change log all stay clean.
756    /// Matches vim's `:set readonly` / `:set ro`. Default `false`.
757    pub readonly: bool,
758    /// When `true`, pressing Enter in insert mode copies the leading
759    /// whitespace of the current line onto the new line. Matches vim's
760    /// `:set autoindent`. Default `true` (vim parity).
761    pub autoindent: bool,
762    /// When `true`, bumps indent by one `shiftwidth` after a line ending
763    /// in `{` / `(` / `[`, and strips one indent unit when the user types
764    /// `}` / `)` / `]` on a whitespace-only line. See `compute_enter_indent`
765    /// in `vim.rs` for the tree-sitter plug-in seam. Default `true`.
766    pub smartindent: bool,
767    /// Cap on undo-stack length. Older entries are pruned past this
768    /// bound. `0` means unlimited. Matches vim's `:set undolevels`.
769    /// Default `1000`.
770    pub undo_levels: u32,
771    /// When `true`, cursor motions inside insert mode break the
772    /// current undo group (so a single `u` only reverses the run of
773    /// keystrokes that preceded the motion). Default `true`.
774    /// Currently a no-op — engine doesn't yet break the undo group
775    /// on insert-mode motions; field is wired through `:set
776    /// undobreak` for forward compatibility.
777    pub undo_break_on_motion: bool,
778    /// Vim-flavoured "what counts as a word" character class.
779    /// Comma-separated tokens: `@` = `is_alphabetic()`, `_` = literal
780    /// `_`, `48-57` = decimal char range, bare integer = single char
781    /// code, single ASCII punctuation = literal. Default
782    /// `"@,48-57,_,192-255"` matches vim.
783    pub iskeyword: String,
784    /// Multi-key sequence timeout (e.g. `gg`, `dd`). When the user
785    /// pauses longer than this between keys, any pending prefix is
786    /// abandoned and the next key starts a fresh sequence. Matches
787    /// vim's `:set timeoutlen` / `:set tm` (millis). Default 1000ms.
788    pub timeout_len: core::time::Duration,
789    /// When true, render absolute line numbers in the gutter. Matches
790    /// vim's `:set number` / `:set nu`. Default `true`.
791    pub number: bool,
792    /// When true, render line numbers as offsets from the cursor row.
793    /// Combined with `number`, the cursor row shows its absolute number
794    /// while other rows show the relative offset (vim's `nu+rnu` hybrid).
795    /// Matches vim's `:set relativenumber` / `:set rnu`. Default `false`.
796    pub relativenumber: bool,
797    /// Minimum gutter width in cells for the line-number column.
798    /// Width grows past this to fit the largest displayed number.
799    /// Matches vim's `:set numberwidth` / `:set nuw`. Default `4`.
800    /// Range 1..=20.
801    pub numberwidth: usize,
802    /// Highlight the row where the cursor sits. Matches vim's `:set cursorline`.
803    /// Default `false`.
804    pub cursorline: bool,
805    /// Highlight the column where the cursor sits. Matches vim's `:set cursorcolumn`.
806    /// Default `false`.
807    pub cursorcolumn: bool,
808    /// Sign-column display mode. Matches vim's `:set signcolumn`.
809    /// Default [`crate::types::SignColumnMode::Auto`].
810    pub signcolumn: crate::types::SignColumnMode,
811    /// Number of cells reserved for a fold-marker gutter.
812    /// Matches vim's `:set foldcolumn`. Default `0`.
813    pub foldcolumn: u32,
814    /// Comma-separated 1-based column indices for vertical rulers.
815    /// Matches vim's `:set colorcolumn`. Default `""`.
816    pub colorcolumn: String,
817}
818
819impl Default for Settings {
820    fn default() -> Self {
821        Self {
822            shiftwidth: 4,
823            tabstop: 4,
824            softtabstop: 4,
825            ignore_case: false,
826            smartcase: false,
827            wrapscan: true,
828            textwidth: 79,
829            expandtab: true,
830            wrap: hjkl_buffer::Wrap::None,
831            readonly: false,
832            autoindent: true,
833            smartindent: true,
834            undo_levels: 1000,
835            undo_break_on_motion: true,
836            iskeyword: "@,48-57,_,192-255".to_string(),
837            timeout_len: core::time::Duration::from_millis(1000),
838            number: true,
839            relativenumber: false,
840            numberwidth: 4,
841            cursorline: false,
842            cursorcolumn: false,
843            signcolumn: crate::types::SignColumnMode::Auto,
844            foldcolumn: 0,
845            colorcolumn: String::new(),
846        }
847    }
848}
849
850/// Translate a SPEC [`crate::types::Options`] into the engine's
851/// internal [`Settings`] representation. Field-by-field map; the
852/// shapes are isomorphic except for type widths
853/// (`u32` vs `usize`, [`crate::types::WrapMode`] vs
854/// [`hjkl_buffer::Wrap`]). 0.1.0 (Patch C-δ) collapses both into one
855/// type once the `Editor<B, H>::new(buffer, host, options)` constructor
856/// is the canonical entry point.
857fn settings_from_options(o: &crate::types::Options) -> Settings {
858    Settings {
859        shiftwidth: o.shiftwidth as usize,
860        tabstop: o.tabstop as usize,
861        softtabstop: o.softtabstop as usize,
862        ignore_case: o.ignorecase,
863        smartcase: o.smartcase,
864        wrapscan: o.wrapscan,
865        textwidth: o.textwidth as usize,
866        expandtab: o.expandtab,
867        wrap: match o.wrap {
868            crate::types::WrapMode::None => hjkl_buffer::Wrap::None,
869            crate::types::WrapMode::Char => hjkl_buffer::Wrap::Char,
870            crate::types::WrapMode::Word => hjkl_buffer::Wrap::Word,
871        },
872        readonly: o.readonly,
873        autoindent: o.autoindent,
874        smartindent: o.smartindent,
875        undo_levels: o.undo_levels,
876        undo_break_on_motion: o.undo_break_on_motion,
877        iskeyword: o.iskeyword.clone(),
878        timeout_len: o.timeout_len,
879        number: o.number,
880        relativenumber: o.relativenumber,
881        numberwidth: o.numberwidth,
882        cursorline: o.cursorline,
883        cursorcolumn: o.cursorcolumn,
884        signcolumn: o.signcolumn,
885        foldcolumn: o.foldcolumn,
886        colorcolumn: o.colorcolumn.clone(),
887    }
888}
889
890/// Host-observable LSP requests triggered by editor bindings. The
891/// hjkl-engine crate doesn't talk to an LSP itself — it just raises an
892/// intent that the TUI layer picks up and routes to `sqls`.
893#[derive(Debug, Clone, Copy, PartialEq, Eq)]
894pub enum LspIntent {
895    /// `gd` — textDocument/definition at the cursor.
896    GotoDefinition,
897}
898
899impl<H: crate::types::Host> Editor<hjkl_buffer::Buffer, H> {
900    /// Build an [`Editor`] from a buffer, host adapter, and SPEC options.
901    ///
902    /// 0.1.0 (Patch C-δ): canonical, frozen constructor per SPEC §"Editor
903    /// surface". Replaces the pre-0.1.0 `Editor::new(KeybindingMode)` /
904    /// `with_host` / `with_options` triad — there is no shim.
905    ///
906    /// Consumers that don't need a custom host pass
907    /// [`crate::types::DefaultHost::new()`]; consumers that don't need
908    /// custom options pass [`crate::types::Options::default()`].
909    pub fn new(buffer: hjkl_buffer::Buffer, host: H, options: crate::types::Options) -> Self {
910        let settings = settings_from_options(&options);
911        Self {
912            keybinding_mode: KeybindingMode::Vim,
913            last_yank: None,
914            vim: VimState::default(),
915            undo_stack: Vec::new(),
916            redo_stack: Vec::new(),
917            content_dirty: false,
918            cached_content: None,
919            viewport_height: AtomicU16::new(0),
920            pending_lsp: None,
921            pending_fold_ops: Vec::new(),
922            buffer,
923            #[cfg(feature = "ratatui")]
924            style_table: Vec::new(),
925            #[cfg(not(feature = "ratatui"))]
926            engine_style_table: Vec::new(),
927            registers: crate::registers::Registers::default(),
928            #[cfg(feature = "ratatui")]
929            styled_spans: Vec::new(),
930            settings,
931            marks: std::collections::BTreeMap::new(),
932            syntax_fold_ranges: Vec::new(),
933            change_log: Vec::new(),
934            sticky_col: None,
935            host,
936            last_emitted_mode: crate::VimMode::Normal,
937            search_state: crate::search::SearchState::new(),
938            buffer_spans: Vec::new(),
939            pending_content_edits: Vec::new(),
940            pending_content_reset: false,
941            last_indent_range: None,
942        }
943    }
944}
945
946impl<B: crate::types::Buffer, H: crate::types::Host> Editor<B, H> {
947    /// Borrow the buffer (typed `&B`). Host renders through this via
948    /// `hjkl_buffer::BufferView` when `B = hjkl_buffer::Buffer`.
949    pub fn buffer(&self) -> &B {
950        &self.buffer
951    }
952
953    /// Mutably borrow the buffer (typed `&mut B`).
954    pub fn buffer_mut(&mut self) -> &mut B {
955        &mut self.buffer
956    }
957
958    /// Borrow the host adapter directly (typed `&H`).
959    pub fn host(&self) -> &H {
960        &self.host
961    }
962
963    /// Mutably borrow the host adapter (typed `&mut H`).
964    pub fn host_mut(&mut self) -> &mut H {
965        &mut self.host
966    }
967}
968
969impl<H: crate::types::Host> Editor<hjkl_buffer::Buffer, H> {
970    /// Update the active `iskeyword` spec for word motions
971    /// (`w`/`b`/`e`/`ge` and engine-side `*`/`#` pickup). 0.0.28
972    /// hoisted iskeyword storage out of `Buffer` — `Editor` is the
973    /// single owner now. Equivalent to assigning
974    /// `settings_mut().iskeyword` directly; the dedicated setter is
975    /// retained for source-compatibility with 0.0.27 callers.
976    pub fn set_iskeyword(&mut self, spec: impl Into<String>) {
977        self.settings.iskeyword = spec.into();
978    }
979
980    /// Emit `Host::emit_cursor_shape` if the public mode has changed
981    /// since the last emit. Engine calls this at the end of every input
982    /// step so mode transitions surface to the host without sprinkling
983    /// the call across every `vim.mode = ...` site.
984    pub fn emit_cursor_shape_if_changed(&mut self) {
985        let mode = self.vim_mode();
986        if mode == self.last_emitted_mode {
987            return;
988        }
989        let shape = match mode {
990            crate::VimMode::Insert => crate::types::CursorShape::Bar,
991            _ => crate::types::CursorShape::Block,
992        };
993        self.host.emit_cursor_shape(shape);
994        self.last_emitted_mode = mode;
995    }
996
997    /// Record a yank/cut payload. Writes both the legacy
998    /// [`Editor::last_yank`] field (drained directly by 0.0.28-era
999    /// hosts) and the new [`crate::types::Host::write_clipboard`]
1000    /// side-channel (Patch B). Consumers should migrate to a `Host`
1001    /// impl whose `write_clipboard` queues the platform-clipboard
1002    /// write; the `last_yank` mirror will be removed at 0.1.0.
1003    pub(crate) fn record_yank_to_host(&mut self, text: String) {
1004        self.host.write_clipboard(text.clone());
1005        self.last_yank = Some(text);
1006    }
1007
1008    /// Vim's sticky column (curswant). `None` before the first motion;
1009    /// hosts shouldn't normally need to read this directly — it's
1010    /// surfaced for migration off `Buffer::sticky_col` and for
1011    /// snapshot tests.
1012    pub fn sticky_col(&self) -> Option<usize> {
1013        self.sticky_col
1014    }
1015
1016    /// Replace the sticky column. Hosts should rarely touch this —
1017    /// motion code maintains it through the standard horizontal /
1018    /// vertical motion paths.
1019    pub fn set_sticky_col(&mut self, col: Option<usize>) {
1020        self.sticky_col = col;
1021    }
1022
1023    /// Host hook: replace the cached syntax-derived block ranges that
1024    /// `:foldsyntax` consumes. the host calls this on every re-parse;
1025    /// the cost is just a `Vec` swap.
1026    /// Look up a named mark by character. Returns `(row, col)` if
1027    /// set; `None` otherwise. Both lowercase (`'a`–`'z`) and
1028    /// uppercase (`'A`–`'Z`) marks live in the same unified
1029    /// [`Editor::marks`] map as of 0.0.36.
1030    pub fn mark(&self, c: char) -> Option<(usize, usize)> {
1031        self.marks.get(&c).copied()
1032    }
1033
1034    /// Set the named mark `c` to `(row, col)`. Used by the FSM's
1035    /// `m{a-zA-Z}` keystroke and by [`Editor::restore_snapshot`].
1036    pub fn set_mark(&mut self, c: char, pos: (usize, usize)) {
1037        self.marks.insert(c, pos);
1038    }
1039
1040    /// Remove the named mark `c` (no-op if unset).
1041    pub fn clear_mark(&mut self, c: char) {
1042        self.marks.remove(&c);
1043    }
1044
1045    /// Look up a buffer-local lowercase mark (`'a`–`'z`). Kept as a
1046    /// thin wrapper over [`Editor::mark`] for source compatibility
1047    /// with pre-0.0.36 callers; new code should call
1048    /// [`Editor::mark`] directly.
1049    #[deprecated(
1050        since = "0.0.36",
1051        note = "use Editor::mark — lowercase + uppercase marks now live in a single map"
1052    )]
1053    pub fn buffer_mark(&self, c: char) -> Option<(usize, usize)> {
1054        self.mark(c)
1055    }
1056
1057    /// Discard the most recent undo entry. Used by ex commands that
1058    /// pre-emptively pushed an undo state (`:s`, `:r`) but ended up
1059    /// matching nothing — popping prevents a no-op undo step from
1060    /// polluting the user's history.
1061    ///
1062    /// Returns `true` if an entry was discarded.
1063    pub fn pop_last_undo(&mut self) -> bool {
1064        self.undo_stack.pop().is_some()
1065    }
1066
1067    /// Read all named marks set this session — both lowercase
1068    /// (`'a`–`'z`) and uppercase (`'A`–`'Z`). Iteration is
1069    /// deterministic (BTreeMap-ordered) so snapshot / `:marks`
1070    /// output is stable.
1071    pub fn marks(&self) -> impl Iterator<Item = (char, (usize, usize))> + '_ {
1072        self.marks.iter().map(|(c, p)| (*c, *p))
1073    }
1074
1075    /// Read all buffer-local lowercase marks. Kept for source
1076    /// compatibility with pre-0.0.36 callers (e.g. `:marks` ex
1077    /// command); new code should use [`Editor::marks`] which
1078    /// iterates the unified map.
1079    #[deprecated(
1080        since = "0.0.36",
1081        note = "use Editor::marks — lowercase + uppercase marks now live in a single map"
1082    )]
1083    pub fn buffer_marks(&self) -> impl Iterator<Item = (char, (usize, usize))> + '_ {
1084        self.marks
1085            .iter()
1086            .filter(|(c, _)| c.is_ascii_lowercase())
1087            .map(|(c, p)| (*c, *p))
1088    }
1089
1090    /// Position the cursor was at when the user last jumped via
1091    /// `<C-o>` / `g;` / similar. `None` before any jump.
1092    pub fn last_jump_back(&self) -> Option<(usize, usize)> {
1093        self.vim.jump_back.last().copied()
1094    }
1095
1096    /// Position of the last edit (where `.` would replay). `None` if
1097    /// no edit has happened yet in this session.
1098    pub fn last_edit_pos(&self) -> Option<(usize, usize)> {
1099        self.vim.last_edit_pos
1100    }
1101
1102    /// Read-only view of the file-marks table — uppercase / "file"
1103    /// marks (`'A`–`'Z`) the host has set this session. Returns an
1104    /// iterator of `(mark_char, (row, col))` pairs.
1105    ///
1106    /// Mutate via the FSM (`m{A-Z}` keystroke) or via
1107    /// [`Editor::restore_snapshot`].
1108    ///
1109    /// 0.0.36: file marks now live in the unified [`Editor::marks`]
1110    /// map; this accessor is kept for source compatibility and
1111    /// filters the unified map to uppercase entries.
1112    pub fn file_marks(&self) -> impl Iterator<Item = (char, (usize, usize))> + '_ {
1113        self.marks
1114            .iter()
1115            .filter(|(c, _)| c.is_ascii_uppercase())
1116            .map(|(c, p)| (*c, *p))
1117    }
1118
1119    /// Read-only view of the cached syntax-derived block ranges that
1120    /// `:foldsyntax` consumes. Returns the slice the host last
1121    /// installed via [`Editor::set_syntax_fold_ranges`]; empty when
1122    /// no syntax integration is active.
1123    pub fn syntax_fold_ranges(&self) -> &[(usize, usize)] {
1124        &self.syntax_fold_ranges
1125    }
1126
1127    pub fn set_syntax_fold_ranges(&mut self, ranges: Vec<(usize, usize)>) {
1128        self.syntax_fold_ranges = ranges;
1129    }
1130
1131    /// Live settings (read-only). `:set` mutates these via
1132    /// [`Editor::settings_mut`].
1133    pub fn settings(&self) -> &Settings {
1134        &self.settings
1135    }
1136
1137    /// Live settings (mutable). `:set` flows through here to mutate
1138    /// shiftwidth / tabstop / textwidth / ignore_case / wrap. Hosts
1139    /// configuring at startup typically construct a [`Settings`]
1140    /// snapshot and overwrite via `*editor.settings_mut() = …`.
1141    pub fn settings_mut(&mut self) -> &mut Settings {
1142        &mut self.settings
1143    }
1144
1145    /// Returns `true` when `:set readonly` is active. Convenience
1146    /// accessor for hosts that cannot import the internal [`Settings`]
1147    /// type. Phase 5 binary uses this to gate `:w` writes.
1148    pub fn is_readonly(&self) -> bool {
1149        self.settings.readonly
1150    }
1151
1152    /// Borrow the engine search state. Hosts inspecting the
1153    /// committed `/` / `?` pattern (e.g. for status-line display) or
1154    /// feeding the active regex into `BufferView::search_pattern`
1155    /// read it from here.
1156    pub fn search_state(&self) -> &crate::search::SearchState {
1157        &self.search_state
1158    }
1159
1160    /// Mutable engine search state. Hosts driving search
1161    /// programmatically (test fixtures, scripted demos) write the
1162    /// pattern through here.
1163    pub fn search_state_mut(&mut self) -> &mut crate::search::SearchState {
1164        &mut self.search_state
1165    }
1166
1167    /// Install `pattern` as the active search regex on the engine
1168    /// state and clear the cached row matches. Pass `None` to clear.
1169    /// 0.0.37: dropped the buffer-side mirror that 0.0.35 introduced
1170    /// — `BufferView` now takes the regex through its `search_pattern`
1171    /// field per step 3 of `DESIGN_33_METHOD_CLASSIFICATION.md`.
1172    pub fn set_search_pattern(&mut self, pattern: Option<regex::Regex>) {
1173        self.search_state.set_pattern(pattern);
1174    }
1175
1176    /// Drive `n` (or the `/` commit equivalent) — advance the cursor
1177    /// to the next match of `search_state.pattern` from the cursor's
1178    /// current position. Returns `true` when a match was found.
1179    /// `skip_current = true` excludes a match the cursor sits on.
1180    pub fn search_advance_forward(&mut self, skip_current: bool) -> bool {
1181        crate::search::search_forward(&mut self.buffer, &mut self.search_state, skip_current)
1182    }
1183
1184    /// Drive `N` — symmetric counterpart of [`Editor::search_advance_forward`].
1185    pub fn search_advance_backward(&mut self, skip_current: bool) -> bool {
1186        crate::search::search_backward(&mut self.buffer, &mut self.search_state, skip_current)
1187    }
1188
1189    /// Install styled syntax spans using `ratatui::style::Style`. The
1190    /// ratatui-flavoured variant of [`Editor::install_syntax_spans`].
1191    /// Drops zero-width runs and clamps `end` to the line's char length
1192    /// so the buffer cache doesn't see runaway ranges. Behind the
1193    /// `ratatui` feature; non-ratatui hosts use the unprefixed
1194    /// [`Editor::install_syntax_spans`] (engine-native `Style`).
1195    ///
1196    /// Renamed from `install_syntax_spans` in 0.0.32 — the unprefixed
1197    /// name now belongs to the engine-native variant per SPEC 0.1.0
1198    /// freeze ("engine never imports ratatui").
1199    #[cfg(feature = "ratatui")]
1200    pub fn install_ratatui_syntax_spans(
1201        &mut self,
1202        spans: Vec<Vec<(usize, usize, ratatui::style::Style)>>,
1203    ) {
1204        // Look up `line_byte_lens` lazily — only fetch a row's length
1205        // when it has at least one span. On a 100k-line file with
1206        // ~50 visible rows, this avoids an O(N) buffer walk per frame.
1207        let mut by_row: Vec<Vec<hjkl_buffer::Span>> = Vec::with_capacity(spans.len());
1208        for (row, row_spans) in spans.iter().enumerate() {
1209            if row_spans.is_empty() {
1210                by_row.push(Vec::new());
1211                continue;
1212            }
1213            let line_len = buf_line(&self.buffer, row).map(str::len).unwrap_or(0);
1214            let mut translated = Vec::with_capacity(row_spans.len());
1215            for (start, end, style) in row_spans {
1216                let end_clamped = (*end).min(line_len);
1217                if end_clamped <= *start {
1218                    continue;
1219                }
1220                let id = self.intern_ratatui_style(*style);
1221                translated.push(hjkl_buffer::Span::new(*start, end_clamped, id));
1222            }
1223            by_row.push(translated);
1224        }
1225        self.buffer_spans = by_row;
1226        self.styled_spans = spans;
1227    }
1228
1229    /// Snapshot of the unnamed register (the default `p` / `P` source).
1230    pub fn yank(&self) -> &str {
1231        &self.registers.unnamed.text
1232    }
1233
1234    /// Borrow the full register bank — `"`, `"0`–`"9`, `"a`–`"z`.
1235    pub fn registers(&self) -> &crate::registers::Registers {
1236        &self.registers
1237    }
1238
1239    /// Mutably borrow the full register bank. Hosts that share registers
1240    /// across multiple editors (e.g. multi-buffer `yy` / `p`) overwrite
1241    /// the slots here on buffer switch.
1242    pub fn registers_mut(&mut self) -> &mut crate::registers::Registers {
1243        &mut self.registers
1244    }
1245
1246    /// Host hook: load the OS clipboard's contents into the `"+` / `"*`
1247    /// register slot. the host calls this before letting vim consume a
1248    /// paste so `"*p` / `"+p` reflect the live clipboard rather than a
1249    /// stale snapshot from the last yank.
1250    pub fn sync_clipboard_register(&mut self, text: String, linewise: bool) {
1251        self.registers.set_clipboard(text, linewise);
1252    }
1253
1254    /// Return the user's pending register selection (set via `"<reg>` chord
1255    /// before an operator). `None` if no register was selected — caller should
1256    /// use the unnamed register `"`.
1257    ///
1258    /// Read-only — does not consume / clear the pending selection. The
1259    /// register is cleared by the engine after the next operator fires.
1260    ///
1261    /// Promoted in 0.6.X for Phase 4e to let the App's visual-op dispatch arm
1262    /// honor `"a` + visual op chord sequences.
1263    pub fn pending_register(&self) -> Option<char> {
1264        self.vim.pending_register
1265    }
1266
1267    /// True when the user's pending register selector is `+` or `*`.
1268    /// the host peeks this so it can refresh `sync_clipboard_register`
1269    /// only when a clipboard read is actually about to happen.
1270    pub fn pending_register_is_clipboard(&self) -> bool {
1271        matches!(self.vim.pending_register, Some('+') | Some('*'))
1272    }
1273
1274    /// Register currently being recorded into via `q{reg}`. `None` when
1275    /// no recording is active. Hosts use this to surface a "recording @r"
1276    /// indicator in the status line.
1277    pub fn recording_register(&self) -> Option<char> {
1278        self.vim.recording_macro
1279    }
1280
1281    /// Pending repeat count the user has typed but not yet resolved
1282    /// (e.g. pressing `5` before `d`). `None` when nothing is pending.
1283    /// Hosts surface this in a "showcmd" area.
1284    pub fn pending_count(&self) -> Option<u32> {
1285        self.vim.pending_count_val()
1286    }
1287
1288    /// The operator character for any in-flight operator that is waiting
1289    /// for a motion (e.g. `d` after the user types `d` but before a
1290    /// motion). Returns `None` when no operator is pending.
1291    pub fn pending_op(&self) -> Option<char> {
1292        self.vim.pending_op_char()
1293    }
1294
1295    /// `true` when the engine is in any pending chord state — waiting for
1296    /// the next key to complete a command (e.g. `r<char>` replace,
1297    /// `f<char>` find, `m<a>` set-mark, `'<a>` goto-mark, operator-pending
1298    /// after `d` / `c` / `y`, `g`-prefix continuation, `z`-prefix continuation,
1299    /// register selection `"<reg>`, macro recording target, etc).
1300    ///
1301    /// Hosts use this to bypass their own chord dispatch (keymap tries, etc.)
1302    /// and forward keys directly to the engine so in-flight commands can
1303    /// complete without the host eating their continuation keys.
1304    pub fn is_chord_pending(&self) -> bool {
1305        self.vim.is_chord_pending()
1306    }
1307
1308    /// `true` when `insert_ctrl_r_arm()` has been called and the dispatcher
1309    /// is waiting for the next typed character to name the register to paste.
1310    /// The dispatcher should call `insert_paste_register(c)` instead of
1311    /// `insert_char(c)` for the next printable key, then the flag auto-clears.
1312    ///
1313    /// Phase 6.5: exposed so the app-level `dispatch_insert_key` can branch
1314    /// without having to drive the full FSM.
1315    pub fn is_insert_register_pending(&self) -> bool {
1316        self.vim.insert_pending_register
1317    }
1318
1319    /// Clear the `Ctrl-R` register-paste pending flag. Call this immediately
1320    /// before `insert_paste_register(c)` in app-level dispatchers so that the
1321    /// flag does not persist into the next key. Call before
1322    /// `insert_paste_register_bridge` (which `hjkl_vim::insert` does).
1323    ///
1324    /// Phase 6.5: used by `dispatch_insert_key` in the app crate.
1325    pub fn clear_insert_register_pending(&mut self) {
1326        self.vim.insert_pending_register = false;
1327    }
1328
1329    /// Read-only view of the jump-back list (positions pushed on "big"
1330    /// motions). Newest entry is at the back — `Ctrl-o` pops from there.
1331    #[allow(clippy::type_complexity)]
1332    pub fn jump_list(&self) -> (&[(usize, usize)], &[(usize, usize)]) {
1333        (&self.vim.jump_back, &self.vim.jump_fwd)
1334    }
1335
1336    /// Read-only view of the change list (positions of recent edits) plus
1337    /// the current walk cursor. Newest entry is at the back.
1338    pub fn change_list(&self) -> (&[(usize, usize)], Option<usize>) {
1339        (&self.vim.change_list, self.vim.change_list_cursor)
1340    }
1341
1342    /// Replace the unnamed register without touching any other slot.
1343    /// For host-driven imports (e.g. system clipboard); operator
1344    /// code uses [`record_yank`] / [`record_delete`].
1345    pub fn set_yank(&mut self, text: impl Into<String>) {
1346        let text = text.into();
1347        let linewise = self.vim.yank_linewise;
1348        self.registers.unnamed = crate::registers::Slot { text, linewise };
1349    }
1350
1351    /// Record a yank into `"` and `"0`, plus the named target if the
1352    /// user prefixed `"reg`. Updates `vim.yank_linewise` for the
1353    /// paste path.
1354    pub(crate) fn record_yank(&mut self, text: String, linewise: bool) {
1355        self.vim.yank_linewise = linewise;
1356        let target = self.vim.pending_register.take();
1357        self.registers.record_yank(text, linewise, target);
1358    }
1359
1360    /// Direct write to a named register slot — bypasses the unnamed
1361    /// `"` and `"0` updates that `record_yank` does. Used by the
1362    /// macro recorder so finishing a `q{reg}` recording doesn't
1363    /// pollute the user's last yank.
1364    pub(crate) fn set_named_register_text(&mut self, reg: char, text: String) {
1365        if let Some(slot) = match reg {
1366            'a'..='z' => Some(&mut self.registers.named[(reg as u8 - b'a') as usize]),
1367            'A'..='Z' => {
1368                Some(&mut self.registers.named[(reg.to_ascii_lowercase() as u8 - b'a') as usize])
1369            }
1370            _ => None,
1371        } {
1372            slot.text = text;
1373            slot.linewise = false;
1374        }
1375    }
1376
1377    /// Record a delete / change into `"` and the `"1`–`"9` ring.
1378    /// Honours the active named-register prefix.
1379    pub(crate) fn record_delete(&mut self, text: String, linewise: bool) {
1380        self.vim.yank_linewise = linewise;
1381        let target = self.vim.pending_register.take();
1382        self.registers.record_delete(text, linewise, target);
1383    }
1384
1385    /// Install styled syntax spans using the engine-native
1386    /// [`crate::types::Style`]. Always available, regardless of the
1387    /// `ratatui` feature. Hosts depending on ratatui can use the
1388    /// ratatui-flavoured [`Editor::install_ratatui_syntax_spans`].
1389    ///
1390    /// Renamed from `install_engine_syntax_spans` in 0.0.32 — at the
1391    /// 0.1.0 freeze the unprefixed name is the universally-available
1392    /// engine-native variant ("engine never imports ratatui").
1393    pub fn install_syntax_spans(&mut self, spans: Vec<Vec<(usize, usize, crate::types::Style)>>) {
1394        let line_byte_lens: Vec<usize> = (0..buf_row_count(&self.buffer))
1395            .map(|r| buf_line(&self.buffer, r).map(str::len).unwrap_or(0))
1396            .collect();
1397        let mut by_row: Vec<Vec<hjkl_buffer::Span>> = Vec::with_capacity(spans.len());
1398        #[cfg(feature = "ratatui")]
1399        let mut ratatui_spans: Vec<Vec<(usize, usize, ratatui::style::Style)>> =
1400            Vec::with_capacity(spans.len());
1401        for (row, row_spans) in spans.iter().enumerate() {
1402            let line_len = line_byte_lens.get(row).copied().unwrap_or(0);
1403            let mut translated = Vec::with_capacity(row_spans.len());
1404            #[cfg(feature = "ratatui")]
1405            let mut translated_r = Vec::with_capacity(row_spans.len());
1406            for (start, end, style) in row_spans {
1407                let end_clamped = (*end).min(line_len);
1408                if end_clamped <= *start {
1409                    continue;
1410                }
1411                let id = self.intern_style(*style);
1412                translated.push(hjkl_buffer::Span::new(*start, end_clamped, id));
1413                #[cfg(feature = "ratatui")]
1414                translated_r.push((*start, end_clamped, engine_style_to_ratatui(*style)));
1415            }
1416            by_row.push(translated);
1417            #[cfg(feature = "ratatui")]
1418            ratatui_spans.push(translated_r);
1419        }
1420        self.buffer_spans = by_row;
1421        #[cfg(feature = "ratatui")]
1422        {
1423            self.styled_spans = ratatui_spans;
1424        }
1425    }
1426
1427    /// Intern a `ratatui::style::Style` and return the opaque id used
1428    /// in `hjkl_buffer::Span::style`. The ratatui-flavoured variant of
1429    /// [`Editor::intern_style`]. Linear-scan dedup — the table grows
1430    /// only as new tree-sitter token kinds appear, so it stays tiny.
1431    /// Behind the `ratatui` feature.
1432    ///
1433    /// Renamed from `intern_style` in 0.0.32 — at 0.1.0 freeze the
1434    /// unprefixed name belongs to the engine-native variant.
1435    #[cfg(feature = "ratatui")]
1436    pub fn intern_ratatui_style(&mut self, style: ratatui::style::Style) -> u32 {
1437        if let Some(idx) = self.style_table.iter().position(|s| *s == style) {
1438            return idx as u32;
1439        }
1440        self.style_table.push(style);
1441        (self.style_table.len() - 1) as u32
1442    }
1443
1444    /// Read-only view of the style table — id `i` → `style_table[i]`.
1445    /// The render path passes a closure backed by this slice as the
1446    /// `StyleResolver` for `BufferView`. Behind the `ratatui` feature.
1447    #[cfg(feature = "ratatui")]
1448    pub fn style_table(&self) -> &[ratatui::style::Style] {
1449        &self.style_table
1450    }
1451
1452    /// Per-row syntax span overlay, one `Vec<Span>` per buffer row.
1453    /// Hosts feed this slice into [`hjkl_buffer::BufferView::spans`]
1454    /// per draw frame.
1455    ///
1456    /// 0.0.37: replaces `editor.buffer().spans()` per step 3 of
1457    /// `DESIGN_33_METHOD_CLASSIFICATION.md`. The buffer no longer
1458    /// caches spans; they live on the engine and route through the
1459    /// `Host::syntax_highlights` pipeline.
1460    pub fn buffer_spans(&self) -> &[Vec<hjkl_buffer::Span>] {
1461        &self.buffer_spans
1462    }
1463
1464    /// Intern a SPEC [`crate::types::Style`] and return its opaque id.
1465    /// With the `ratatui` feature on, the id matches the one
1466    /// [`Editor::intern_ratatui_style`] would return for the equivalent
1467    /// `ratatui::Style` (both share the underlying table). With it off,
1468    /// the engine keeps a parallel `crate::types::Style`-keyed table
1469    /// — ids are still stable per-editor.
1470    ///
1471    /// Hosts that don't depend on ratatui (buffr, future GUI shells)
1472    /// reach this method to populate the table during syntax span
1473    /// installation.
1474    ///
1475    /// Renamed from `intern_engine_style` in 0.0.32 — at 0.1.0 freeze
1476    /// the unprefixed name is the universally-available engine-native
1477    /// variant.
1478    pub fn intern_style(&mut self, style: crate::types::Style) -> u32 {
1479        #[cfg(feature = "ratatui")]
1480        {
1481            let r = engine_style_to_ratatui(style);
1482            self.intern_ratatui_style(r)
1483        }
1484        #[cfg(not(feature = "ratatui"))]
1485        {
1486            if let Some(idx) = self.engine_style_table.iter().position(|s| *s == style) {
1487                return idx as u32;
1488            }
1489            self.engine_style_table.push(style);
1490            (self.engine_style_table.len() - 1) as u32
1491        }
1492    }
1493
1494    /// Look up an interned style by id and return it as a SPEC
1495    /// [`crate::types::Style`]. Returns `None` for ids past the end
1496    /// of the table.
1497    pub fn engine_style_at(&self, id: u32) -> Option<crate::types::Style> {
1498        #[cfg(feature = "ratatui")]
1499        {
1500            let r = self.style_table.get(id as usize).copied()?;
1501            Some(ratatui_style_to_engine(r))
1502        }
1503        #[cfg(not(feature = "ratatui"))]
1504        {
1505            self.engine_style_table.get(id as usize).copied()
1506        }
1507    }
1508
1509    /// Historical reverse-sync hook from when the textarea mirrored
1510    /// the buffer. Now that Buffer is the cursor authority this is a
1511    /// no-op; call sites can remain in place during the migration.
1512    pub fn push_buffer_cursor_to_textarea(&mut self) {}
1513
1514    /// Force the host viewport's top row without touching the
1515    /// cursor. Used by tests that simulate a scroll without the
1516    /// SCROLLOFF cursor adjustment that `scroll_down` / `scroll_up`
1517    /// apply.
1518    ///
1519    /// 0.0.34 (Patch C-δ.1): writes through `Host::viewport_mut`
1520    /// instead of the (now-deleted) `Buffer::viewport_mut`.
1521    pub fn set_viewport_top(&mut self, row: usize) {
1522        let last = buf_row_count(&self.buffer).saturating_sub(1);
1523        let target = row.min(last);
1524        self.host.viewport_mut().top_row = target;
1525    }
1526
1527    /// Set the cursor to `(row, col)`, clamped to the buffer's
1528    /// content. Hosts use this for goto-line, jump-to-mark, and
1529    /// programmatic cursor placement.
1530    pub fn jump_cursor(&mut self, row: usize, col: usize) {
1531        buf_set_cursor_rc(&mut self.buffer, row, col);
1532    }
1533
1534    /// `(row, col)` cursor read sourced from the migration buffer.
1535    /// Equivalent to `self.textarea.cursor()` when the two are in
1536    /// sync — which is the steady state during Phase 7f because
1537    /// every step opens with `sync_buffer_content_from_textarea` and
1538    /// every ported motion pushes the result back. Prefer this over
1539    /// `self.textarea.cursor()` so call sites keep working unchanged
1540    /// once the textarea field is ripped.
1541    pub fn cursor(&self) -> (usize, usize) {
1542        buf_cursor_rc(&self.buffer)
1543    }
1544
1545    /// Drain any pending LSP intent raised by the last key. Returns
1546    /// `None` when no intent is armed.
1547    pub fn take_lsp_intent(&mut self) -> Option<LspIntent> {
1548        self.pending_lsp.take()
1549    }
1550
1551    /// Drain every [`crate::types::FoldOp`] raised since the last
1552    /// call. Hosts that mirror the engine's fold storage (or that
1553    /// project folds onto a separate fold tree, LSP folding ranges,
1554    /// …) drain this each step and dispatch as their own
1555    /// [`crate::types::Host::Intent`] requires.
1556    ///
1557    /// The engine has already applied every op locally against the
1558    /// in-tree [`hjkl_buffer::Buffer`] fold storage via
1559    /// [`crate::buffer_impl::BufferFoldProviderMut`], so hosts that
1560    /// don't track folds independently can ignore the queue
1561    /// (or simply never call this drain).
1562    ///
1563    /// Introduced in 0.0.38 (Patch C-δ.4).
1564    pub fn take_fold_ops(&mut self) -> Vec<crate::types::FoldOp> {
1565        std::mem::take(&mut self.pending_fold_ops)
1566    }
1567
1568    /// Dispatch a [`crate::types::FoldOp`] through the canonical fold
1569    /// surface: queue it for host observation (drained by
1570    /// [`Editor::take_fold_ops`]) and apply it locally against the
1571    /// in-tree buffer fold storage via
1572    /// [`crate::buffer_impl::BufferFoldProviderMut`]. Engine call sites
1573    /// (vim FSM `z…` chords, `:fold*` Ex commands, edit-pipeline
1574    /// invalidation) route every fold mutation through this method.
1575    ///
1576    /// Introduced in 0.0.38 (Patch C-δ.4).
1577    pub fn apply_fold_op(&mut self, op: crate::types::FoldOp) {
1578        use crate::types::FoldProvider;
1579        self.pending_fold_ops.push(op);
1580        let mut provider = crate::buffer_impl::BufferFoldProviderMut::new(&mut self.buffer);
1581        provider.apply(op);
1582    }
1583
1584    /// Refresh the host viewport's height from the cached
1585    /// `viewport_height_value()`. Called from the per-step
1586    /// boilerplate; was the textarea → buffer mirror before Phase 7f
1587    /// put Buffer in charge. 0.0.28 hoisted sticky_col out of
1588    /// `Buffer`. 0.0.34 (Patch C-δ.1) routes the height write through
1589    /// `Host::viewport_mut`.
1590    pub(crate) fn sync_buffer_from_textarea(&mut self) {
1591        let height = self.viewport_height_value();
1592        self.host.viewport_mut().height = height;
1593    }
1594
1595    /// Was the full textarea → buffer content sync. Buffer is the
1596    /// content authority now; this remains as a no-op so the per-step
1597    /// call sites don't have to be ripped in the same patch.
1598    pub(crate) fn sync_buffer_content_from_textarea(&mut self) {
1599        self.sync_buffer_from_textarea();
1600    }
1601
1602    /// Push a `(row, col)` onto the back-jumplist so `Ctrl-o` returns
1603    /// to it later. Used by host-driven jumps (e.g. `gd`) that move
1604    /// the cursor without going through the vim engine's motion
1605    /// machinery, where push_jump fires automatically.
1606    pub fn record_jump(&mut self, pos: (usize, usize)) {
1607        const JUMPLIST_MAX: usize = 100;
1608        self.vim.jump_back.push(pos);
1609        if self.vim.jump_back.len() > JUMPLIST_MAX {
1610            self.vim.jump_back.remove(0);
1611        }
1612        self.vim.jump_fwd.clear();
1613    }
1614
1615    /// Host apps call this each draw with the current text area height so
1616    /// scroll helpers can clamp the cursor without recomputing layout.
1617    pub fn set_viewport_height(&self, height: u16) {
1618        self.viewport_height.store(height, Ordering::Relaxed);
1619    }
1620
1621    /// Last height published by `set_viewport_height` (in rows).
1622    pub fn viewport_height_value(&self) -> u16 {
1623        self.viewport_height.load(Ordering::Relaxed)
1624    }
1625
1626    /// Apply `edit` against the buffer and return the inverse so the
1627    /// host can push it onto an undo stack. Side effects: dirty
1628    /// flag, change-list ring, mark / jump-list shifts, change_log
1629    /// append, fold invalidation around the touched rows.
1630    ///
1631    /// The primary edit funnel — both FSM operators and ex commands
1632    /// route mutations through here so the side effects fire
1633    /// uniformly.
1634    pub fn mutate_edit(&mut self, edit: hjkl_buffer::Edit) -> hjkl_buffer::Edit {
1635        // `:set readonly` short-circuits every mutation funnel: no
1636        // buffer change, no dirty flag, no undo entry, no change-log
1637        // emission. We swallow the requested `edit` and hand back a
1638        // self-inverse no-op (`InsertStr` of an empty string at the
1639        // current cursor) so callers that push the return value onto
1640        // an undo stack still get a structurally valid round trip.
1641        if self.settings.readonly {
1642            let _ = edit;
1643            return hjkl_buffer::Edit::InsertStr {
1644                at: buf_cursor_pos(&self.buffer),
1645                text: String::new(),
1646            };
1647        }
1648        let pre_row = buf_cursor_row(&self.buffer);
1649        let pre_rows = buf_row_count(&self.buffer);
1650        // Capture the pre-edit cursor for the dot mark (`'.` / `` `. ``).
1651        // Vim's `:h '.` says "the position where the last change was made",
1652        // meaning the change-start, not the post-insert cursor. We snap it
1653        // here before `apply_buffer_edit` moves the cursor.
1654        let (pre_edit_row, pre_edit_col) = buf_cursor_rc(&self.buffer);
1655        // Map the underlying buffer edit to a SPEC EditOp for
1656        // change-log emission before consuming it. Coarse — see
1657        // change_log field doc on the struct.
1658        self.change_log.extend(edit_to_editops(&edit));
1659        // Compute ContentEdit fan-out from the pre-edit buffer state.
1660        // Done before `apply_buffer_edit` consumes `edit` so we can
1661        // inspect the operation's fields and the buffer's pre-edit row
1662        // bytes (needed for byte_of_row / col_byte conversion). Edits
1663        // are pushed onto `pending_content_edits` for host drain.
1664        let content_edits = content_edits_from_buffer_edit(&self.buffer, &edit);
1665        self.pending_content_edits.extend(content_edits);
1666        // 0.0.42 (Patch C-δ.7): the `apply_edit` reach is centralized
1667        // in [`crate::buf_helpers::apply_buffer_edit`] (option (c) of
1668        // the 0.0.42 plan — see that fn's doc comment). The free fn
1669        // takes `&mut hjkl_buffer::Buffer` so the editor body itself
1670        // no longer carries a `self.buffer.<inherent>` hop.
1671        let inverse = apply_buffer_edit(&mut self.buffer, edit);
1672        let (pos_row, pos_col) = buf_cursor_rc(&self.buffer);
1673        // Drop any folds the edit's range overlapped — vim opens the
1674        // surrounding fold automatically when you edit inside it. The
1675        // approximation here invalidates folds covering either the
1676        // pre-edit cursor row or the post-edit cursor row, which
1677        // catches the common single-line / multi-line edit shapes.
1678        let lo = pre_row.min(pos_row);
1679        let hi = pre_row.max(pos_row);
1680        self.apply_fold_op(crate::types::FoldOp::Invalidate {
1681            start_row: lo,
1682            end_row: hi,
1683        });
1684        // Dot mark records the PRE-edit position (change start), matching
1685        // vim's `:h '.` semantics. Previously this stored the post-edit
1686        // cursor, which diverged from nvim on `iX<Esc>j`.
1687        self.vim.last_edit_pos = Some((pre_edit_row, pre_edit_col));
1688        // Append to the change-list ring (skip when the cursor sits on
1689        // the same cell as the last entry — back-to-back keystrokes on
1690        // one column shouldn't pollute the ring). A new edit while
1691        // walking the ring trims the forward half, vim style.
1692        let entry = (pos_row, pos_col);
1693        if self.vim.change_list.last() != Some(&entry) {
1694            if let Some(idx) = self.vim.change_list_cursor.take() {
1695                self.vim.change_list.truncate(idx + 1);
1696            }
1697            self.vim.change_list.push(entry);
1698            let len = self.vim.change_list.len();
1699            if len > crate::vim::CHANGE_LIST_MAX {
1700                self.vim
1701                    .change_list
1702                    .drain(0..len - crate::vim::CHANGE_LIST_MAX);
1703            }
1704        }
1705        self.vim.change_list_cursor = None;
1706        // Shift / drop marks + jump-list entries to track the row
1707        // delta the edit produced. Without this, every line-changing
1708        // edit silently invalidates `'a`-style positions.
1709        let post_rows = buf_row_count(&self.buffer);
1710        let delta = post_rows as isize - pre_rows as isize;
1711        if delta != 0 {
1712            self.shift_marks_after_edit(pre_row, delta);
1713        }
1714        self.push_buffer_content_to_textarea();
1715        self.mark_content_dirty();
1716        inverse
1717    }
1718
1719    /// Migrate user marks + jumplist entries when an edit at row
1720    /// `edit_start` changes the buffer's row count by `delta` (positive
1721    /// for inserts, negative for deletes). Marks tied to a deleted row
1722    /// are dropped; marks past the affected band shift by `delta`.
1723    fn shift_marks_after_edit(&mut self, edit_start: usize, delta: isize) {
1724        if delta == 0 {
1725            return;
1726        }
1727        // Deleted-row band (only meaningful for delta < 0). Inclusive
1728        // start, exclusive end.
1729        let drop_end = if delta < 0 {
1730            edit_start.saturating_add((-delta) as usize)
1731        } else {
1732            edit_start
1733        };
1734        let shift_threshold = drop_end.max(edit_start.saturating_add(1));
1735
1736        // 0.0.36: lowercase + uppercase marks share the unified
1737        // `marks` map; one pass migrates both.
1738        let mut to_drop: Vec<char> = Vec::new();
1739        for (c, (row, _col)) in self.marks.iter_mut() {
1740            if (edit_start..drop_end).contains(row) {
1741                to_drop.push(*c);
1742            } else if *row >= shift_threshold {
1743                *row = ((*row as isize) + delta).max(0) as usize;
1744            }
1745        }
1746        for c in to_drop {
1747            self.marks.remove(&c);
1748        }
1749
1750        let shift_jumps = |entries: &mut Vec<(usize, usize)>| {
1751            entries.retain(|(row, _)| !(edit_start..drop_end).contains(row));
1752            for (row, _) in entries.iter_mut() {
1753                if *row >= shift_threshold {
1754                    *row = ((*row as isize) + delta).max(0) as usize;
1755                }
1756            }
1757        };
1758        shift_jumps(&mut self.vim.jump_back);
1759        shift_jumps(&mut self.vim.jump_fwd);
1760    }
1761
1762    /// Reverse-sync helper paired with [`Editor::mutate_edit`]: rebuild
1763    /// the textarea from the buffer's lines + cursor, preserving yank
1764    /// text. Heavy (allocates a fresh `TextArea`) but correct; the
1765    /// textarea field disappears at the end of Phase 7f anyway.
1766    /// No-op since Buffer is the content authority. Retained as a
1767    /// shim so call sites in `mutate_edit` and friends don't have to
1768    /// be ripped in lockstep with the field removal.
1769    pub(crate) fn push_buffer_content_to_textarea(&mut self) {}
1770
1771    /// Single choke-point for "the buffer just changed". Sets the
1772    /// dirty flag and drops the cached `content_arc` snapshot so
1773    /// subsequent reads rebuild from the live textarea. Callers
1774    /// mutating `textarea` directly (e.g. the TUI's bracketed-paste
1775    /// path) must invoke this to keep the cache honest.
1776    pub fn mark_content_dirty(&mut self) {
1777        self.content_dirty = true;
1778        self.cached_content = None;
1779    }
1780
1781    /// Returns true if content changed since the last call, then clears the flag.
1782    pub fn take_dirty(&mut self) -> bool {
1783        let dirty = self.content_dirty;
1784        self.content_dirty = false;
1785        dirty
1786    }
1787
1788    /// Drain the queue of [`crate::types::ContentEdit`]s emitted since
1789    /// the last call. Each entry corresponds to a single buffer
1790    /// mutation funnelled through [`Editor::mutate_edit`]; block edits
1791    /// fan out to one entry per row touched.
1792    ///
1793    /// Hosts call this each frame (after [`Editor::take_content_reset`])
1794    /// to fan edits into a tree-sitter parser via `Tree::edit`.
1795    pub fn take_content_edits(&mut self) -> Vec<crate::types::ContentEdit> {
1796        std::mem::take(&mut self.pending_content_edits)
1797    }
1798
1799    /// Returns `true` if a bulk buffer replacement happened since the
1800    /// last call (e.g. `set_content` / `restore` / undo restore), then
1801    /// clears the flag. When this returns `true`, hosts should drop
1802    /// any retained syntax tree before consuming
1803    /// [`Editor::take_content_edits`].
1804    pub fn take_content_reset(&mut self) -> bool {
1805        let r = self.pending_content_reset;
1806        self.pending_content_reset = false;
1807        r
1808    }
1809
1810    /// Pull-model coarse change observation. If content changed since
1811    /// the last call, returns `Some(Arc<String>)` with the new content
1812    /// and clears the dirty flag; otherwise returns `None`.
1813    ///
1814    /// Hosts that need fine-grained edit deltas (e.g., DOM patching at
1815    /// the character level) should diff against their own previous
1816    /// snapshot. The SPEC `take_changes() -> Vec<EditOp>` API lands
1817    /// once every edit path inside the engine is instrumented; this
1818    /// coarse form covers the pull-model use case in the meantime.
1819    pub fn take_content_change(&mut self) -> Option<std::sync::Arc<String>> {
1820        if !self.content_dirty {
1821            return None;
1822        }
1823        let arc = self.content_arc();
1824        self.content_dirty = false;
1825        Some(arc)
1826    }
1827
1828    /// Returns the cursor's row within the visible textarea (0-based), updating
1829    /// the stored viewport top so subsequent calls remain accurate.
1830    pub fn cursor_screen_row(&mut self, height: u16) -> u16 {
1831        let cursor = buf_cursor_row(&self.buffer);
1832        let top = self.host.viewport().top_row;
1833        cursor.saturating_sub(top).min(height as usize - 1) as u16
1834    }
1835
1836    /// Returns the cursor's screen position `(x, y)` for the textarea
1837    /// described by `(area_x, area_y, area_width, area_height)`.
1838    /// Accounts for line-number gutter, viewport scroll, and any extra
1839    /// gutter width to the left of the number column (sign column, fold
1840    /// column). Returns `None` if the cursor is outside the visible
1841    /// viewport. Always available (engine-native; no ratatui dependency).
1842    ///
1843    /// `extra_gutter_width` is added to the number-column width before
1844    /// computing the cursor x position. Callers (e.g. `apps/hjkl/src/render.rs`)
1845    /// pass `sign_w + fold_w` here so the cursor lands on the correct cell
1846    /// when a dedicated sign or fold column is present.
1847    ///
1848    /// Renamed from `cursor_screen_pos_xywh` in 0.0.32 — the
1849    /// ratatui-flavoured `Rect` variant is now
1850    /// [`Editor::cursor_screen_pos_in_rect`] (cfg `ratatui`).
1851    pub fn cursor_screen_pos(
1852        &self,
1853        area_x: u16,
1854        area_y: u16,
1855        area_width: u16,
1856        area_height: u16,
1857        extra_gutter_width: u16,
1858    ) -> Option<(u16, u16)> {
1859        let (pos_row, pos_col) = buf_cursor_rc(&self.buffer);
1860        let v = self.host.viewport();
1861        if pos_row < v.top_row || pos_col < v.top_col {
1862            return None;
1863        }
1864        let lnum_width = if self.settings.number || self.settings.relativenumber {
1865            let needed = buf_row_count(&self.buffer).to_string().len() + 1;
1866            needed.max(self.settings.numberwidth) as u16
1867        } else {
1868            0
1869        };
1870        // Full offset from the left edge of the window to the first text cell.
1871        let gutter_total = lnum_width + extra_gutter_width;
1872        let dy = (pos_row - v.top_row) as u16;
1873        // Convert char column to visual column so cursor lands on the
1874        // correct cell when the line contains tabs (which the renderer
1875        // expands to TAB_WIDTH stops). Tab width must match the renderer.
1876        let line = self.buffer.line(pos_row).unwrap_or("");
1877        let tab_width = if v.tab_width == 0 {
1878            4
1879        } else {
1880            v.tab_width as usize
1881        };
1882        let visual_pos = visual_col_for_char(line, pos_col, tab_width);
1883        let visual_top = visual_col_for_char(line, v.top_col, tab_width);
1884        let dx = (visual_pos - visual_top) as u16;
1885        if dy >= area_height || dx + gutter_total >= area_width {
1886            return None;
1887        }
1888        Some((area_x + gutter_total + dx, area_y + dy))
1889    }
1890
1891    /// Ratatui [`Rect`]-flavoured wrapper around
1892    /// [`Editor::cursor_screen_pos`]. Behind the `ratatui` feature.
1893    ///
1894    /// Renamed from `cursor_screen_pos` in 0.0.32 — the unprefixed
1895    /// name now belongs to the engine-native variant.
1896    ///
1897    /// `extra_gutter_width` is the combined width of the sign column and
1898    /// fold column that sit to the left of the number column (and thus
1899    /// to the left of the text area). Pass `sign_w + fold_w` from the
1900    /// render layer.
1901    #[cfg(feature = "ratatui")]
1902    pub fn cursor_screen_pos_in_rect(
1903        &self,
1904        area: Rect,
1905        extra_gutter_width: u16,
1906    ) -> Option<(u16, u16)> {
1907        self.cursor_screen_pos(area.x, area.y, area.width, area.height, extra_gutter_width)
1908    }
1909
1910    /// Returns the current vim mode. Phase 6.3: reads from the stable
1911    /// `current_mode` field (kept in sync by both the FSM step loop and
1912    /// the Phase 6.3 primitive bridges) rather than deriving from the
1913    /// FSM-internal `mode` field via `public_mode()`.
1914    pub fn vim_mode(&self) -> VimMode {
1915        self.vim.current_mode
1916    }
1917
1918    /// Bounds of the active visual-block rectangle as
1919    /// `(top_row, bot_row, left_col, right_col)` — all inclusive.
1920    /// `None` when we're not in VisualBlock mode.
1921    /// Read-only view of the live `/` or `?` prompt. `None` outside
1922    /// search-prompt mode.
1923    pub fn search_prompt(&self) -> Option<&crate::vim::SearchPrompt> {
1924        self.vim.search_prompt.as_ref()
1925    }
1926
1927    /// Most recent committed search pattern (persists across `n` / `N`
1928    /// and across prompt exits). `None` before the first search.
1929    pub fn last_search(&self) -> Option<&str> {
1930        self.vim.last_search.as_deref()
1931    }
1932
1933    /// Whether the last committed search was a forward `/` (`true`) or
1934    /// a backward `?` (`false`). `n` and `N` consult this to honour the
1935    /// direction the user committed.
1936    pub fn last_search_forward(&self) -> bool {
1937        self.vim.last_search_forward
1938    }
1939
1940    /// Set the most recent committed search text + direction. Used by
1941    /// host-driven prompts (e.g. apps/hjkl's `/` `?` prompt that lives
1942    /// outside the engine's vim FSM) so `n` / `N` repeat the host's
1943    /// most recent commit with the right direction. Pass `None` /
1944    /// `true` to clear.
1945    pub fn set_last_search(&mut self, text: Option<String>, forward: bool) {
1946        self.vim.last_search = text;
1947        self.vim.last_search_forward = forward;
1948    }
1949
1950    /// Start/end `(row, col)` of the active char-wise Visual selection
1951    /// (inclusive on both ends, positionally ordered). `None` when not
1952    /// in Visual mode.
1953    pub fn char_highlight(&self) -> Option<((usize, usize), (usize, usize))> {
1954        if self.vim_mode() != VimMode::Visual {
1955            return None;
1956        }
1957        let anchor = self.vim.visual_anchor;
1958        let cursor = self.cursor();
1959        let (start, end) = if anchor <= cursor {
1960            (anchor, cursor)
1961        } else {
1962            (cursor, anchor)
1963        };
1964        Some((start, end))
1965    }
1966
1967    /// Top/bottom rows of the active VisualLine selection (inclusive).
1968    /// `None` when we're not in VisualLine mode.
1969    pub fn line_highlight(&self) -> Option<(usize, usize)> {
1970        if self.vim_mode() != VimMode::VisualLine {
1971            return None;
1972        }
1973        let anchor = self.vim.visual_line_anchor;
1974        let cursor = buf_cursor_row(&self.buffer);
1975        Some((anchor.min(cursor), anchor.max(cursor)))
1976    }
1977
1978    pub fn block_highlight(&self) -> Option<(usize, usize, usize, usize)> {
1979        if self.vim_mode() != VimMode::VisualBlock {
1980            return None;
1981        }
1982        let (ar, ac) = self.vim.block_anchor;
1983        let cr = buf_cursor_row(&self.buffer);
1984        let cc = self.vim.block_vcol;
1985        let top = ar.min(cr);
1986        let bot = ar.max(cr);
1987        let left = ac.min(cc);
1988        let right = ac.max(cc);
1989        Some((top, bot, left, right))
1990    }
1991
1992    /// Active selection in `hjkl_buffer::Selection` shape. `None` when
1993    /// not in a Visual mode. Phase 7d-i wiring — the host hands this
1994    /// straight to `BufferView` once render flips off textarea
1995    /// (Phase 7d-ii drops the `paint_*_overlay` calls on the same
1996    /// switch).
1997    pub fn buffer_selection(&self) -> Option<hjkl_buffer::Selection> {
1998        use hjkl_buffer::{Position, Selection};
1999        match self.vim_mode() {
2000            VimMode::Visual => {
2001                let (ar, ac) = self.vim.visual_anchor;
2002                let head = buf_cursor_pos(&self.buffer);
2003                Some(Selection::Char {
2004                    anchor: Position::new(ar, ac),
2005                    head,
2006                })
2007            }
2008            VimMode::VisualLine => {
2009                let anchor_row = self.vim.visual_line_anchor;
2010                let head_row = buf_cursor_row(&self.buffer);
2011                Some(Selection::Line {
2012                    anchor_row,
2013                    head_row,
2014                })
2015            }
2016            VimMode::VisualBlock => {
2017                let (ar, ac) = self.vim.block_anchor;
2018                let cr = buf_cursor_row(&self.buffer);
2019                let cc = self.vim.block_vcol;
2020                Some(Selection::Block {
2021                    anchor: Position::new(ar, ac),
2022                    head: Position::new(cr, cc),
2023                })
2024            }
2025            _ => None,
2026        }
2027    }
2028
2029    /// Force back to normal mode (used when dismissing completions etc.)
2030    pub fn force_normal(&mut self) {
2031        self.vim.force_normal();
2032    }
2033
2034    pub fn content(&self) -> String {
2035        let n = buf_row_count(&self.buffer);
2036        let mut s = String::new();
2037        for r in 0..n {
2038            if r > 0 {
2039                s.push('\n');
2040            }
2041            s.push_str(crate::types::Query::line(&self.buffer, r as u32));
2042        }
2043        s.push('\n');
2044        s
2045    }
2046
2047    /// Same logical output as [`content`], but returns a cached
2048    /// `Arc<String>` so back-to-back reads within an un-mutated window
2049    /// are ref-count bumps instead of multi-MB joins. The cache is
2050    /// invalidated by every [`mark_content_dirty`] call.
2051    pub fn content_arc(&mut self) -> std::sync::Arc<String> {
2052        if let Some(arc) = &self.cached_content {
2053            return std::sync::Arc::clone(arc);
2054        }
2055        let arc = std::sync::Arc::new(self.content());
2056        self.cached_content = Some(std::sync::Arc::clone(&arc));
2057        arc
2058    }
2059
2060    pub fn set_content(&mut self, text: &str) {
2061        let mut lines: Vec<String> = text.lines().map(|l| l.to_string()).collect();
2062        while lines.last().map(|l| l.is_empty()).unwrap_or(false) {
2063            lines.pop();
2064        }
2065        if lines.is_empty() {
2066            lines.push(String::new());
2067        }
2068        let _ = lines;
2069        crate::types::BufferEdit::replace_all(&mut self.buffer, text);
2070        self.undo_stack.clear();
2071        self.redo_stack.clear();
2072        // Whole-buffer replace supersedes any queued ContentEdits.
2073        self.pending_content_edits.clear();
2074        self.pending_content_reset = true;
2075        self.mark_content_dirty();
2076    }
2077
2078    /// Whole-buffer replace that **preserves the undo history**.
2079    ///
2080    /// Equivalent to [`Editor::set_content`] but pushes the current buffer
2081    /// state onto the undo stack first, so a subsequent `u` walks back to
2082    /// the pre-replacement content. Use this for any operation the user
2083    /// expects to undo as a single step — e.g. external formatter output
2084    /// (`hjkl-mangler`) installed via the async [`crate::app::FormatWorker`].
2085    ///
2086    /// Like `push_undo`, this clears the redo stack (vim semantics: any
2087    /// new edit invalidates redo).
2088    pub fn set_content_undoable(&mut self, text: &str) {
2089        self.push_undo();
2090        let mut lines: Vec<String> = text.lines().map(|l| l.to_string()).collect();
2091        while lines.last().map(|l| l.is_empty()).unwrap_or(false) {
2092            lines.pop();
2093        }
2094        if lines.is_empty() {
2095            lines.push(String::new());
2096        }
2097        let _ = lines;
2098        crate::types::BufferEdit::replace_all(&mut self.buffer, text);
2099        // Whole-buffer replace supersedes any queued ContentEdits.
2100        self.pending_content_edits.clear();
2101        self.pending_content_reset = true;
2102        self.mark_content_dirty();
2103    }
2104
2105    /// Drain the pending change log produced by buffer mutations.
2106    ///
2107    /// Returns a `Vec<EditOp>` covering edits applied since the last
2108    /// call. Empty when no edits ran. Pull-model, complementary to
2109    /// [`Editor::take_content_change`] which gives back the new full
2110    /// content.
2111    ///
2112    /// Mapping coverage:
2113    /// - InsertChar / InsertStr → exact `EditOp` with empty range +
2114    ///   replacement.
2115    /// - DeleteRange (`Char` kind) → exact range + empty replacement.
2116    /// - Replace → exact range + new replacement.
2117    /// - DeleteRange (`Line`/`Block`), JoinLines, SplitLines,
2118    ///   InsertBlock, DeleteBlockChunks → best-effort placeholder
2119    ///   covering the touched range. Hosts wanting per-cell deltas
2120    ///   should diff their own `lines()` snapshot.
2121    pub fn take_changes(&mut self) -> Vec<crate::types::Edit> {
2122        std::mem::take(&mut self.change_log)
2123    }
2124
2125    /// Read the engine's current settings as a SPEC
2126    /// [`crate::types::Options`].
2127    ///
2128    /// Bridges between the legacy [`Settings`] (which carries fewer
2129    /// fields than SPEC) and the planned 0.1.0 trait surface. Fields
2130    /// not present in `Settings` fall back to vim defaults (e.g.,
2131    /// `expandtab=false`, `wrapscan=true`, `timeout_len=1000ms`).
2132    /// Once trait extraction lands, this becomes the canonical config
2133    /// reader and `Settings` retires.
2134    pub fn current_options(&self) -> crate::types::Options {
2135        crate::types::Options {
2136            shiftwidth: self.settings.shiftwidth as u32,
2137            tabstop: self.settings.tabstop as u32,
2138            softtabstop: self.settings.softtabstop as u32,
2139            textwidth: self.settings.textwidth as u32,
2140            expandtab: self.settings.expandtab,
2141            ignorecase: self.settings.ignore_case,
2142            smartcase: self.settings.smartcase,
2143            wrapscan: self.settings.wrapscan,
2144            wrap: match self.settings.wrap {
2145                hjkl_buffer::Wrap::None => crate::types::WrapMode::None,
2146                hjkl_buffer::Wrap::Char => crate::types::WrapMode::Char,
2147                hjkl_buffer::Wrap::Word => crate::types::WrapMode::Word,
2148            },
2149            readonly: self.settings.readonly,
2150            autoindent: self.settings.autoindent,
2151            smartindent: self.settings.smartindent,
2152            undo_levels: self.settings.undo_levels,
2153            undo_break_on_motion: self.settings.undo_break_on_motion,
2154            iskeyword: self.settings.iskeyword.clone(),
2155            timeout_len: self.settings.timeout_len,
2156            ..crate::types::Options::default()
2157        }
2158    }
2159
2160    /// Apply a SPEC [`crate::types::Options`] to the engine's settings.
2161    /// Only the fields backed by today's [`Settings`] take effect;
2162    /// remaining options become live once trait extraction wires them
2163    /// through.
2164    pub fn apply_options(&mut self, opts: &crate::types::Options) {
2165        self.settings.shiftwidth = opts.shiftwidth as usize;
2166        self.settings.tabstop = opts.tabstop as usize;
2167        self.settings.softtabstop = opts.softtabstop as usize;
2168        self.settings.textwidth = opts.textwidth as usize;
2169        self.settings.expandtab = opts.expandtab;
2170        self.settings.ignore_case = opts.ignorecase;
2171        self.settings.smartcase = opts.smartcase;
2172        self.settings.wrapscan = opts.wrapscan;
2173        self.settings.wrap = match opts.wrap {
2174            crate::types::WrapMode::None => hjkl_buffer::Wrap::None,
2175            crate::types::WrapMode::Char => hjkl_buffer::Wrap::Char,
2176            crate::types::WrapMode::Word => hjkl_buffer::Wrap::Word,
2177        };
2178        self.settings.readonly = opts.readonly;
2179        self.settings.autoindent = opts.autoindent;
2180        self.settings.smartindent = opts.smartindent;
2181        self.settings.undo_levels = opts.undo_levels;
2182        self.settings.undo_break_on_motion = opts.undo_break_on_motion;
2183        self.set_iskeyword(opts.iskeyword.clone());
2184        self.settings.timeout_len = opts.timeout_len;
2185        self.settings.number = opts.number;
2186        self.settings.relativenumber = opts.relativenumber;
2187        self.settings.numberwidth = opts.numberwidth;
2188        self.settings.cursorline = opts.cursorline;
2189        self.settings.cursorcolumn = opts.cursorcolumn;
2190        self.settings.signcolumn = opts.signcolumn;
2191        self.settings.foldcolumn = opts.foldcolumn;
2192        self.settings.colorcolumn = opts.colorcolumn.clone();
2193    }
2194
2195    /// Active visual selection as a SPEC [`crate::types::Highlight`]
2196    /// with [`crate::types::HighlightKind::Selection`].
2197    ///
2198    /// Returns `None` when the editor isn't in a Visual mode.
2199    /// Visual-line and visual-block selections collapse to the
2200    /// bounding char range of the selection — the SPEC `Selection`
2201    /// kind doesn't carry sub-line info today; hosts that need full
2202    /// line / block geometry continue to read [`buffer_selection`]
2203    /// (the legacy [`hjkl_buffer::Selection`] shape).
2204    pub fn selection_highlight(&self) -> Option<crate::types::Highlight> {
2205        use crate::types::{Highlight, HighlightKind, Pos};
2206        let sel = self.buffer_selection()?;
2207        let (start, end) = match sel {
2208            hjkl_buffer::Selection::Char { anchor, head } => {
2209                let a = (anchor.row, anchor.col);
2210                let h = (head.row, head.col);
2211                if a <= h { (a, h) } else { (h, a) }
2212            }
2213            hjkl_buffer::Selection::Line {
2214                anchor_row,
2215                head_row,
2216            } => {
2217                let (top, bot) = if anchor_row <= head_row {
2218                    (anchor_row, head_row)
2219                } else {
2220                    (head_row, anchor_row)
2221                };
2222                let last_col = buf_line(&self.buffer, bot).map(|l| l.len()).unwrap_or(0);
2223                ((top, 0), (bot, last_col))
2224            }
2225            hjkl_buffer::Selection::Block { anchor, head } => {
2226                let (top, bot) = if anchor.row <= head.row {
2227                    (anchor.row, head.row)
2228                } else {
2229                    (head.row, anchor.row)
2230                };
2231                let (left, right) = if anchor.col <= head.col {
2232                    (anchor.col, head.col)
2233                } else {
2234                    (head.col, anchor.col)
2235                };
2236                ((top, left), (bot, right))
2237            }
2238        };
2239        Some(Highlight {
2240            range: Pos {
2241                line: start.0 as u32,
2242                col: start.1 as u32,
2243            }..Pos {
2244                line: end.0 as u32,
2245                col: end.1 as u32,
2246            },
2247            kind: HighlightKind::Selection,
2248        })
2249    }
2250
2251    /// SPEC-typed highlights for `line`.
2252    ///
2253    /// Two emission modes:
2254    ///
2255    /// - **IncSearch**: the user is typing a `/` or `?` prompt and
2256    ///   `Editor::search_prompt` is `Some`. Live-preview matches of
2257    ///   the in-flight pattern surface as
2258    ///   [`crate::types::HighlightKind::IncSearch`].
2259    /// - **SearchMatch**: the prompt has been committed (or absent)
2260    ///   and the buffer's armed pattern is non-empty. Matches surface
2261    ///   as [`crate::types::HighlightKind::SearchMatch`].
2262    ///
2263    /// Selection / MatchParen / Syntax(id) variants land once the
2264    /// trait extraction routes the FSM's selection set + the host's
2265    /// syntax pipeline through the [`crate::types::Host`] trait.
2266    ///
2267    /// Returns an empty vec when there is nothing to highlight or
2268    /// `line` is out of bounds.
2269    pub fn highlights_for_line(&mut self, line: u32) -> Vec<crate::types::Highlight> {
2270        use crate::types::{Highlight, HighlightKind, Pos};
2271        let row = line as usize;
2272        if row >= buf_row_count(&self.buffer) {
2273            return Vec::new();
2274        }
2275
2276        // Live preview while the prompt is open beats the committed
2277        // pattern.
2278        if let Some(prompt) = self.search_prompt() {
2279            if prompt.text.is_empty() {
2280                return Vec::new();
2281            }
2282            let Ok(re) = regex::Regex::new(&prompt.text) else {
2283                return Vec::new();
2284            };
2285            let Some(haystack) = buf_line(&self.buffer, row) else {
2286                return Vec::new();
2287            };
2288            return re
2289                .find_iter(haystack)
2290                .map(|m| Highlight {
2291                    range: Pos {
2292                        line,
2293                        col: m.start() as u32,
2294                    }..Pos {
2295                        line,
2296                        col: m.end() as u32,
2297                    },
2298                    kind: HighlightKind::IncSearch,
2299                })
2300                .collect();
2301        }
2302
2303        if self.search_state.pattern.is_none() {
2304            return Vec::new();
2305        }
2306        let dgen = crate::types::Query::dirty_gen(&self.buffer);
2307        crate::search::search_matches(&self.buffer, &mut self.search_state, dgen, row)
2308            .into_iter()
2309            .map(|(start, end)| Highlight {
2310                range: Pos {
2311                    line,
2312                    col: start as u32,
2313                }..Pos {
2314                    line,
2315                    col: end as u32,
2316                },
2317                kind: HighlightKind::SearchMatch,
2318            })
2319            .collect()
2320    }
2321
2322    /// Build the engine's [`crate::types::RenderFrame`] for the
2323    /// current state. Hosts call this once per redraw and diff
2324    /// across frames.
2325    ///
2326    /// Coarse today — covers mode + cursor + cursor shape + viewport
2327    /// top + line count. SPEC-target fields (selections, highlights,
2328    /// command line, search prompt, status line) land once trait
2329    /// extraction routes them through `SelectionSet` and the
2330    /// `Highlight` pipeline.
2331    pub fn render_frame(&self) -> crate::types::RenderFrame {
2332        use crate::types::{CursorShape, RenderFrame, SnapshotMode};
2333        let (cursor_row, cursor_col) = self.cursor();
2334        let (mode, shape) = match self.vim_mode() {
2335            crate::VimMode::Normal => (SnapshotMode::Normal, CursorShape::Block),
2336            crate::VimMode::Insert => (SnapshotMode::Insert, CursorShape::Bar),
2337            crate::VimMode::Visual => (SnapshotMode::Visual, CursorShape::Block),
2338            crate::VimMode::VisualLine => (SnapshotMode::VisualLine, CursorShape::Block),
2339            crate::VimMode::VisualBlock => (SnapshotMode::VisualBlock, CursorShape::Block),
2340        };
2341        RenderFrame {
2342            mode,
2343            cursor_row: cursor_row as u32,
2344            cursor_col: cursor_col as u32,
2345            cursor_shape: shape,
2346            viewport_top: self.host.viewport().top_row as u32,
2347            line_count: crate::types::Query::line_count(&self.buffer),
2348        }
2349    }
2350
2351    /// Capture the editor's coarse state into a serde-friendly
2352    /// [`crate::types::EditorSnapshot`].
2353    ///
2354    /// Today's snapshot covers mode, cursor, lines, viewport top.
2355    /// Registers, marks, jump list, undo tree, and full options arrive
2356    /// once phase 5 trait extraction lands the generic
2357    /// `Editor<B: Buffer, H: Host>` constructor — this method's surface
2358    /// stays stable; only the snapshot's internal fields grow.
2359    ///
2360    /// Distinct from the internal `snapshot` used by undo (which
2361    /// returns `(Vec<String>, (usize, usize))`); host-facing
2362    /// persistence goes through this one.
2363    pub fn take_snapshot(&self) -> crate::types::EditorSnapshot {
2364        use crate::types::{EditorSnapshot, SnapshotMode};
2365        let mode = match self.vim_mode() {
2366            crate::VimMode::Normal => SnapshotMode::Normal,
2367            crate::VimMode::Insert => SnapshotMode::Insert,
2368            crate::VimMode::Visual => SnapshotMode::Visual,
2369            crate::VimMode::VisualLine => SnapshotMode::VisualLine,
2370            crate::VimMode::VisualBlock => SnapshotMode::VisualBlock,
2371        };
2372        let cursor = self.cursor();
2373        let cursor = (cursor.0 as u32, cursor.1 as u32);
2374        let lines: Vec<String> = buf_lines_to_vec(&self.buffer);
2375        let viewport_top = self.host.viewport().top_row as u32;
2376        let marks = self
2377            .marks
2378            .iter()
2379            .map(|(c, (r, col))| (*c, (*r as u32, *col as u32)))
2380            .collect();
2381        EditorSnapshot {
2382            version: EditorSnapshot::VERSION,
2383            mode,
2384            cursor,
2385            lines,
2386            viewport_top,
2387            registers: self.registers.clone(),
2388            marks,
2389        }
2390    }
2391
2392    /// Restore editor state from an [`EditorSnapshot`]. Returns
2393    /// [`crate::EngineError::SnapshotVersion`] if the snapshot's
2394    /// `version` doesn't match [`EditorSnapshot::VERSION`].
2395    ///
2396    /// Mode is best-effort: `SnapshotMode` only round-trips the
2397    /// status-line summary, not the full FSM state. Visual / Insert
2398    /// mode entry happens through synthetic key dispatch when needed.
2399    pub fn restore_snapshot(
2400        &mut self,
2401        snap: crate::types::EditorSnapshot,
2402    ) -> Result<(), crate::EngineError> {
2403        use crate::types::EditorSnapshot;
2404        if snap.version != EditorSnapshot::VERSION {
2405            return Err(crate::EngineError::SnapshotVersion(
2406                snap.version,
2407                EditorSnapshot::VERSION,
2408            ));
2409        }
2410        let text = snap.lines.join("\n");
2411        self.set_content(&text);
2412        self.jump_cursor(snap.cursor.0 as usize, snap.cursor.1 as usize);
2413        self.host.viewport_mut().top_row = snap.viewport_top as usize;
2414        self.registers = snap.registers;
2415        self.marks = snap
2416            .marks
2417            .into_iter()
2418            .map(|(c, (r, col))| (c, (r as usize, col as usize)))
2419            .collect();
2420        Ok(())
2421    }
2422
2423    /// Install `text` as the pending yank buffer so the next `p`/`P` pastes
2424    /// it. Linewise is inferred from a trailing newline, matching how `yy`/`dd`
2425    /// shape their payload.
2426    pub fn seed_yank(&mut self, text: String) {
2427        let linewise = text.ends_with('\n');
2428        self.vim.yank_linewise = linewise;
2429        self.registers.unnamed = crate::registers::Slot { text, linewise };
2430    }
2431
2432    /// Scroll the viewport down by `rows`. The cursor stays on its
2433    /// absolute line (vim convention) unless the scroll would take it
2434    /// off-screen — in that case it's clamped to the first row still
2435    /// visible.
2436    pub fn scroll_down(&mut self, rows: i16) {
2437        self.scroll_viewport(rows);
2438    }
2439
2440    /// Scroll the viewport up by `rows`. Cursor stays unless it would
2441    /// fall off the bottom of the new viewport, then clamp to the
2442    /// bottom-most visible row.
2443    pub fn scroll_up(&mut self, rows: i16) {
2444        self.scroll_viewport(-rows);
2445    }
2446
2447    /// Scroll the viewport right by `cols` columns. Only the horizontal
2448    /// offset (`top_col`) moves — the cursor is NOT adjusted (matches
2449    /// vim's `zl` behaviour for horizontal scroll without wrap).
2450    pub fn scroll_right(&mut self, cols: i16) {
2451        let vp = self.host.viewport_mut();
2452        let cols_i = cols as isize;
2453        let new_top = (vp.top_col as isize + cols_i).max(0) as usize;
2454        vp.top_col = new_top;
2455    }
2456
2457    /// Scroll the viewport left by `cols` columns. Delegates to
2458    /// `scroll_right` with a negated argument so the floor-at-zero
2459    /// clamp is shared.
2460    pub fn scroll_left(&mut self, cols: i16) {
2461        self.scroll_right(-cols);
2462    }
2463
2464    /// Vim's `scrolloff` default — keep the cursor at least this many
2465    /// rows away from the top / bottom edge of the viewport while
2466    /// scrolling. Collapses to `height / 2` for tiny viewports.
2467    const SCROLLOFF: usize = 5;
2468
2469    /// Scroll the viewport so the cursor stays at least `SCROLLOFF`
2470    /// rows from each edge. Replaces the bare
2471    /// `Buffer::ensure_cursor_visible` call at end-of-step so motions
2472    /// don't park the cursor on the very last visible row.
2473    pub fn ensure_cursor_in_scrolloff(&mut self) {
2474        let height = self.viewport_height.load(Ordering::Relaxed) as usize;
2475        if height == 0 {
2476            // 0.0.42 (Patch C-δ.7): viewport math lifted onto engine
2477            // free fns over `B: Query [+ Cursor]` + `&dyn FoldProvider`.
2478            // Disjoint-field borrow split: `self.buffer` (immutable via
2479            // `folds` snapshot + cursor) and `self.host` (mutable
2480            // viewport ref) live on distinct struct fields, so one
2481            // statement satisfies the borrow checker.
2482            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2483            crate::viewport_math::ensure_cursor_visible(
2484                &self.buffer,
2485                &folds,
2486                self.host.viewport_mut(),
2487            );
2488            return;
2489        }
2490        // Cap margin at (height - 1) / 2 so the upper + lower bands
2491        // can't overlap on tiny windows (margin=5 + height=10 would
2492        // otherwise produce contradictory clamp ranges).
2493        let margin = Self::SCROLLOFF.min(height.saturating_sub(1) / 2);
2494        // Soft-wrap path: scrolloff math runs in *screen rows*, not
2495        // doc rows, since a wrapped doc row spans many visual lines.
2496        if !matches!(self.host.viewport().wrap, hjkl_buffer::Wrap::None) {
2497            self.ensure_scrolloff_wrap(height, margin);
2498            return;
2499        }
2500        let cursor_row = buf_cursor_row(&self.buffer);
2501        let last_row = buf_row_count(&self.buffer).saturating_sub(1);
2502        let v = self.host.viewport_mut();
2503        // Top edge: cursor_row should sit at >= top_row + margin.
2504        if cursor_row < v.top_row + margin {
2505            v.top_row = cursor_row.saturating_sub(margin);
2506        }
2507        // Bottom edge: cursor_row should sit at <= top_row + height - 1 - margin.
2508        let max_bottom = height.saturating_sub(1).saturating_sub(margin);
2509        if cursor_row > v.top_row + max_bottom {
2510            v.top_row = cursor_row.saturating_sub(max_bottom);
2511        }
2512        // Clamp top_row so we never scroll past the buffer's bottom.
2513        let max_top = last_row.saturating_sub(height.saturating_sub(1));
2514        if v.top_row > max_top {
2515            v.top_row = max_top;
2516        }
2517        // Defer to Buffer for column-side scroll (no scrolloff for
2518        // horizontal scrolling — vim default `sidescrolloff = 0`).
2519        let cursor = buf_cursor_pos(&self.buffer);
2520        self.host.viewport_mut().ensure_visible(cursor);
2521    }
2522
2523    /// Soft-wrap-aware scrolloff. Walks `top_row` one visible doc row
2524    /// at a time so the cursor's *screen* row stays inside
2525    /// `[margin, height - 1 - margin]`, then clamps `top_row` so the
2526    /// buffer's bottom never leaves blank rows below it.
2527    fn ensure_scrolloff_wrap(&mut self, height: usize, margin: usize) {
2528        let cursor_row = buf_cursor_row(&self.buffer);
2529        // Step 1 — cursor above viewport: snap top to cursor row,
2530        // then we'll fix up the margin below.
2531        if cursor_row < self.host.viewport().top_row {
2532            let v = self.host.viewport_mut();
2533            v.top_row = cursor_row;
2534            v.top_col = 0;
2535        }
2536        // Step 2 — push top forward until cursor's screen row is
2537        // within the bottom margin (`csr <= height - 1 - margin`).
2538        // 0.0.33 (Patch C-γ): fold-iteration goes through the
2539        // [`crate::types::FoldProvider`] surface via
2540        // [`crate::buffer_impl::BufferFoldProvider`]. 0.0.34 (Patch
2541        // C-δ.1): `cursor_screen_row` / `max_top_for_height` now take
2542        // a `&Viewport` parameter; the host owns the viewport, so the
2543        // disjoint `(self.host, self.buffer)` borrows split cleanly.
2544        let max_csr = height.saturating_sub(1).saturating_sub(margin);
2545        loop {
2546            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2547            let csr =
2548                crate::viewport_math::cursor_screen_row(&self.buffer, &folds, self.host.viewport())
2549                    .unwrap_or(0);
2550            if csr <= max_csr {
2551                break;
2552            }
2553            let top = self.host.viewport().top_row;
2554            let row_count = buf_row_count(&self.buffer);
2555            let next = {
2556                let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2557                <crate::buffer_impl::BufferFoldProvider<'_> as crate::types::FoldProvider>::next_visible_row(&folds, top, row_count)
2558            };
2559            let Some(next) = next else {
2560                break;
2561            };
2562            // Don't walk past the cursor's row.
2563            if next > cursor_row {
2564                self.host.viewport_mut().top_row = cursor_row;
2565                break;
2566            }
2567            self.host.viewport_mut().top_row = next;
2568        }
2569        // Step 3 — pull top backward until cursor's screen row is
2570        // past the top margin (`csr >= margin`).
2571        loop {
2572            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2573            let csr =
2574                crate::viewport_math::cursor_screen_row(&self.buffer, &folds, self.host.viewport())
2575                    .unwrap_or(0);
2576            if csr >= margin {
2577                break;
2578            }
2579            let top = self.host.viewport().top_row;
2580            let prev = {
2581                let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2582                <crate::buffer_impl::BufferFoldProvider<'_> as crate::types::FoldProvider>::prev_visible_row(&folds, top)
2583            };
2584            let Some(prev) = prev else {
2585                break;
2586            };
2587            self.host.viewport_mut().top_row = prev;
2588        }
2589        // Step 4 — clamp top so the buffer's bottom doesn't leave
2590        // blank rows below it. `max_top_for_height` walks segments
2591        // backward from the last row until it accumulates `height`
2592        // screen rows.
2593        let max_top = {
2594            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2595            crate::viewport_math::max_top_for_height(
2596                &self.buffer,
2597                &folds,
2598                self.host.viewport(),
2599                height,
2600            )
2601        };
2602        if self.host.viewport().top_row > max_top {
2603            self.host.viewport_mut().top_row = max_top;
2604        }
2605        self.host.viewport_mut().top_col = 0;
2606    }
2607
2608    fn scroll_viewport(&mut self, delta: i16) {
2609        if delta == 0 {
2610            return;
2611        }
2612        // Bump the host viewport's top within bounds.
2613        let total_rows = buf_row_count(&self.buffer) as isize;
2614        let height = self.viewport_height.load(Ordering::Relaxed) as usize;
2615        let cur_top = self.host.viewport().top_row as isize;
2616        let new_top = (cur_top + delta as isize)
2617            .max(0)
2618            .min((total_rows - 1).max(0)) as usize;
2619        self.host.viewport_mut().top_row = new_top;
2620        // Mirror to textarea so its viewport reads (still consumed by
2621        // a couple of helpers) stay accurate.
2622        let _ = cur_top;
2623        if height == 0 {
2624            return;
2625        }
2626        // Apply scrolloff: keep the cursor at least SCROLLOFF rows
2627        // from the visible viewport edges.
2628        let (cursor_row, cursor_col) = buf_cursor_rc(&self.buffer);
2629        let margin = Self::SCROLLOFF.min(height / 2);
2630        let min_row = new_top + margin;
2631        let max_row = new_top + height.saturating_sub(1).saturating_sub(margin);
2632        let target_row = cursor_row.clamp(min_row, max_row.max(min_row));
2633        if target_row != cursor_row {
2634            let line_len = buf_line(&self.buffer, target_row)
2635                .map(|l| l.chars().count())
2636                .unwrap_or(0);
2637            let target_col = cursor_col.min(line_len.saturating_sub(1));
2638            buf_set_cursor_rc(&mut self.buffer, target_row, target_col);
2639        }
2640    }
2641
2642    pub fn goto_line(&mut self, line: usize) {
2643        let row = line.saturating_sub(1);
2644        let max = buf_row_count(&self.buffer).saturating_sub(1);
2645        let target = row.min(max);
2646        buf_set_cursor_rc(&mut self.buffer, target, 0);
2647        // Vim: `:N` / `+N` jump scrolls the viewport too — without this
2648        // the cursor lands off-screen and the user has to scroll
2649        // manually to see it.
2650        self.ensure_cursor_in_scrolloff();
2651    }
2652
2653    /// Scroll so the cursor row lands at the given viewport position:
2654    /// `Center` → middle row, `Top` → first row, `Bottom` → last row.
2655    /// Cursor stays on its absolute line; only the viewport moves.
2656    pub(super) fn scroll_cursor_to(&mut self, pos: CursorScrollTarget) {
2657        let height = self.viewport_height.load(Ordering::Relaxed) as usize;
2658        if height == 0 {
2659            return;
2660        }
2661        let cur_row = buf_cursor_row(&self.buffer);
2662        let cur_top = self.host.viewport().top_row;
2663        // Scrolloff awareness: `zt` lands the cursor at the top edge
2664        // of the viable area (top + margin), `zb` at the bottom edge
2665        // (top + height - 1 - margin). Match the cap used by
2666        // `ensure_cursor_in_scrolloff` so contradictory bounds are
2667        // impossible on tiny viewports.
2668        let margin = Self::SCROLLOFF.min(height.saturating_sub(1) / 2);
2669        let new_top = match pos {
2670            CursorScrollTarget::Center => cur_row.saturating_sub(height / 2),
2671            CursorScrollTarget::Top => cur_row.saturating_sub(margin),
2672            CursorScrollTarget::Bottom => {
2673                cur_row.saturating_sub(height.saturating_sub(1).saturating_sub(margin))
2674            }
2675        };
2676        if new_top == cur_top {
2677            return;
2678        }
2679        self.host.viewport_mut().top_row = new_top;
2680    }
2681
2682    /// Jump the cursor to the given 1-based line/column, clamped to the document.
2683    pub fn jump_to(&mut self, line: usize, col: usize) {
2684        let r = line.saturating_sub(1);
2685        let max_row = buf_row_count(&self.buffer).saturating_sub(1);
2686        let r = r.min(max_row);
2687        let line_len = buf_line(&self.buffer, r)
2688            .map(|l| l.chars().count())
2689            .unwrap_or(0);
2690        let c = col.saturating_sub(1).min(line_len);
2691        buf_set_cursor_rc(&mut self.buffer, r, c);
2692    }
2693
2694    // ── Host-agnostic doc-coord mouse primitives (Phase 1 of issue #114) ─────
2695    //
2696    // These primitives operate on document (row, col) coordinates that the HOST
2697    // computes from its own layout knowledge (cell geometry for the TUI host,
2698    // pixel geometry for the future GUI host). The engine has no u16 terminal
2699    // assumption here — it just moves the cursor in doc-space.
2700
2701    /// Set the cursor to the given doc-space `(row, col)`, clamped to the
2702    /// document bounds. Hosts use this for programmatic cursor placement and
2703    /// as the building block for the mouse-click path.
2704    ///
2705    /// `col` may equal `line.chars().count()` (Insert-mode "one past end"
2706    /// position); values beyond that are clamped to `char_count`.
2707    pub fn set_cursor_doc(&mut self, row: usize, col: usize) {
2708        let max_row = buf_row_count(&self.buffer).saturating_sub(1);
2709        let r = row.min(max_row);
2710        let line_len = buf_line(&self.buffer, r)
2711            .map(|l| l.chars().count())
2712            .unwrap_or(0);
2713        let c = col.min(line_len);
2714        buf_set_cursor_rc(&mut self.buffer, r, c);
2715    }
2716
2717    /// Handle a left-button click at doc-space `(row, col)`.
2718    ///
2719    /// Exits Visual mode if active, breaks the insert-mode undo group (Vim
2720    /// parity for `undo_break_on_motion`), then moves the cursor. The host
2721    /// performs cell→doc or pixel→doc translation before calling this.
2722    ///
2723    /// Mode-aware EOL clamp (neovim parity): in Normal / Visual modes the
2724    /// cursor lives on chars and never on the implicit `\n` — `col` is
2725    /// capped at `line.chars().count().saturating_sub(1)`. Insert mode
2726    /// allows the one-past-EOL insert position (`col == chars().count()`).
2727    ///
2728    /// Resets `sticky_col` to the clicked column so the next `j`/`k`
2729    /// motion uses the clicked column as the intended visual column
2730    /// (otherwise the cursor would snap back to the keyboard-tracked
2731    /// column on the first vertical motion after a click).
2732    pub fn mouse_click_doc(&mut self, row: usize, col: usize) {
2733        if self.vim.is_visual() {
2734            self.vim.force_normal();
2735        }
2736        // Mouse-position click counts as a motion — break the active
2737        // insert-mode undo group when the toggle is on (vim parity).
2738        crate::vim::break_undo_group_in_insert(self);
2739
2740        let max_row = buf_row_count(&self.buffer).saturating_sub(1);
2741        let r = row.min(max_row);
2742        let line_len = buf_line(&self.buffer, r)
2743            .map(|l| l.chars().count())
2744            .unwrap_or(0);
2745        let cap = if self.vim.current_mode == crate::VimMode::Insert {
2746            line_len
2747        } else {
2748            line_len.saturating_sub(1)
2749        };
2750        let c = col.min(cap);
2751        buf_set_cursor_rc(&mut self.buffer, r, c);
2752        self.sticky_col = Some(c);
2753    }
2754
2755    /// Begin a mouse-drag selection: anchor at the current cursor and enter
2756    /// Visual-char mode. Idempotent if already in Visual-char mode.
2757    pub fn mouse_begin_drag(&mut self) {
2758        if !self.vim.is_visual_char() {
2759            vim::enter_visual_char_bridge(self);
2760        }
2761    }
2762
2763    /// Extend an in-progress mouse drag to doc-space `(row, col)`.
2764    ///
2765    /// Moves the live cursor; the Visual anchor stays where
2766    /// [`Editor::mouse_begin_drag`] set it. Call after the host has
2767    /// translated the drag position to doc coordinates.
2768    pub fn mouse_extend_drag_doc(&mut self, row: usize, col: usize) {
2769        self.set_cursor_doc(row, col);
2770    }
2771
2772    pub fn insert_str(&mut self, text: &str) {
2773        let pos = crate::types::Cursor::cursor(&self.buffer);
2774        crate::types::BufferEdit::insert_at(&mut self.buffer, pos, text);
2775        self.push_buffer_content_to_textarea();
2776        self.mark_content_dirty();
2777    }
2778
2779    pub fn accept_completion(&mut self, completion: &str) {
2780        use crate::types::{BufferEdit, Cursor as CursorTrait, Pos};
2781        let cursor_pos = CursorTrait::cursor(&self.buffer);
2782        let cursor_row = cursor_pos.line as usize;
2783        let cursor_col = cursor_pos.col as usize;
2784        let line = buf_line(&self.buffer, cursor_row).unwrap_or("").to_string();
2785        let chars: Vec<char> = line.chars().collect();
2786        let prefix_len = chars[..cursor_col.min(chars.len())]
2787            .iter()
2788            .rev()
2789            .take_while(|c| c.is_alphanumeric() || **c == '_')
2790            .count();
2791        if prefix_len > 0 {
2792            let start = Pos {
2793                line: cursor_row as u32,
2794                col: (cursor_col - prefix_len) as u32,
2795            };
2796            BufferEdit::delete_range(&mut self.buffer, start..cursor_pos);
2797        }
2798        let cursor = CursorTrait::cursor(&self.buffer);
2799        BufferEdit::insert_at(&mut self.buffer, cursor, completion);
2800        self.push_buffer_content_to_textarea();
2801        self.mark_content_dirty();
2802    }
2803
2804    pub(super) fn snapshot(&self) -> (Vec<String>, (usize, usize)) {
2805        let rc = buf_cursor_rc(&self.buffer);
2806        (buf_lines_to_vec(&self.buffer), rc)
2807    }
2808
2809    /// Walk one step back through the undo history. Equivalent to the
2810    /// user pressing `u` in normal mode. Drains the most recent undo
2811    /// entry and pushes it onto the redo stack.
2812    pub fn undo(&mut self) {
2813        crate::vim::do_undo(self);
2814    }
2815
2816    /// Walk one step forward through the redo history. Equivalent to
2817    /// `<C-r>` in normal mode.
2818    pub fn redo(&mut self) {
2819        crate::vim::do_redo(self);
2820    }
2821
2822    /// Snapshot current buffer state onto the undo stack and clear
2823    /// the redo stack. Bounded by `settings.undo_levels` — older
2824    /// entries pruned. Call before any group of buffer mutations the
2825    /// user might want to undo as a single step.
2826    pub fn push_undo(&mut self) {
2827        let snap = self.snapshot();
2828        self.undo_stack.push(snap);
2829        self.cap_undo();
2830        self.redo_stack.clear();
2831    }
2832
2833    /// Trim the undo stack down to `settings.undo_levels`, dropping
2834    /// the oldest entries. `undo_levels == 0` is treated as
2835    /// "unlimited" (vim's 0-means-no-undo semantics intentionally
2836    /// skipped — guarding with `> 0` is one line shorter than gating
2837    /// the cap path with an explicit zero-check above the call site).
2838    pub(crate) fn cap_undo(&mut self) {
2839        let cap = self.settings.undo_levels as usize;
2840        if cap > 0 && self.undo_stack.len() > cap {
2841            let diff = self.undo_stack.len() - cap;
2842            self.undo_stack.drain(..diff);
2843        }
2844    }
2845
2846    /// Test-only accessor for the undo stack length.
2847    #[doc(hidden)]
2848    pub fn undo_stack_len(&self) -> usize {
2849        self.undo_stack.len()
2850    }
2851
2852    /// Replace the buffer with `lines` joined by `\n` and set the
2853    /// cursor to `cursor`. Used by undo / `:e!` / snapshot restore
2854    /// paths. Marks the editor dirty.
2855    pub fn restore(&mut self, lines: Vec<String>, cursor: (usize, usize)) {
2856        let text = lines.join("\n");
2857        crate::types::BufferEdit::replace_all(&mut self.buffer, &text);
2858        buf_set_cursor_rc(&mut self.buffer, cursor.0, cursor.1);
2859        // Bulk replace — supersedes any queued ContentEdits.
2860        self.pending_content_edits.clear();
2861        self.pending_content_reset = true;
2862        self.mark_content_dirty();
2863    }
2864
2865    /// Returns true if the key was consumed by the editor.
2866    /// Replace the char under the cursor with `ch`, `count` times. Matches
2867    /// vim `r<x>` semantics: cursor ends on the last replaced char, undo
2868    /// snapshot taken once at start. Promoted to public surface in 0.5.5
2869    /// so hjkl-vim's pending-state reducer can dispatch `Replace` without
2870    /// re-entering the FSM.
2871    pub fn replace_char_at(&mut self, ch: char, count: usize) {
2872        vim::replace_char(self, ch, count);
2873    }
2874
2875    /// Apply vim's `f<x>` / `F<x>` / `t<x>` / `T<x>` motion. Moves the cursor
2876    /// to the `count`-th occurrence of `ch` on the current line, respecting
2877    /// `forward` (direction) and `till` (stop one char before target).
2878    /// Records `last_find` so `;` / `,` repeat work.
2879    ///
2880    /// No-op if the target char isn't on the current line within range.
2881    /// Cursor / scroll / sticky-col semantics match `f<x>` via `execute_motion`.
2882    pub fn find_char(&mut self, ch: char, forward: bool, till: bool, count: usize) {
2883        vim::apply_find_char(self, ch, forward, till, count.max(1));
2884    }
2885
2886    /// Apply the g-chord effect for `g<ch>` with a pre-captured `count`.
2887    /// Mirrors the full `handle_after_g` dispatch table — `gg`, `gj`, `gk`,
2888    /// `gv`, `gU` / `gu` / `g~` (→ operator-pending), `gi`, `g*`, `g#`, etc.
2889    ///
2890    /// Promoted to public surface in 0.5.10 so hjkl-vim's
2891    /// `PendingState::AfterG` reducer can dispatch `AfterGChord` without
2892    /// re-entering the engine FSM.
2893    pub fn after_g(&mut self, ch: char, count: usize) {
2894        vim::apply_after_g(self, ch, count);
2895    }
2896
2897    /// Apply the z-chord effect for `z<ch>` with a pre-captured `count`.
2898    /// Mirrors the full `handle_after_z` dispatch table — `zz` / `zt` / `zb`
2899    /// (scroll-cursor), `zo` / `zc` / `za` / `zR` / `zM` / `zE` / `zd`
2900    /// (fold ops), and `zf` (fold-add over visual selection or → op-pending).
2901    ///
2902    /// Promoted to public surface in 0.5.11 so hjkl-vim's
2903    /// `PendingState::AfterZ` reducer can dispatch `AfterZChord` without
2904    /// re-entering the engine FSM.
2905    pub fn after_z(&mut self, ch: char, count: usize) {
2906        vim::apply_after_z(self, ch, count);
2907    }
2908
2909    /// Apply an operator over a single-key motion. `op` is the engine `Operator`
2910    /// and `motion_key` is the raw character (e.g. `'w'`, `'$'`, `'G'`). The
2911    /// engine resolves the char to a [`vim::Motion`] via `parse_motion`, applies
2912    /// the vim quirks (`cw` → `ce`, `cW` → `cE`, `FindRepeat` → stored find),
2913    /// then calls `apply_op_with_motion`. `total_count` is already the product of
2914    /// the prefix count and any inner count accumulated by the reducer.
2915    ///
2916    /// No-op when `motion_key` does not map to a known motion (engine silently
2917    /// cancels the operator, matching vim's behaviour on unknown motions).
2918    ///
2919    /// Promoted to the public surface in 0.5.12 so the hjkl-vim
2920    /// `PendingState::AfterOp` reducer can dispatch `ApplyOpMotion` without
2921    /// re-entering the engine FSM.
2922    pub fn apply_op_motion(
2923        &mut self,
2924        op: crate::vim::Operator,
2925        motion_key: char,
2926        total_count: usize,
2927    ) {
2928        vim::apply_op_motion_key(self, op, motion_key, total_count);
2929    }
2930
2931    /// Apply a doubled-letter line op (`dd` / `yy` / `cc` / `>>` / `<<`).
2932    /// `total_count` is the product of prefix count and inner count.
2933    ///
2934    /// Promoted to the public surface in 0.5.12 so the hjkl-vim
2935    /// `PendingState::AfterOp` reducer can dispatch `ApplyOpDouble` without
2936    /// re-entering the engine FSM.
2937    pub fn apply_op_double(&mut self, op: crate::vim::Operator, total_count: usize) {
2938        vim::apply_op_double(self, op, total_count);
2939    }
2940
2941    /// Apply an operator over a find motion (`df<x>` / `dF<x>` / `dt<x>` /
2942    /// `dT<x>`). Builds `Motion::Find { ch, forward, till }`, applies it via
2943    /// `apply_op_with_motion`, records `last_find` for `;` / `,` repeat, and
2944    /// updates `last_change` when `op` is Change (for dot-repeat).
2945    ///
2946    /// `total_count` is the product of prefix count and any inner count
2947    /// accumulated by the reducer — already folded at transition time.
2948    ///
2949    /// Promoted to the public surface in 0.5.14 so the hjkl-vim
2950    /// `PendingState::OpFind` reducer can dispatch `ApplyOpFind` without
2951    /// re-entering the engine FSM. `handle_op_find_target` (used by the
2952    /// chord-init op path) delegates here to avoid logic duplication.
2953    pub fn apply_op_find(
2954        &mut self,
2955        op: crate::vim::Operator,
2956        ch: char,
2957        forward: bool,
2958        till: bool,
2959        total_count: usize,
2960    ) {
2961        vim::apply_op_find_motion(self, op, ch, forward, till, total_count);
2962    }
2963
2964    /// Apply an operator over a text-object range (`diw` / `daw` / `di"` etc.).
2965    /// Maps `ch` to a `TextObject` per the standard vim table, calls
2966    /// `apply_op_with_text_object`, and records `last_change` when `op` is
2967    /// Change (dot-repeat). Unknown `ch` values are silently ignored (no-op),
2968    /// matching the engine FSM's behaviour on unrecognised text-object chars.
2969    ///
2970    /// `total_count` is accepted for API symmetry with `apply_op_motion` /
2971    /// `apply_op_find` but is currently unused — text objects don't repeat in
2972    /// vim's current grammar. Kept for future-proofing.
2973    ///
2974    /// Promoted to the public surface in 0.5.15 so the hjkl-vim
2975    /// `PendingState::OpTextObj` reducer can dispatch `ApplyOpTextObj` without
2976    /// re-entering the engine FSM. `handle_text_object` (chord-init op path)
2977    /// delegates to the shared `apply_op_text_obj_inner` helper to avoid logic
2978    /// duplication.
2979    pub fn apply_op_text_obj(
2980        &mut self,
2981        op: crate::vim::Operator,
2982        ch: char,
2983        inner: bool,
2984        total_count: usize,
2985    ) {
2986        vim::apply_op_text_obj_inner(self, op, ch, inner, total_count);
2987    }
2988
2989    /// Apply an operator over a g-chord motion or case-op linewise form
2990    /// (`dgg` / `dge` / `dgE` / `dgj` / `dgk` / `gUgU` etc.).
2991    ///
2992    /// - If `op` is Uppercase/Lowercase/ToggleCase and `ch` matches the op's
2993    ///   letter (`U`/`u`/`~`), executes the line op (linewise form).
2994    /// - Otherwise maps `ch` to a motion:
2995    ///   - `'g'` → `Motion::FileTop` (gg)
2996    ///   - `'e'` → `Motion::WordEndBack` (ge)
2997    ///   - `'E'` → `Motion::BigWordEndBack` (gE)
2998    ///   - `'j'` → `Motion::ScreenDown` (gj)
2999    ///   - `'k'` → `Motion::ScreenUp` (gk)
3000    ///   - unknown → no-op (silently ignored, matching engine FSM behaviour)
3001    /// - Updates `last_change` for dot-repeat when `op` is a change operator.
3002    ///
3003    /// `total_count` is the already-folded product of prefix and inner counts.
3004    ///
3005    /// Promoted to the public surface in 0.5.16 so the hjkl-vim
3006    /// `PendingState::OpG` reducer can dispatch `ApplyOpG` without
3007    /// re-entering the engine FSM. `handle_op_after_g` (chord-init op path)
3008    /// delegates to the shared `apply_op_g_inner` helper to avoid logic
3009    /// duplication.
3010    pub fn apply_op_g(&mut self, op: crate::vim::Operator, ch: char, total_count: usize) {
3011        vim::apply_op_g_inner(self, op, ch, total_count);
3012    }
3013
3014    // ─── Range-query helpers for partial-format dispatch (#119) ─────────────
3015
3016    /// Dry-run `motion_key` and return `(min_row, max_row)` between the cursor
3017    /// row and the motion's target row. Used by the app layer to compute the
3018    /// [`hjkl_mangler::RangeSpec`] for `=<motion>` before submitting the async
3019    /// format job.
3020    ///
3021    /// Returns `None` when `motion_key` does not map to a known motion (same
3022    /// condition that makes `apply_op_motion` a no-op).
3023    ///
3024    /// The cursor is restored to its original position after the probe —
3025    /// the buffer content is not touched.
3026    pub fn range_for_op_motion(
3027        &mut self,
3028        motion_key: char,
3029        total_count: usize,
3030    ) -> Option<(usize, usize)> {
3031        let start = self.cursor();
3032        // Reuse the same logic as apply_op_motion_key but only read the
3033        // target row — we parse the motion, apply it to move the cursor,
3034        // then immediately restore.
3035        let input = crate::input::Input {
3036            key: crate::input::Key::Char(motion_key),
3037            ctrl: false,
3038            alt: false,
3039            shift: false,
3040        };
3041        let motion = vim::parse_motion(&input)?;
3042        // Resolve FindRepeat and cw/cW quirks just like apply_op_motion_key.
3043        let motion = match motion {
3044            vim::Motion::FindRepeat { reverse } => match self.vim.last_find {
3045                Some((ch, forward, till)) => vim::Motion::Find {
3046                    ch,
3047                    forward: if reverse { !forward } else { forward },
3048                    till,
3049                },
3050                None => return None,
3051            },
3052            m => m,
3053        };
3054        vim::apply_motion_cursor_ctx(self, &motion, total_count, true);
3055        let end = self.cursor();
3056        // Restore cursor.
3057        buf_set_cursor_rc(&mut self.buffer, start.0, start.1);
3058        let (r0, r1) = (start.0.min(end.0), start.0.max(end.0));
3059        Some((r0, r1))
3060    }
3061
3062    /// Dry-run a `g`-prefixed motion and return `(min_row, max_row)`. Used for
3063    /// `=gg` / `=gj` etc. Returns `None` for unknown `ch` values or case-op
3064    /// linewise forms that don't map to a row range.
3065    ///
3066    /// The cursor is restored after the probe.
3067    pub fn range_for_op_g(&mut self, ch: char, total_count: usize) -> Option<(usize, usize)> {
3068        let start = self.cursor();
3069        let motion = match ch {
3070            'g' => vim::Motion::FileTop,
3071            'e' => vim::Motion::WordEndBack,
3072            'E' => vim::Motion::BigWordEndBack,
3073            'j' => vim::Motion::ScreenDown,
3074            'k' => vim::Motion::ScreenUp,
3075            _ => return None,
3076        };
3077        vim::apply_motion_cursor_ctx(self, &motion, total_count, true);
3078        let end = self.cursor();
3079        buf_set_cursor_rc(&mut self.buffer, start.0, start.1);
3080        let (r0, r1) = (start.0.min(end.0), start.0.max(end.0));
3081        Some((r0, r1))
3082    }
3083
3084    /// Dry-run a text-object lookup and return `(min_row, max_row)` for the
3085    /// matched region. Returns `None` when `ch` is not a known text-object
3086    /// kind or the text object could not be resolved (e.g. no enclosing bracket).
3087    ///
3088    /// The buffer is not mutated.
3089    pub fn range_for_op_text_obj(
3090        &self,
3091        ch: char,
3092        inner: bool,
3093        _total_count: usize,
3094    ) -> Option<(usize, usize)> {
3095        let obj = match ch {
3096            'w' => vim::TextObject::Word { big: false },
3097            'W' => vim::TextObject::Word { big: true },
3098            '"' | '\'' | '`' => vim::TextObject::Quote(ch),
3099            '(' | ')' | 'b' => vim::TextObject::Bracket('('),
3100            '[' | ']' => vim::TextObject::Bracket('['),
3101            '{' | '}' | 'B' => vim::TextObject::Bracket('{'),
3102            '<' | '>' => vim::TextObject::Bracket('<'),
3103            'p' => vim::TextObject::Paragraph,
3104            't' => vim::TextObject::XmlTag,
3105            's' => vim::TextObject::Sentence,
3106            _ => return None,
3107        };
3108        let (start, end, _kind) = vim::text_object_range(self, obj, inner)?;
3109        let (r0, r1) = (start.0.min(end.0), start.0.max(end.0));
3110        Some((r0, r1))
3111    }
3112
3113    // ─── Phase 4a: pub range-mutation primitives (hjkl#70) ──────────────────
3114    //
3115    // These do not consume input — the caller (hjkl-vim's visual-mode operator
3116    // path, chunk 4e) has already resolved the range from the visual selection
3117    // before calling in. Normal-mode op dispatch continues to use
3118    // `apply_op_motion` / `apply_op_double` / `apply_op_find` / `apply_op_text_obj`.
3119
3120    /// Delete the region `[start, end)` and stash the removed text in
3121    /// `register`. `'"'` selects the unnamed register (vim default); `'a'`–`'z'`
3122    /// select named registers.
3123    ///
3124    /// Pure range-mutation primitive — does not consume input. Called by
3125    /// hjkl-vim's visual-mode operator path which has already resolved the range
3126    /// from the visual selection.
3127    ///
3128    /// Promoted to the public surface in 0.6.7 for Phase 4 visual-mode op
3129    /// grammar migration (kryptic-sh/hjkl#70).
3130    pub fn delete_range(
3131        &mut self,
3132        start: (usize, usize),
3133        end: (usize, usize),
3134        kind: crate::vim::RangeKind,
3135        register: char,
3136    ) {
3137        vim::delete_range_bridge(self, start, end, kind, register);
3138    }
3139
3140    /// Yank (copy) the region `[start, end)` into `register` without mutating
3141    /// the buffer. `'"'` selects the unnamed register; `'0'` the yank-only
3142    /// register; `'a'`–`'z'` select named registers.
3143    ///
3144    /// Pure range-mutation primitive — does not consume input. Called by
3145    /// hjkl-vim's visual-mode operator path which has already resolved the range
3146    /// from the visual selection.
3147    ///
3148    /// Promoted to the public surface in 0.6.7 for Phase 4 visual-mode op
3149    /// grammar migration (kryptic-sh/hjkl#70).
3150    pub fn yank_range(
3151        &mut self,
3152        start: (usize, usize),
3153        end: (usize, usize),
3154        kind: crate::vim::RangeKind,
3155        register: char,
3156    ) {
3157        vim::yank_range_bridge(self, start, end, kind, register);
3158    }
3159
3160    /// Delete the region `[start, end)` and transition to Insert mode (vim `c`
3161    /// operator). The deleted text is stashed in `register`. On return the
3162    /// editor is in Insert mode; the caller must not issue further normal-mode
3163    /// ops until the insert session ends.
3164    ///
3165    /// Pure range-mutation primitive — does not consume input. Called by
3166    /// hjkl-vim's visual-mode operator path which has already resolved the range
3167    /// from the visual selection.
3168    ///
3169    /// Promoted to the public surface in 0.6.7 for Phase 4 visual-mode op
3170    /// grammar migration (kryptic-sh/hjkl#70).
3171    pub fn change_range(
3172        &mut self,
3173        start: (usize, usize),
3174        end: (usize, usize),
3175        kind: crate::vim::RangeKind,
3176        register: char,
3177    ) {
3178        vim::change_range_bridge(self, start, end, kind, register);
3179    }
3180
3181    /// Indent (`count > 0`) or outdent (`count < 0`) the row span
3182    /// `[start.0, end.0]`. Column components are ignored — indent is always
3183    /// linewise. `shiftwidth` overrides the editor's configured shiftwidth for
3184    /// this call; pass `0` to use the current editor setting. `count == 0` is a
3185    /// no-op.
3186    ///
3187    /// Pure range-mutation primitive — does not consume input. Called by
3188    /// hjkl-vim's visual-mode operator path which has already resolved the range
3189    /// from the visual selection.
3190    ///
3191    /// Promoted to the public surface in 0.6.7 for Phase 4 visual-mode op
3192    /// grammar migration (kryptic-sh/hjkl#70).
3193    pub fn indent_range(
3194        &mut self,
3195        start: (usize, usize),
3196        end: (usize, usize),
3197        count: i32,
3198        shiftwidth: u32,
3199    ) {
3200        vim::indent_range_bridge(self, start, end, count, shiftwidth);
3201    }
3202
3203    /// Apply a case transformation (`Operator::Uppercase` /
3204    /// `Operator::Lowercase` / `Operator::ToggleCase`) to the region
3205    /// `[start, end)`. Other `Operator` variants are silently ignored (no-op).
3206    /// Yanks registers are left untouched — vim's case operators do not write
3207    /// to registers.
3208    ///
3209    /// Pure range-mutation primitive — does not consume input. Called by
3210    /// hjkl-vim's visual-mode operator path which has already resolved the range
3211    /// from the visual selection.
3212    ///
3213    /// Promoted to the public surface in 0.6.7 for Phase 4 visual-mode op
3214    /// grammar migration (kryptic-sh/hjkl#70).
3215    pub fn case_range(
3216        &mut self,
3217        start: (usize, usize),
3218        end: (usize, usize),
3219        kind: crate::vim::RangeKind,
3220        op: crate::vim::Operator,
3221    ) {
3222        vim::case_range_bridge(self, start, end, kind, op);
3223    }
3224
3225    // ─── Phase 4e: pub block-shape range-mutation primitives (hjkl#70) ──────
3226    //
3227    // Rectangular VisualBlock operations. `top_row`/`bot_row` are inclusive
3228    // line indices; `left_col`/`right_col` are inclusive char-column bounds.
3229    // Ragged-edge handling (short lines not reaching `right_col`) matches the
3230    // engine FSM's `apply_block_operator` path — short lines lose only the
3231    // chars that exist.
3232    //
3233    // `register` is the target register; `'"'` selects the unnamed register.
3234
3235    /// Delete a rectangular VisualBlock selection. `top_row` / `bot_row` are
3236    /// inclusive line bounds; `left_col` / `right_col` are inclusive column
3237    /// bounds at the visual (display) column level. Ragged-edge handling
3238    /// matches engine FSM's VisualBlock op behavior — short lines that don't
3239    /// reach `right_col` lose only the chars that exist.
3240    ///
3241    /// `register` honors the user's pending register selection.
3242    ///
3243    /// Promoted in 0.6.X for Phase 4e block-op grammar migration.
3244    pub fn delete_block(
3245        &mut self,
3246        top_row: usize,
3247        bot_row: usize,
3248        left_col: usize,
3249        right_col: usize,
3250        register: char,
3251    ) {
3252        vim::delete_block_bridge(self, top_row, bot_row, left_col, right_col, register);
3253    }
3254
3255    /// Yank a rectangular VisualBlock selection into `register` without
3256    /// mutating the buffer. `'"'` selects the unnamed register.
3257    ///
3258    /// Promoted in 0.6.X for Phase 4e block-op grammar migration.
3259    pub fn yank_block(
3260        &mut self,
3261        top_row: usize,
3262        bot_row: usize,
3263        left_col: usize,
3264        right_col: usize,
3265        register: char,
3266    ) {
3267        vim::yank_block_bridge(self, top_row, bot_row, left_col, right_col, register);
3268    }
3269
3270    /// Delete a rectangular VisualBlock selection and enter Insert mode (`c`
3271    /// operator). The deleted text is stashed in `register`. Mode is Insert
3272    /// on return; the caller must not issue further normal-mode ops until the
3273    /// insert session ends.
3274    ///
3275    /// Promoted in 0.6.X for Phase 4e block-op grammar migration.
3276    pub fn change_block(
3277        &mut self,
3278        top_row: usize,
3279        bot_row: usize,
3280        left_col: usize,
3281        right_col: usize,
3282        register: char,
3283    ) {
3284        vim::change_block_bridge(self, top_row, bot_row, left_col, right_col, register);
3285    }
3286
3287    /// Indent (`count > 0`) or outdent (`count < 0`) rows `top_row..=bot_row`.
3288    /// Column bounds are ignored — vim's block indent is always linewise.
3289    /// `count == 0` is a no-op.
3290    ///
3291    /// Promoted in 0.6.X for Phase 4e block-op grammar migration.
3292    pub fn indent_block(
3293        &mut self,
3294        top_row: usize,
3295        bot_row: usize,
3296        _left_col: usize,
3297        _right_col: usize,
3298        count: i32,
3299    ) {
3300        vim::indent_block_bridge(self, top_row, bot_row, count);
3301    }
3302
3303    /// Auto-indent (v1 dumb shiftwidth) the row span `[start.0, end.0]`.
3304    /// Column components are ignored — auto-indent is always linewise.
3305    ///
3306    /// The algorithm is a naive bracket-depth counter: it scans the buffer from
3307    /// row 0 to compute the correct depth at `start.0`, then for each line in
3308    /// the target range strips existing leading whitespace and prepends
3309    /// `depth × indent_unit` where `indent_unit` is `"\t"` when `expandtab`
3310    /// is `false`, or `" " × shiftwidth` when `expandtab` is `true`. Lines
3311    /// whose first non-whitespace character is a close bracket (`}`, `)`, `]`)
3312    /// get one fewer indent level. Empty / whitespace-only lines are cleared.
3313    ///
3314    /// After the operation the cursor lands on the first non-whitespace
3315    /// character of `start_row` (vim parity for `==`).
3316    ///
3317    /// **v1 limitation**: the bracket scan does not detect brackets inside
3318    /// string literals or comments. Code such as `let s = "{";` will increment
3319    /// the depth counter even though the brace is not a structural opener.
3320    /// Tree-sitter / LSP indentation is deferred to a follow-up.
3321    pub fn auto_indent_range(&mut self, start: (usize, usize), end: (usize, usize)) {
3322        vim::auto_indent_range_bridge(self, start, end);
3323    }
3324
3325    /// Drain the row range set by the most recent auto-indent operation.
3326    ///
3327    /// Returns `Some((top_row, bot_row))` (inclusive) on the first call after
3328    /// an `=` / `==` / `=G` / Visual-`=` operator, then clears the stored
3329    /// value so a subsequent call returns `None`. The host (e.g. `apps/hjkl`)
3330    /// uses this to arm a brief visual flash over the reindented rows.
3331    pub fn take_last_indent_range(&mut self) -> Option<(usize, usize)> {
3332        self.last_indent_range.take()
3333    }
3334
3335    // ─── Phase 4b: pub text-object resolution (hjkl#70) ─────────────────────
3336    //
3337    // Pure functions — no cursor mutation, no mode change, no register write.
3338    // Each method delegates to `vim::text_object_*_bridge`, which in turn calls
3339    // the existing `word_text_object` private resolver in vim.rs.
3340    //
3341    // Called by hjkl-vim's `OpTextObj` reducer (chunk 4e) to resolve the range
3342    // before invoking a range-mutation primitive (`delete_range`, etc.).
3343    //
3344    // Return value: `Some((start, end))` where both positions are `(row, col)`
3345    // byte-column pairs and `end` is *exclusive* (one past the last byte to act
3346    // on), matching the convention used by `delete_range` / `yank_range` / etc.
3347    // Returns `None` when the cursor is on an empty line or the resolver cannot
3348    // find a word boundary.
3349
3350    /// Resolve the range of `iw` (inner word) at the current cursor position.
3351    ///
3352    /// An inner word is the contiguous run of keyword characters (or punctuation
3353    /// characters if the cursor is on punctuation) under the cursor, without any
3354    /// surrounding whitespace. Whitespace-only positions return `None`.
3355    ///
3356    /// Pure function — does not move the cursor or change any editor state.
3357    /// Called by hjkl-vim's `OpTextObj` reducer to resolve the range before
3358    /// invoking a range-mutation primitive (`delete_range`, etc.).
3359    ///
3360    /// Promoted to the public surface in 0.6.X for Phase 4b text-object grammar
3361    /// migration (kryptic-sh/hjkl#70).
3362    pub fn text_object_inner_word(&self) -> Option<((usize, usize), (usize, usize))> {
3363        vim::text_object_inner_word_bridge(self)
3364    }
3365
3366    /// Resolve the range of `aw` (around word) at the current cursor position.
3367    ///
3368    /// Like `iw` but extends the range to include trailing whitespace after the
3369    /// word. If no trailing whitespace exists, leading whitespace before the word
3370    /// is absorbed instead (vim `:help text-objects` behaviour).
3371    ///
3372    /// Pure function — does not move the cursor or change any editor state.
3373    ///
3374    /// Promoted to the public surface in 0.6.X for Phase 4b text-object grammar
3375    /// migration (kryptic-sh/hjkl#70).
3376    pub fn text_object_around_word(&self) -> Option<((usize, usize), (usize, usize))> {
3377        vim::text_object_around_word_bridge(self)
3378    }
3379
3380    /// Resolve the range of `iW` (inner WORD) at the current cursor position.
3381    ///
3382    /// A WORD is any contiguous run of non-whitespace characters — punctuation
3383    /// is not treated as a word boundary. Returns the span of the WORD under the
3384    /// cursor, without surrounding whitespace.
3385    ///
3386    /// Pure function — does not move the cursor or change any editor state.
3387    ///
3388    /// Promoted to the public surface in 0.6.X for Phase 4b text-object grammar
3389    /// migration (kryptic-sh/hjkl#70).
3390    pub fn text_object_inner_big_word(&self) -> Option<((usize, usize), (usize, usize))> {
3391        vim::text_object_inner_big_word_bridge(self)
3392    }
3393
3394    /// Resolve the range of `aW` (around WORD) at the current cursor position.
3395    ///
3396    /// Like `iW` but extends the range to include trailing whitespace after the
3397    /// WORD. If no trailing whitespace exists, leading whitespace before the WORD
3398    /// is absorbed instead.
3399    ///
3400    /// Pure function — does not move the cursor or change any editor state.
3401    ///
3402    /// Promoted to the public surface in 0.6.X for Phase 4b text-object grammar
3403    /// migration (kryptic-sh/hjkl#70).
3404    pub fn text_object_around_big_word(&self) -> Option<((usize, usize), (usize, usize))> {
3405        vim::text_object_around_big_word_bridge(self)
3406    }
3407
3408    // ─── Phase 4c: pub text-object resolution — quote + bracket (hjkl#70) ───
3409    //
3410    // Pure functions — no cursor mutation, no mode change, no register write.
3411    // Each method delegates to `vim::text_object_*_bridge`, which in turn calls
3412    // the existing private resolvers (`quote_text_object`, `bracket_text_object`)
3413    // in vim.rs.
3414    //
3415    // Quote methods take the quote char itself (`'"'`, `'\''`, `` '`' ``).
3416    // Bracket methods take the OPEN bracket char (`'('`, `'{'`, `'['`, `'<'`);
3417    // close-bracket variants (`)`, `}`, `]`, `>`) are NOT accepted here — the
3418    // hjkl-vim grammar layer normalises close→open before calling these methods.
3419    //
3420    // Return value: `Some((start, end))` where both positions are `(row, col)`
3421    // byte-column pairs and `end` is *exclusive* (one past the last byte to act
3422    // on), matching the convention used by `delete_range` / `yank_range` / etc.
3423    // `bracket_text_object` internally distinguishes Linewise vs Exclusive
3424    // ranges for multi-line pairs; that tag is stripped here — callers receive
3425    // the same flat shape as all other text-object resolvers.
3426
3427    /// Resolve the range of `i<quote>` (inner quote) at the cursor position.
3428    ///
3429    /// `quote` is one of `'"'`, `'\''`, or `` '`' ``. Returns `None` when the
3430    /// cursor's line contains fewer than two occurrences of `quote`, or when no
3431    /// matching pair can be found around or ahead of the cursor.
3432    ///
3433    /// Inner range excludes the quote characters themselves.
3434    ///
3435    /// Pure function — no cursor mutation.
3436    ///
3437    /// Promoted to the public surface in 0.6.X for Phase 4c text-object grammar
3438    /// migration (kryptic-sh/hjkl#70).
3439    pub fn text_object_inner_quote(&self, quote: char) -> Option<((usize, usize), (usize, usize))> {
3440        vim::text_object_inner_quote_bridge(self, quote)
3441    }
3442
3443    /// Resolve the range of `a<quote>` (around quote) at the cursor position.
3444    ///
3445    /// Like `i<quote>` but includes the quote characters themselves plus
3446    /// surrounding whitespace on one side: trailing whitespace after the closing
3447    /// quote if any exists; otherwise leading whitespace before the opening
3448    /// quote. This matches vim `:help text-objects` behaviour.
3449    ///
3450    /// Pure function — no cursor mutation.
3451    ///
3452    /// Promoted to the public surface in 0.6.X for Phase 4c text-object grammar
3453    /// migration (kryptic-sh/hjkl#70).
3454    pub fn text_object_around_quote(
3455        &self,
3456        quote: char,
3457    ) -> Option<((usize, usize), (usize, usize))> {
3458        vim::text_object_around_quote_bridge(self, quote)
3459    }
3460
3461    /// Resolve the range of `i<bracket>` (inner bracket pair) at the cursor.
3462    ///
3463    /// `open` must be one of `'('`, `'{'`, `'['`, `'<'` — the corresponding
3464    /// close bracket is derived automatically. Close-bracket chars (`)`, `}`,
3465    /// `]`, `>`) are **not** accepted; hjkl-vim normalises close→open before
3466    /// calling this method. Returns `None` when no enclosing pair is found.
3467    ///
3468    /// The cursor may be anywhere inside the pair or on a bracket character
3469    /// itself. When not inside any pair the resolver falls back to a forward
3470    /// scan (targets.vim-style: `ci(` works when the cursor is before `(`).
3471    ///
3472    /// Inner range excludes the bracket characters. Multi-line pairs are
3473    /// supported; the returned range spans the full content between the
3474    /// brackets.
3475    ///
3476    /// Pure function — no cursor mutation.
3477    ///
3478    /// `ib` / `iB` aliases live in the hjkl-vim grammar layer and are not
3479    /// handled here.
3480    ///
3481    /// Promoted to the public surface in 0.6.X for Phase 4c text-object grammar
3482    /// migration (kryptic-sh/hjkl#70).
3483    pub fn text_object_inner_bracket(
3484        &self,
3485        open: char,
3486    ) -> Option<((usize, usize), (usize, usize))> {
3487        vim::text_object_inner_bracket_bridge(self, open)
3488    }
3489
3490    /// Resolve the range of `a<bracket>` (around bracket pair) at the cursor.
3491    ///
3492    /// Like `i<bracket>` but includes the bracket characters themselves.
3493    /// `open` must be one of `'('`, `'{'`, `'['`, `'<'`.
3494    ///
3495    /// Pure function — no cursor mutation.
3496    ///
3497    /// `aB` alias lives in the hjkl-vim grammar layer and is not handled here.
3498    ///
3499    /// Promoted to the public surface in 0.6.X for Phase 4c text-object grammar
3500    /// migration (kryptic-sh/hjkl#70).
3501    pub fn text_object_around_bracket(
3502        &self,
3503        open: char,
3504    ) -> Option<((usize, usize), (usize, usize))> {
3505        vim::text_object_around_bracket_bridge(self, open)
3506    }
3507
3508    // ── Sentence text objects (is / as) ───────────────────────────────────
3509
3510    /// Resolve `is` (inner sentence) at the cursor position.
3511    ///
3512    /// Returns the range of the current sentence, excluding trailing
3513    /// whitespace. Sentence boundaries follow vim's `is` semantics (period /
3514    /// `?` / `!` followed by whitespace or end-of-paragraph).
3515    ///
3516    /// Pure function — no cursor mutation.
3517    ///
3518    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
3519    /// grammar migration (kryptic-sh/hjkl#70).
3520    pub fn text_object_inner_sentence(&self) -> Option<((usize, usize), (usize, usize))> {
3521        vim::text_object_inner_sentence_bridge(self)
3522    }
3523
3524    /// Resolve `as` (around sentence) at the cursor position.
3525    ///
3526    /// Like `is` but includes trailing whitespace after the sentence
3527    /// terminator.
3528    ///
3529    /// Pure function — no cursor mutation.
3530    ///
3531    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
3532    /// grammar migration (kryptic-sh/hjkl#70).
3533    pub fn text_object_around_sentence(&self) -> Option<((usize, usize), (usize, usize))> {
3534        vim::text_object_around_sentence_bridge(self)
3535    }
3536
3537    // ── Paragraph text objects (ip / ap) ──────────────────────────────────
3538
3539    /// Resolve `ip` (inner paragraph) at the cursor position.
3540    ///
3541    /// A paragraph is a block of non-blank lines bounded by blank lines or
3542    /// buffer edges. Returns `None` when the cursor is on a blank line.
3543    ///
3544    /// Pure function — no cursor mutation.
3545    ///
3546    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
3547    /// grammar migration (kryptic-sh/hjkl#70).
3548    pub fn text_object_inner_paragraph(&self) -> Option<((usize, usize), (usize, usize))> {
3549        vim::text_object_inner_paragraph_bridge(self)
3550    }
3551
3552    /// Resolve `ap` (around paragraph) at the cursor position.
3553    ///
3554    /// Like `ip` but includes one trailing blank line when present.
3555    ///
3556    /// Pure function — no cursor mutation.
3557    ///
3558    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
3559    /// grammar migration (kryptic-sh/hjkl#70).
3560    pub fn text_object_around_paragraph(&self) -> Option<((usize, usize), (usize, usize))> {
3561        vim::text_object_around_paragraph_bridge(self)
3562    }
3563
3564    // ── Tag text objects (it / at) ────────────────────────────────────────
3565
3566    /// Resolve `it` (inner tag) at the cursor position.
3567    ///
3568    /// Matches XML/HTML-style `<tag>...</tag>` pairs. Returns the range of
3569    /// inner content between the open and close tags (excluding the tags
3570    /// themselves).
3571    ///
3572    /// Pure function — no cursor mutation.
3573    ///
3574    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
3575    /// grammar migration (kryptic-sh/hjkl#70).
3576    pub fn text_object_inner_tag(&self) -> Option<((usize, usize), (usize, usize))> {
3577        vim::text_object_inner_tag_bridge(self)
3578    }
3579
3580    /// Resolve `at` (around tag) at the cursor position.
3581    ///
3582    /// Like `it` but includes the open and close tag delimiters themselves.
3583    ///
3584    /// Pure function — no cursor mutation.
3585    ///
3586    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
3587    /// grammar migration (kryptic-sh/hjkl#70).
3588    pub fn text_object_around_tag(&self) -> Option<((usize, usize), (usize, usize))> {
3589        vim::text_object_around_tag_bridge(self)
3590    }
3591
3592    /// Execute a named cursor motion `kind` repeated `count` times.
3593    ///
3594    /// Maps the keymap-layer `crate::MotionKind` to the engine's internal
3595    /// motion primitives, bypassing the engine FSM. Identical cursor semantics
3596    /// to the FSM path — sticky column, scroll sync, and big-jump tracking are
3597    /// all applied via `vim::execute_motion` (for Down/Up) or the same helpers
3598    /// used by the FSM arms.
3599    ///
3600    /// Introduced in 0.6.1 as the host entry point for Phase 3a of
3601    /// kryptic-sh/hjkl#69: the app keymap dispatches `AppAction::Motion` and
3602    /// calls this method rather than re-entering the engine FSM.
3603    ///
3604    /// Engine FSM arms for `h`/`j`/`k`/`l`/`<BS>`/`<Space>`/`+`/`-` remain
3605    /// intact for macro-replay coverage (macros re-feed raw keys through the
3606    /// FSM). This method is the keymap / controller path only.
3607    pub fn apply_motion(&mut self, kind: crate::MotionKind, count: usize) {
3608        vim::apply_motion_kind(self, kind, count);
3609    }
3610
3611    /// Set `vim.pending_register` to `Some(reg)` if `reg` is a valid register
3612    /// selector (`a`–`z`, `A`–`Z`, `0`–`9`, `"`, `+`, `*`, `_`). Invalid
3613    /// chars are silently ignored (no-op), matching the engine FSM's
3614    /// `handle_select_register` behaviour.
3615    ///
3616    /// Promoted to the public surface in 0.5.17 so the hjkl-vim
3617    /// `PendingState::SelectRegister` reducer can dispatch `SetPendingRegister`
3618    /// without re-entering the engine FSM. `handle_select_register` (engine FSM
3619    /// path for macro-replay / defensive coverage) delegates here to avoid
3620    /// logic duplication.
3621    pub fn set_pending_register(&mut self, reg: char) {
3622        if reg.is_ascii_alphanumeric() || matches!(reg, '"' | '+' | '*' | '_') {
3623            self.vim.pending_register = Some(reg);
3624        }
3625        // Invalid chars silently no-op (matches engine FSM behavior).
3626    }
3627
3628    /// Record a mark named `ch` at the current cursor position.
3629    ///
3630    /// Validates `ch` (must be `a`–`z` or `A`–`Z` to match vim's mark-name
3631    /// rules). Invalid chars are silently ignored (no-op), matching the engine
3632    /// FSM's `handle_set_mark` behaviour.
3633    ///
3634    /// Promoted to the public surface in 0.6.7 so the hjkl-vim
3635    /// `PendingState::SetMark` reducer can dispatch `EngineCmd::SetMark`
3636    /// without re-entering the engine FSM. `handle_set_mark` delegates here.
3637    pub fn set_mark_at_cursor(&mut self, ch: char) {
3638        vim::set_mark_at_cursor(self, ch);
3639    }
3640
3641    /// `.` dot-repeat: replay the last buffered change at the current cursor.
3642    /// `count` scales repeats (e.g. `3.` runs the last change 3 times). When
3643    /// `count` is 0, defaults to 1. No-op when no change has been buffered yet.
3644    ///
3645    /// Storage of `LastChange` stays inside engine for now; Phase 5c of
3646    /// kryptic-sh/hjkl#71 just lifts the `.` chord binding into the app
3647    /// keymap so the engine FSM `.` arm is no longer the entry point. Engine
3648    /// FSM `.` arm stays for macro-replay defensive coverage.
3649    pub fn replay_last_change(&mut self, count: usize) {
3650        vim::replay_last_change(self, count);
3651    }
3652
3653    /// Jump to the mark named `ch`, linewise (row only; col snaps to first
3654    /// non-blank). Pushes the pre-jump position onto the jumplist if the
3655    /// cursor actually moved.
3656    ///
3657    /// Accepts the same mark chars as vim's `'<ch>` command: `a`–`z`,
3658    /// `A`–`Z`, `'`/`` ` `` (jump-back peek), `.` (last edit), and the
3659    /// special auto-marks `[`, `]`, `<`, `>`. Unset marks and invalid chars
3660    /// are silently ignored (no-op), matching the engine FSM's
3661    /// `handle_goto_mark` behaviour.
3662    ///
3663    /// Promoted to the public surface in 0.6.7 so the hjkl-vim
3664    /// `PendingState::GotoMarkLine` reducer can dispatch
3665    /// `EngineCmd::GotoMarkLine` without re-entering the engine FSM.
3666    pub fn goto_mark_line(&mut self, ch: char) {
3667        vim::goto_mark(self, ch, true);
3668    }
3669
3670    /// Jump to the mark named `ch`, charwise (exact row + col). Pushes the
3671    /// pre-jump position onto the jumplist if the cursor actually moved.
3672    ///
3673    /// Accepts the same mark chars as vim's `` `<ch> `` command: `a`–`z`,
3674    /// `A`–`Z`, `'`/`` ` `` (jump-back peek), `.` (last edit), and the
3675    /// special auto-marks `[`, `]`, `<`, `>`. Unset marks and invalid chars
3676    /// are silently ignored (no-op), matching the engine FSM's
3677    /// `handle_goto_mark` behaviour.
3678    ///
3679    /// Promoted to the public surface in 0.6.7 so the hjkl-vim
3680    /// `PendingState::GotoMarkChar` reducer can dispatch
3681    /// `EngineCmd::GotoMarkChar` without re-entering the engine FSM.
3682    pub fn goto_mark_char(&mut self, ch: char) {
3683        vim::goto_mark(self, ch, false);
3684    }
3685
3686    // ── Macro controller API (Phase 5b) ──────────────────────────────────────
3687
3688    /// Begin recording keystrokes into register `reg`. The caller (app) is
3689    /// responsible for stopping the recording via `stop_macro_record` when the
3690    /// user presses bare `q`.
3691    ///
3692    /// - Uppercase `reg` (e.g. `'A'`) appends to the existing lowercase
3693    ///   recording by pre-seeding `recording_keys` with the decoded text of the
3694    ///   matching lowercase register, matching vim's capital-register append
3695    ///   semantics.
3696    /// - Lowercase `reg` clears `recording_keys` (fresh recording).
3697    /// - Invalid chars (non-alphabetic, non-digit) are silently ignored.
3698    ///
3699    /// Promoted to the public surface in Phase 5b so the app's
3700    /// `route_chord_key` can start a recording without re-entering the engine
3701    /// FSM. `handle_record_macro_target` (engine FSM path for macro-replay
3702    /// defensive coverage) continues to use the same logic via delegation.
3703    pub fn start_macro_record(&mut self, reg: char) {
3704        if !(reg.is_ascii_alphabetic() || reg.is_ascii_digit()) {
3705            return;
3706        }
3707        self.vim.recording_macro = Some(reg);
3708        if reg.is_ascii_uppercase() {
3709            // Seed recording_keys with the existing lowercase register's text
3710            // decoded back to inputs so capital-register append continues from
3711            // where the previous recording left off.
3712            let lower = reg.to_ascii_lowercase();
3713            let text = self
3714                .registers
3715                .read(lower)
3716                .map(|s| s.text.clone())
3717                .unwrap_or_default();
3718            self.vim.recording_keys = crate::input::decode_macro(&text);
3719        } else {
3720            self.vim.recording_keys.clear();
3721        }
3722    }
3723
3724    /// Finalize the active recording: encode `recording_keys` as text and write
3725    /// to the matching (lowercase) named register. Clears both `recording_macro`
3726    /// and `recording_keys`. No-ops if no recording is active.
3727    ///
3728    /// Promoted to the public surface in Phase 5b so the app's `QChord` action
3729    /// can stop a recording when the user presses bare `q` without re-entering
3730    /// the engine FSM.
3731    pub fn stop_macro_record(&mut self) {
3732        let Some(reg) = self.vim.recording_macro.take() else {
3733            return;
3734        };
3735        let keys = std::mem::take(&mut self.vim.recording_keys);
3736        let text = crate::input::encode_macro(&keys);
3737        self.set_named_register_text(reg.to_ascii_lowercase(), text);
3738    }
3739
3740    /// Returns `true` while a `q{reg}` recording is in progress.
3741    /// Hosts use this to show a "recording @r" status indicator and to decide
3742    /// whether bare `q` should stop the recording or open the `RecordMacroTarget`
3743    /// chord.
3744    pub fn is_recording_macro(&self) -> bool {
3745        self.vim.recording_macro.is_some()
3746    }
3747
3748    /// Returns `true` while a macro is being replayed. The app sets this flag
3749    /// (via `play_macro`) and clears it (via `end_macro_replay`) around the
3750    /// re-feed loop so the recorder hook can skip double-capture.
3751    pub fn is_replaying_macro(&self) -> bool {
3752        self.vim.replaying_macro
3753    }
3754
3755    /// Decode the named register `reg` into a `Vec<crate::input::Input>` and
3756    /// prepare for replay, returning the inputs the app should re-feed through
3757    /// `route_chord_key`.
3758    ///
3759    /// Resolves `reg`:
3760    /// - `'@'` → use `vim.last_macro`; returns empty vec if none.
3761    /// - Any other char → lowercase it, read the register, decode.
3762    ///
3763    /// Side-effects:
3764    /// - Sets `vim.last_macro` to the resolved register.
3765    /// - Sets `vim.replaying_macro = true` so the recorder hook skips during
3766    ///   replay. The app calls `end_macro_replay` after the loop finishes.
3767    ///
3768    /// Returns an empty vec (and no side-effects for `'@'`) if the register is
3769    /// unset or empty.
3770    pub fn play_macro(&mut self, reg: char, count: usize) -> Vec<crate::input::Input> {
3771        let resolved = if reg == '@' {
3772            match self.vim.last_macro {
3773                Some(r) => r,
3774                None => return vec![],
3775            }
3776        } else {
3777            reg.to_ascii_lowercase()
3778        };
3779        let text = match self.registers.read(resolved) {
3780            Some(slot) if !slot.text.is_empty() => slot.text.clone(),
3781            _ => return vec![],
3782        };
3783        let keys = crate::input::decode_macro(&text);
3784        self.vim.last_macro = Some(resolved);
3785        self.vim.replaying_macro = true;
3786        // Multiply by count (minimum 1).
3787        keys.repeat(count.max(1))
3788    }
3789
3790    /// Clear the `replaying_macro` flag. Called by the app after the
3791    /// re-feed loop in the `PlayMacro` commit arm completes (or aborts).
3792    pub fn end_macro_replay(&mut self) {
3793        self.vim.replaying_macro = false;
3794    }
3795
3796    /// Append `input` to the active recording (`recording_keys`) if and only
3797    /// if a recording is in progress AND we are not currently replaying.
3798    /// Called by the app's `route_chord_key` recorder hook so that user
3799    /// keystrokes captured through the app-level chord path are recorded
3800    /// (rather than relying solely on the engine FSM's in-step hook).
3801    pub fn record_input(&mut self, input: crate::input::Input) {
3802        if self.vim.recording_macro.is_some() && !self.vim.replaying_macro {
3803            self.vim.recording_keys.push(input);
3804        }
3805    }
3806
3807    // ─── Phase 6.1: public insert-mode primitives (kryptic-sh/hjkl#87) ────────
3808    //
3809    // Each method is the publicly callable form of one insert-mode action.
3810    // All logic lives in the corresponding `vim::*_bridge` free function;
3811    // these methods are thin delegators so the public surface stays on `Editor`.
3812    //
3813    // Invariants (enforced by the bridge fns):
3814    //   - Buffer mutations go through `mutate_edit` (dirty/undo/change-list).
3815    //   - Navigation keys call `break_undo_group_in_insert` when the FSM did.
3816    //   - `push_buffer_cursor_to_textarea` is called after every mutation
3817    //     (currently a no-op, kept for migration hygiene).
3818
3819    /// Insert `ch` at the cursor. In Replace mode, overstrike the cell under
3820    /// the cursor instead of inserting; at end-of-line, always appends. With
3821    /// `smartindent` on, closing brackets (`}`/`)`/`]`) trigger one-unit
3822    /// dedent on an otherwise-whitespace line.
3823    ///
3824    /// Callers must ensure the editor is in Insert or Replace mode before
3825    /// calling this method.
3826    pub fn insert_char(&mut self, ch: char) {
3827        let mutated = vim::insert_char_bridge(self, ch);
3828        if mutated {
3829            self.mark_content_dirty();
3830            let (row, _) = self.cursor();
3831            self.vim.widen_insert_row(row);
3832        }
3833    }
3834
3835    /// Insert a newline at the cursor, applying autoindent / smartindent to
3836    /// prefix the new line with the appropriate leading whitespace.
3837    ///
3838    /// Callers must ensure the editor is in Insert mode before calling.
3839    pub fn insert_newline(&mut self) {
3840        let mutated = vim::insert_newline_bridge(self);
3841        if mutated {
3842            self.mark_content_dirty();
3843            let (row, _) = self.cursor();
3844            self.vim.widen_insert_row(row);
3845        }
3846    }
3847
3848    /// Insert a tab character (or spaces up to the next `softtabstop` boundary
3849    /// when `expandtab` is set).
3850    ///
3851    /// Callers must ensure the editor is in Insert mode before calling.
3852    pub fn insert_tab(&mut self) {
3853        let mutated = vim::insert_tab_bridge(self);
3854        if mutated {
3855            self.mark_content_dirty();
3856            let (row, _) = self.cursor();
3857            self.vim.widen_insert_row(row);
3858        }
3859    }
3860
3861    /// Delete the character before the cursor (Backspace). With `softtabstop`
3862    /// active, deletes the entire soft-tab run at an aligned boundary. Joins
3863    /// with the previous line when at column 0.
3864    ///
3865    /// Callers must ensure the editor is in Insert mode before calling.
3866    pub fn insert_backspace(&mut self) {
3867        let mutated = vim::insert_backspace_bridge(self);
3868        if mutated {
3869            self.mark_content_dirty();
3870            let (row, _) = self.cursor();
3871            self.vim.widen_insert_row(row);
3872        }
3873    }
3874
3875    /// Delete the character under the cursor (Delete key). Joins with the
3876    /// next line when at end-of-line.
3877    ///
3878    /// Callers must ensure the editor is in Insert mode before calling.
3879    pub fn insert_delete(&mut self) {
3880        let mutated = vim::insert_delete_bridge(self);
3881        if mutated {
3882            self.mark_content_dirty();
3883            let (row, _) = self.cursor();
3884            self.vim.widen_insert_row(row);
3885        }
3886    }
3887
3888    /// Move the cursor one step in `dir` (arrow key), breaking the undo group
3889    /// per `undo_break_on_motion`.
3890    ///
3891    /// Callers must ensure the editor is in Insert mode before calling.
3892    pub fn insert_arrow(&mut self, dir: vim::InsertDir) {
3893        vim::insert_arrow_bridge(self, dir);
3894        let (row, _) = self.cursor();
3895        self.vim.widen_insert_row(row);
3896    }
3897
3898    /// Move the cursor to the start of the current line (Home key), breaking
3899    /// the undo group.
3900    ///
3901    /// Callers must ensure the editor is in Insert mode before calling.
3902    pub fn insert_home(&mut self) {
3903        vim::insert_home_bridge(self);
3904        let (row, _) = self.cursor();
3905        self.vim.widen_insert_row(row);
3906    }
3907
3908    /// Move the cursor to the end of the current line (End key), breaking the
3909    /// undo group.
3910    ///
3911    /// Callers must ensure the editor is in Insert mode before calling.
3912    pub fn insert_end(&mut self) {
3913        vim::insert_end_bridge(self);
3914        let (row, _) = self.cursor();
3915        self.vim.widen_insert_row(row);
3916    }
3917
3918    /// Scroll up one full viewport height (PageUp), moving the cursor with it.
3919    /// `viewport_h` is the current viewport height in rows; pass
3920    /// `self.viewport_height_value()` if the stored value is current.
3921    ///
3922    /// Callers must ensure the editor is in Insert mode before calling.
3923    pub fn insert_pageup(&mut self, viewport_h: u16) {
3924        vim::insert_pageup_bridge(self, viewport_h);
3925        let (row, _) = self.cursor();
3926        self.vim.widen_insert_row(row);
3927    }
3928
3929    /// Scroll down one full viewport height (PageDown), moving the cursor with
3930    /// it. `viewport_h` is the current viewport height in rows.
3931    ///
3932    /// Callers must ensure the editor is in Insert mode before calling.
3933    pub fn insert_pagedown(&mut self, viewport_h: u16) {
3934        vim::insert_pagedown_bridge(self, viewport_h);
3935        let (row, _) = self.cursor();
3936        self.vim.widen_insert_row(row);
3937    }
3938
3939    /// Delete from the cursor back to the start of the previous word (`Ctrl-W`).
3940    /// At column 0, joins with the previous line (vim `b`-motion semantics).
3941    ///
3942    /// Callers must ensure the editor is in Insert mode before calling.
3943    pub fn insert_ctrl_w(&mut self) {
3944        let mutated = vim::insert_ctrl_w_bridge(self);
3945        if mutated {
3946            self.mark_content_dirty();
3947            let (row, _) = self.cursor();
3948            self.vim.widen_insert_row(row);
3949        }
3950    }
3951
3952    /// Delete from the cursor back to the start of the current line (`Ctrl-U`).
3953    /// No-op when already at column 0.
3954    ///
3955    /// Callers must ensure the editor is in Insert mode before calling.
3956    pub fn insert_ctrl_u(&mut self) {
3957        let mutated = vim::insert_ctrl_u_bridge(self);
3958        if mutated {
3959            self.mark_content_dirty();
3960            let (row, _) = self.cursor();
3961            self.vim.widen_insert_row(row);
3962        }
3963    }
3964
3965    /// Delete one character backwards (`Ctrl-H`) — alias for Backspace in
3966    /// insert mode. Joins with the previous line when at col 0.
3967    ///
3968    /// Callers must ensure the editor is in Insert mode before calling.
3969    pub fn insert_ctrl_h(&mut self) {
3970        let mutated = vim::insert_ctrl_h_bridge(self);
3971        if mutated {
3972            self.mark_content_dirty();
3973            let (row, _) = self.cursor();
3974            self.vim.widen_insert_row(row);
3975        }
3976    }
3977
3978    /// Enter "one-shot normal" mode (`Ctrl-O`): suspend insert for the next
3979    /// complete normal-mode command, then return to insert automatically.
3980    ///
3981    /// Callers must ensure the editor is in Insert mode before calling.
3982    pub fn insert_ctrl_o_arm(&mut self) {
3983        vim::insert_ctrl_o_bridge(self);
3984    }
3985
3986    /// Arm the register-paste selector (`Ctrl-R`). The next call to
3987    /// `insert_paste_register(reg)` will insert the register contents.
3988    /// Alternatively, feeding a `Key::Char(c)` through the FSM will consume
3989    /// the armed state and paste register `c`.
3990    ///
3991    /// Callers must ensure the editor is in Insert mode before calling.
3992    pub fn insert_ctrl_r_arm(&mut self) {
3993        vim::insert_ctrl_r_bridge(self);
3994    }
3995
3996    /// Indent the current line by one `shiftwidth` and shift the cursor right
3997    /// by the same amount (`Ctrl-T`).
3998    ///
3999    /// Callers must ensure the editor is in Insert mode before calling.
4000    pub fn insert_ctrl_t(&mut self) {
4001        let mutated = vim::insert_ctrl_t_bridge(self);
4002        if mutated {
4003            self.mark_content_dirty();
4004            let (row, _) = self.cursor();
4005            self.vim.widen_insert_row(row);
4006        }
4007    }
4008
4009    /// Outdent the current line by up to one `shiftwidth` and shift the cursor
4010    /// left by the amount stripped (`Ctrl-D`).
4011    ///
4012    /// Callers must ensure the editor is in Insert mode before calling.
4013    pub fn insert_ctrl_d(&mut self) {
4014        let mutated = vim::insert_ctrl_d_bridge(self);
4015        if mutated {
4016            self.mark_content_dirty();
4017            let (row, _) = self.cursor();
4018            self.vim.widen_insert_row(row);
4019        }
4020    }
4021
4022    /// Paste the contents of register `reg` at the cursor (the commit arm of
4023    /// `Ctrl-R {reg}`). Unknown or empty registers are a no-op.
4024    ///
4025    /// Callers must ensure the editor is in Insert mode before calling.
4026    pub fn insert_paste_register(&mut self, reg: char) {
4027        vim::insert_paste_register_bridge(self, reg);
4028        let (row, _) = self.cursor();
4029        self.vim.widen_insert_row(row);
4030    }
4031
4032    /// Exit insert mode to Normal: finish the insert session, step the cursor
4033    /// one cell left (vim convention on Esc), record the `gi` target position,
4034    /// and update the sticky column.
4035    ///
4036    /// Callers must ensure the editor is in Insert mode before calling.
4037    pub fn leave_insert_to_normal(&mut self) {
4038        vim::leave_insert_to_normal_bridge(self);
4039    }
4040
4041    // ── Phase 6.2: normal-mode primitive controller methods ───────────────────
4042    //
4043    // Each method is a thin wrapper around a `pub(crate) fn *_bridge` in
4044    // `vim.rs` following the same pattern as Phase 6.1. The FSM's
4045    // `handle_normal_only` now calls the same bridges so both paths are
4046    // identical. See kryptic-sh/hjkl#88 for the full promotion plan.
4047
4048    /// `i` — transition to Insert mode at the current cursor position.
4049    /// `count` is stored in the insert session and replayed by dot-repeat
4050    /// as a repeat count on the inserted text.
4051    pub fn enter_insert_i(&mut self, count: usize) {
4052        vim::enter_insert_i_bridge(self, count);
4053    }
4054
4055    /// `I` — move to the first non-blank character on the line, then
4056    /// transition to Insert mode. `count` is stored for dot-repeat.
4057    pub fn enter_insert_shift_i(&mut self, count: usize) {
4058        vim::enter_insert_shift_i_bridge(self, count);
4059    }
4060
4061    /// `a` — advance the cursor one cell past the current position, then
4062    /// transition to Insert mode (append). `count` is stored for dot-repeat.
4063    pub fn enter_insert_a(&mut self, count: usize) {
4064        vim::enter_insert_a_bridge(self, count);
4065    }
4066
4067    /// `A` — move the cursor to the end of the line, then transition to
4068    /// Insert mode (append at end). `count` is stored for dot-repeat.
4069    pub fn enter_insert_shift_a(&mut self, count: usize) {
4070        vim::enter_insert_shift_a_bridge(self, count);
4071    }
4072
4073    /// `o` — open a new line below the current line with smart-indent, then
4074    /// transition to Insert mode. `count` is stored for dot-repeat replay.
4075    pub fn open_line_below(&mut self, count: usize) {
4076        vim::open_line_below_bridge(self, count);
4077    }
4078
4079    /// `O` — open a new line above the current line with smart-indent, then
4080    /// transition to Insert mode. `count` is stored for dot-repeat replay.
4081    pub fn open_line_above(&mut self, count: usize) {
4082        vim::open_line_above_bridge(self, count);
4083    }
4084
4085    /// `R` — enter Replace mode: subsequent typed characters overstrike the
4086    /// cell under the cursor rather than inserting. `count` is for replay.
4087    pub fn enter_replace_mode(&mut self, count: usize) {
4088        vim::enter_replace_mode_bridge(self, count);
4089    }
4090
4091    /// `x` — delete `count` characters forward from the cursor and write them
4092    /// to the unnamed register. No-op on an empty line. Records for `.`.
4093    pub fn delete_char_forward(&mut self, count: usize) {
4094        vim::delete_char_forward_bridge(self, count);
4095    }
4096
4097    /// `X` — delete `count` characters backward from the cursor and write
4098    /// them to the unnamed register. No-op at column 0. Records for `.`.
4099    pub fn delete_char_backward(&mut self, count: usize) {
4100        vim::delete_char_backward_bridge(self, count);
4101    }
4102
4103    /// `s` — substitute `count` characters: delete them (writing to the
4104    /// unnamed register) then enter Insert mode. Equivalent to `cl`.
4105    /// Records as `OpMotion { Change, Right }` for dot-repeat.
4106    pub fn substitute_char(&mut self, count: usize) {
4107        vim::substitute_char_bridge(self, count);
4108    }
4109
4110    /// `S` — substitute the current line: wipe its contents (writing to the
4111    /// unnamed register) then enter Insert mode. Equivalent to `cc`.
4112    /// Records as `LineOp { Change }` for dot-repeat.
4113    pub fn substitute_line(&mut self, count: usize) {
4114        vim::substitute_line_bridge(self, count);
4115    }
4116
4117    /// `D` — delete from the cursor to end-of-line, writing to the unnamed
4118    /// register. The cursor parks on the new last character. Records for `.`.
4119    pub fn delete_to_eol(&mut self) {
4120        vim::delete_to_eol_bridge(self);
4121    }
4122
4123    /// `C` — change from the cursor to end-of-line: delete to EOL then enter
4124    /// Insert mode. Equivalent to `c$`. Does not record its own `last_change`
4125    /// (the insert session records `DeleteToEol` on exit, like `c` motions).
4126    pub fn change_to_eol(&mut self) {
4127        vim::change_to_eol_bridge(self);
4128    }
4129
4130    /// `Y` — yank from the cursor to end-of-line into the unnamed register.
4131    /// Vim 8 default: equivalent to `y$`. `count` multiplies the motion.
4132    pub fn yank_to_eol(&mut self, count: usize) {
4133        vim::yank_to_eol_bridge(self, count);
4134    }
4135
4136    /// `J` — join `count` lines (default 2) onto the current line, inserting
4137    /// a single space between each non-empty pair. Records for dot-repeat.
4138    pub fn join_line(&mut self, count: usize) {
4139        vim::join_line_bridge(self, count);
4140    }
4141
4142    /// `~` — toggle the case of `count` characters from the cursor, advancing
4143    /// right after each toggle. Records `ToggleCase` for dot-repeat.
4144    pub fn toggle_case_at_cursor(&mut self, count: usize) {
4145        vim::toggle_case_at_cursor_bridge(self, count);
4146    }
4147
4148    /// `p` — paste the unnamed register (or the register selected via `"r`)
4149    /// after the cursor. Linewise content opens a new line below; charwise
4150    /// content is inserted inline. Records `Paste { before: false }` for `.`.
4151    pub fn paste_after(&mut self, count: usize) {
4152        vim::paste_after_bridge(self, count);
4153    }
4154
4155    /// `P` — paste the unnamed register (or the `"r` register) before the
4156    /// cursor. Linewise content opens a new line above; charwise is inline.
4157    /// Records `Paste { before: true }` for dot-repeat.
4158    pub fn paste_before(&mut self, count: usize) {
4159        vim::paste_before_bridge(self, count);
4160    }
4161
4162    /// `<C-o>` — jump back `count` entries in the jumplist, saving the
4163    /// current position on the forward stack so `<C-i>` can return.
4164    pub fn jump_back(&mut self, count: usize) {
4165        vim::jump_back_bridge(self, count);
4166    }
4167
4168    /// `<C-i>` / `Tab` — redo `count` entries on the forward jumplist stack,
4169    /// saving the current position on the backward stack.
4170    pub fn jump_forward(&mut self, count: usize) {
4171        vim::jump_forward_bridge(self, count);
4172    }
4173
4174    /// `<C-f>` / `<C-b>` — scroll the cursor by one full viewport height
4175    /// (height − 2 rows, preserving two-line overlap). `count` multiplies.
4176    /// `dir = Down` for `<C-f>`, `Up` for `<C-b>`.
4177    pub fn scroll_full_page(&mut self, dir: vim::ScrollDir, count: usize) {
4178        vim::scroll_full_page_bridge(self, dir, count);
4179    }
4180
4181    /// `<C-d>` / `<C-u>` — scroll the cursor by half the viewport height.
4182    /// `count` multiplies the step. `dir = Down` for `<C-d>`, `Up` for `<C-u>`.
4183    pub fn scroll_half_page(&mut self, dir: vim::ScrollDir, count: usize) {
4184        vim::scroll_half_page_bridge(self, dir, count);
4185    }
4186
4187    /// `<C-e>` / `<C-y>` — scroll the viewport `count` lines without moving
4188    /// the cursor (cursor is clamped to the new visible region if necessary).
4189    /// `dir = Down` for `<C-e>` (scroll text up), `Up` for `<C-y>`.
4190    pub fn scroll_line(&mut self, dir: vim::ScrollDir, count: usize) {
4191        vim::scroll_line_bridge(self, dir, count);
4192    }
4193
4194    /// `n` — repeat the last `/` or `?` search `count` times in its original
4195    /// direction. `forward = true` keeps the direction; `false` inverts (`N`).
4196    pub fn search_repeat(&mut self, forward: bool, count: usize) {
4197        vim::search_repeat_bridge(self, forward, count);
4198    }
4199
4200    /// `*` / `#` / `g*` / `g#` — search for the word under the cursor.
4201    /// `forward` chooses direction; `whole_word` wraps the pattern in `\b`
4202    /// anchors (true for `*` / `#`, false for `g*` / `g#`). `count` repeats.
4203    pub fn word_search(&mut self, forward: bool, whole_word: bool, count: usize) {
4204        vim::word_search_bridge(self, forward, whole_word, count);
4205    }
4206
4207    // ── Phase 6.3: visual-mode primitive controller methods ──────────────────
4208    //
4209    // Each method is a thin wrapper around a `pub(crate) fn *_bridge` in
4210    // `vim.rs` following the same pattern as Phase 6.1 / 6.2. Both the FSM
4211    // and these wrappers write `current_mode` so `vim_mode()` returns correct
4212    // values regardless of which path performed the transition.
4213    // See kryptic-sh/hjkl#89 for the full promotion plan.
4214
4215    /// `v` from Normal — enter charwise Visual mode, anchoring the selection
4216    /// at the current cursor position.
4217    pub fn enter_visual_char(&mut self) {
4218        vim::enter_visual_char_bridge(self);
4219    }
4220
4221    /// `V` from Normal — enter linewise Visual mode, anchoring on the current
4222    /// line. Motions extend the selection by whole lines.
4223    pub fn enter_visual_line(&mut self) {
4224        vim::enter_visual_line_bridge(self);
4225    }
4226
4227    /// `<C-v>` from Normal — enter Visual-block mode. The selection is a
4228    /// rectangle whose corners are the anchor and the live cursor.
4229    pub fn enter_visual_block(&mut self) {
4230        vim::enter_visual_block_bridge(self);
4231    }
4232
4233    /// Esc from any visual mode — set `<` / `>` marks, stash the selection
4234    /// for `gv` re-entry, then return to Normal mode.
4235    pub fn exit_visual_to_normal(&mut self) {
4236        vim::exit_visual_to_normal_bridge(self);
4237    }
4238
4239    /// `o` in Visual / VisualLine / VisualBlock — swap the cursor and anchor
4240    /// so the user can extend the other end of the selection. Does NOT
4241    /// mutate the selection range; only the active endpoint changes.
4242    pub fn visual_o_toggle(&mut self) {
4243        vim::visual_o_toggle_bridge(self);
4244    }
4245
4246    /// `gv` — restore the last visual selection (mode + anchor + cursor
4247    /// position). No-op when no visual selection has been exited yet.
4248    pub fn reenter_last_visual(&mut self) {
4249        vim::reenter_last_visual_bridge(self);
4250    }
4251
4252    /// Direct mode-transition entry point. Sets both the internal FSM mode
4253    /// and the stable `current_mode` field read by [`Editor::vim_mode`].
4254    ///
4255    /// Prefer the semantic primitives (`enter_visual_char`, `enter_insert_i`,
4256    /// …) which also set up required bookkeeping (anchors, sessions, …).
4257    /// Use `set_mode` only when you need a raw mode flip without side-effects.
4258    pub fn set_mode(&mut self, mode: VimMode) {
4259        vim::set_mode_bridge(self, mode);
4260    }
4261}
4262
4263// ── Phase 6.6b: FSM state accessors (for hjkl-vim ownership) ─────────────────
4264//
4265// The FSM (now in hjkl-vim) reads/writes `VimState` fields through public
4266// `Editor` accessors and mutators defined in this block. Each method gets a
4267// one-line `///` rustdoc. Fields mutated as a unit get a combined action method
4268// rather than individual getters + setters (e.g. `accumulate_count_digit`).
4269
4270/// State carried between [`Editor::begin_step`] and [`Editor::end_step`].
4271///
4272/// Treat as opaque — construct by calling `begin_step` and pass the
4273/// returned value directly into `end_step` without modification.
4274/// The fields capture per-step pre-dispatch state that the epilogue
4275/// needs to run its invariants correctly.
4276pub struct StepBookkeeping {
4277    /// True when the pending chord before this step was a macro-chord
4278    /// (`q{reg}` or `@{reg}`). The recorder hook skips these bookkeeping
4279    /// keys so that only the *payload* keys enter `recording_keys`.
4280    pub pending_was_macro_chord: bool,
4281    /// True when the mode was Insert *before* the FSM body ran. Used by
4282    /// the Ctrl-o one-shot-normal epilogue to decide whether to bounce
4283    /// back into Insert.
4284    pub was_insert: bool,
4285    /// Pre-dispatch visual snapshot. When the FSM body transitions out of
4286    /// a visual mode the epilogue uses this to set the `<`/`>` marks and
4287    /// store `last_visual` for `gv`.
4288    pub pre_visual_snapshot: Option<vim::LastVisual>,
4289}
4290
4291impl<H: crate::types::Host> Editor<hjkl_buffer::Buffer, H> {
4292    // ── Pending chord ─────────────────────────────────────────────────────────
4293
4294    /// Return a clone of the current pending chord state.
4295    pub fn pending(&self) -> vim::Pending {
4296        self.vim.pending.clone()
4297    }
4298
4299    /// Overwrite the pending chord state.
4300    pub fn set_pending(&mut self, p: vim::Pending) {
4301        self.vim.pending = p;
4302    }
4303
4304    /// Atomically take the pending chord, replacing it with `Pending::None`.
4305    pub fn take_pending(&mut self) -> vim::Pending {
4306        std::mem::take(&mut self.vim.pending)
4307    }
4308
4309    // ── Count prefix ──────────────────────────────────────────────────────────
4310
4311    /// Return the raw digit-prefix count (`0` = no prefix typed yet).
4312    pub fn count(&self) -> usize {
4313        self.vim.count
4314    }
4315
4316    /// Overwrite the digit-prefix count directly.
4317    pub fn set_count(&mut self, c: usize) {
4318        self.vim.count = c;
4319    }
4320
4321    /// Accumulate one more digit into the count prefix (mirrors `count * 10 + digit`).
4322    pub fn accumulate_count_digit(&mut self, digit: usize) {
4323        self.vim.count = self.vim.count.saturating_mul(10) + digit;
4324    }
4325
4326    /// Reset the count prefix to zero (no pending count).
4327    pub fn reset_count(&mut self) {
4328        self.vim.count = 0;
4329    }
4330
4331    /// Consume the count and return it; resets to zero. Returns `1` when no
4332    /// prefix was typed (mirrors `take_count` in vim.rs).
4333    pub fn take_count(&mut self) -> usize {
4334        if self.vim.count > 0 {
4335            let n = self.vim.count;
4336            self.vim.count = 0;
4337            n
4338        } else {
4339            1
4340        }
4341    }
4342
4343    // ── Internal FSM mode ─────────────────────────────────────────────────────
4344
4345    /// Return the FSM-internal mode (Normal / Insert / Visual / …).
4346    pub fn fsm_mode(&self) -> vim::Mode {
4347        self.vim.mode
4348    }
4349
4350    /// Overwrite the FSM-internal mode without side-effects. Prefer the
4351    /// semantic primitives (`enter_insert_i`, `enter_visual_char`, …).
4352    pub fn set_fsm_mode(&mut self, m: vim::Mode) {
4353        self.vim.mode = m;
4354        self.vim.current_mode = self.vim.public_mode();
4355    }
4356
4357    // ── Replaying flag ────────────────────────────────────────────────────────
4358
4359    /// `true` while the `.` dot-repeat replay is running.
4360    pub fn is_replaying(&self) -> bool {
4361        self.vim.replaying
4362    }
4363
4364    /// Set or clear the dot-replay flag.
4365    pub fn set_replaying(&mut self, v: bool) {
4366        self.vim.replaying = v;
4367    }
4368
4369    // ── One-shot normal (Ctrl-o) ──────────────────────────────────────────────
4370
4371    /// `true` when we entered Normal from Insert via `Ctrl-o` and will return
4372    /// to Insert after the next complete command.
4373    pub fn is_one_shot_normal(&self) -> bool {
4374        self.vim.one_shot_normal
4375    }
4376
4377    /// Set or clear the Ctrl-o one-shot-normal flag.
4378    pub fn set_one_shot_normal(&mut self, v: bool) {
4379        self.vim.one_shot_normal = v;
4380    }
4381
4382    // ── Last find (f/F/t/T target) ────────────────────────────────────────────
4383
4384    /// Return the last `f`/`F`/`t`/`T` target as `(char, forward, till)`, or
4385    /// `None` before any find command was executed.
4386    pub fn last_find(&self) -> Option<(char, bool, bool)> {
4387        self.vim.last_find
4388    }
4389
4390    /// Overwrite the stored last-find target.
4391    pub fn set_last_find(&mut self, target: Option<(char, bool, bool)>) {
4392        self.vim.last_find = target;
4393    }
4394
4395    // ── Last change (dot-repeat payload) ─────────────────────────────────────
4396
4397    /// Return a clone of the last recorded mutating change, or `None` before
4398    /// any change has been made.
4399    pub fn last_change(&self) -> Option<vim::LastChange> {
4400        self.vim.last_change.clone()
4401    }
4402
4403    /// Overwrite the stored last-change record.
4404    pub fn set_last_change(&mut self, lc: Option<vim::LastChange>) {
4405        self.vim.last_change = lc;
4406    }
4407
4408    /// Borrow the last-change record mutably (e.g. to fill in an `inserted`
4409    /// field after the insert session completes).
4410    pub fn last_change_mut(&mut self) -> Option<&mut vim::LastChange> {
4411        self.vim.last_change.as_mut()
4412    }
4413
4414    // ── Insert session ────────────────────────────────────────────────────────
4415
4416    /// Borrow the active insert session, or `None` when not in Insert mode.
4417    pub fn insert_session(&self) -> Option<&vim::InsertSession> {
4418        self.vim.insert_session.as_ref()
4419    }
4420
4421    /// Borrow the active insert session mutably.
4422    pub fn insert_session_mut(&mut self) -> Option<&mut vim::InsertSession> {
4423        self.vim.insert_session.as_mut()
4424    }
4425
4426    /// Atomically take the insert session out, leaving `None`.
4427    pub fn take_insert_session(&mut self) -> Option<vim::InsertSession> {
4428        self.vim.insert_session.take()
4429    }
4430
4431    /// Install a new insert session, replacing any existing one.
4432    pub fn set_insert_session(&mut self, s: Option<vim::InsertSession>) {
4433        self.vim.insert_session = s;
4434    }
4435
4436    // ── Visual anchors ────────────────────────────────────────────────────────
4437
4438    /// Return the charwise Visual-mode anchor `(row, col)`.
4439    pub fn visual_anchor(&self) -> (usize, usize) {
4440        self.vim.visual_anchor
4441    }
4442
4443    /// Overwrite the charwise Visual-mode anchor.
4444    pub fn set_visual_anchor(&mut self, anchor: (usize, usize)) {
4445        self.vim.visual_anchor = anchor;
4446    }
4447
4448    /// Return the VisualLine anchor row.
4449    pub fn visual_line_anchor(&self) -> usize {
4450        self.vim.visual_line_anchor
4451    }
4452
4453    /// Overwrite the VisualLine anchor row.
4454    pub fn set_visual_line_anchor(&mut self, row: usize) {
4455        self.vim.visual_line_anchor = row;
4456    }
4457
4458    /// Return the VisualBlock anchor `(row, col)`.
4459    pub fn block_anchor(&self) -> (usize, usize) {
4460        self.vim.block_anchor
4461    }
4462
4463    /// Overwrite the VisualBlock anchor.
4464    pub fn set_block_anchor(&mut self, anchor: (usize, usize)) {
4465        self.vim.block_anchor = anchor;
4466    }
4467
4468    /// Return the VisualBlock virtual column used to survive j/k row clamping.
4469    pub fn block_vcol(&self) -> usize {
4470        self.vim.block_vcol
4471    }
4472
4473    /// Overwrite the VisualBlock virtual column.
4474    pub fn set_block_vcol(&mut self, vcol: usize) {
4475        self.vim.block_vcol = vcol;
4476    }
4477
4478    // ── Yank linewise flag ────────────────────────────────────────────────────
4479
4480    /// `true` when the last yank/cut was linewise (affects `p`/`P` layout).
4481    pub fn yank_linewise(&self) -> bool {
4482        self.vim.yank_linewise
4483    }
4484
4485    /// Set or clear the linewise-yank flag.
4486    pub fn set_yank_linewise(&mut self, v: bool) {
4487        self.vim.yank_linewise = v;
4488    }
4489
4490    // ── Pending register selector ─────────────────────────────────────────────
4491    // Note: `pending_register()` getter already exists at line ~1254 (Phase 4e).
4492    // Only the mutators are new here.
4493
4494    /// Overwrite the pending register selector (Phase 6.6b mutator companion to
4495    /// the existing `pending_register()` getter).
4496    pub fn set_pending_register_raw(&mut self, reg: Option<char>) {
4497        self.vim.pending_register = reg;
4498    }
4499
4500    /// Atomically take the pending register, returning `None` afterward.
4501    pub fn take_pending_register_raw(&mut self) -> Option<char> {
4502        self.vim.pending_register.take()
4503    }
4504
4505    // ── Macro recording ───────────────────────────────────────────────────────
4506
4507    /// Return the register currently being recorded into, or `None`.
4508    pub fn recording_macro(&self) -> Option<char> {
4509        self.vim.recording_macro
4510    }
4511
4512    /// Overwrite the recording-macro target register.
4513    pub fn set_recording_macro(&mut self, reg: Option<char>) {
4514        self.vim.recording_macro = reg;
4515    }
4516
4517    /// Append one input to the in-progress macro recording buffer.
4518    pub fn push_recording_key(&mut self, input: crate::input::Input) {
4519        self.vim.recording_keys.push(input);
4520    }
4521
4522    /// Atomically take the recorded key sequence, leaving an empty vec.
4523    pub fn take_recording_keys(&mut self) -> Vec<crate::input::Input> {
4524        std::mem::take(&mut self.vim.recording_keys)
4525    }
4526
4527    /// Overwrite the recording-keys buffer (e.g. to seed from a register).
4528    pub fn set_recording_keys(&mut self, keys: Vec<crate::input::Input>) {
4529        self.vim.recording_keys = keys;
4530    }
4531
4532    // ── Macro replay flag ─────────────────────────────────────────────────────
4533
4534    /// `true` while `@reg` macro replay is running (suppresses re-recording).
4535    pub fn is_replaying_macro_raw(&self) -> bool {
4536        self.vim.replaying_macro
4537    }
4538
4539    /// Set or clear the macro-replay-in-progress flag.
4540    pub fn set_replaying_macro_raw(&mut self, v: bool) {
4541        self.vim.replaying_macro = v;
4542    }
4543
4544    // ── Last macro register ───────────────────────────────────────────────────
4545
4546    /// Return the register of the most recently played macro (`@@` source).
4547    pub fn last_macro(&self) -> Option<char> {
4548        self.vim.last_macro
4549    }
4550
4551    /// Overwrite the last-played-macro register.
4552    pub fn set_last_macro(&mut self, reg: Option<char>) {
4553        self.vim.last_macro = reg;
4554    }
4555
4556    // ── Last insert position ──────────────────────────────────────────────────
4557
4558    /// Return the cursor position when Insert mode was last exited (for `gi`).
4559    pub fn last_insert_pos(&self) -> Option<(usize, usize)> {
4560        self.vim.last_insert_pos
4561    }
4562
4563    /// Overwrite the stored last-insert position.
4564    pub fn set_last_insert_pos(&mut self, pos: Option<(usize, usize)>) {
4565        self.vim.last_insert_pos = pos;
4566    }
4567
4568    // ── Last visual selection ─────────────────────────────────────────────────
4569
4570    /// Return the saved visual selection snapshot for `gv`, or `None`.
4571    pub fn last_visual(&self) -> Option<vim::LastVisual> {
4572        self.vim.last_visual
4573    }
4574
4575    /// Overwrite the saved visual selection snapshot.
4576    pub fn set_last_visual(&mut self, snap: Option<vim::LastVisual>) {
4577        self.vim.last_visual = snap;
4578    }
4579
4580    // ── Viewport-pinned flag ──────────────────────────────────────────────────
4581
4582    /// `true` when `zz`/`zt`/`zb` pinned the viewport this step (suppresses
4583    /// the end-of-step scrolloff pass).
4584    pub fn viewport_pinned(&self) -> bool {
4585        self.vim.viewport_pinned
4586    }
4587
4588    /// Set or clear the viewport-pinned flag.
4589    pub fn set_viewport_pinned(&mut self, v: bool) {
4590        self.vim.viewport_pinned = v;
4591    }
4592
4593    // ── Insert pending register (Ctrl-R wait) ─────────────────────────────────
4594
4595    /// `true` while waiting for the register-name key after `Ctrl-R` in
4596    /// Insert mode.
4597    pub fn insert_pending_register(&self) -> bool {
4598        self.vim.insert_pending_register
4599    }
4600
4601    /// Set or clear the `Ctrl-R` register-wait flag.
4602    pub fn set_insert_pending_register(&mut self, v: bool) {
4603        self.vim.insert_pending_register = v;
4604    }
4605
4606    // ── Change-mark start ─────────────────────────────────────────────────────
4607
4608    /// Return the stashed `[` mark start for a Change operation, or `None`.
4609    pub fn change_mark_start(&self) -> Option<(usize, usize)> {
4610        self.vim.change_mark_start
4611    }
4612
4613    /// Atomically take the change-mark start, leaving `None`.
4614    pub fn take_change_mark_start(&mut self) -> Option<(usize, usize)> {
4615        self.vim.change_mark_start.take()
4616    }
4617
4618    /// Overwrite the change-mark start.
4619    pub fn set_change_mark_start(&mut self, pos: Option<(usize, usize)>) {
4620        self.vim.change_mark_start = pos;
4621    }
4622
4623    // ── Timeout tracking ──────────────────────────────────────────────────────
4624
4625    /// Return the wall-clock `Instant` of the last keystroke.
4626    pub fn last_input_at(&self) -> Option<std::time::Instant> {
4627        self.vim.last_input_at
4628    }
4629
4630    /// Overwrite the wall-clock last-input timestamp.
4631    pub fn set_last_input_at(&mut self, t: Option<std::time::Instant>) {
4632        self.vim.last_input_at = t;
4633    }
4634
4635    /// Return the `Host::now()` duration at the last keystroke.
4636    pub fn last_input_host_at(&self) -> Option<core::time::Duration> {
4637        self.vim.last_input_host_at
4638    }
4639
4640    /// Overwrite the host-clock last-input timestamp.
4641    pub fn set_last_input_host_at(&mut self, d: Option<core::time::Duration>) {
4642        self.vim.last_input_host_at = d;
4643    }
4644
4645    // ── Search prompt ──────────────────────────────────────────────────────────
4646
4647    /// Borrow the live search prompt, or `None` when not in search-prompt mode.
4648    pub fn search_prompt_state(&self) -> Option<&vim::SearchPrompt> {
4649        self.vim.search_prompt.as_ref()
4650    }
4651
4652    /// Borrow the live search prompt mutably.
4653    pub fn search_prompt_state_mut(&mut self) -> Option<&mut vim::SearchPrompt> {
4654        self.vim.search_prompt.as_mut()
4655    }
4656
4657    /// Atomically take the search prompt, leaving `None`.
4658    pub fn take_search_prompt_state(&mut self) -> Option<vim::SearchPrompt> {
4659        self.vim.search_prompt.take()
4660    }
4661
4662    /// Install a new search prompt (entering search-prompt mode).
4663    pub fn set_search_prompt_state(&mut self, prompt: Option<vim::SearchPrompt>) {
4664        self.vim.search_prompt = prompt;
4665    }
4666
4667    // ── Last search pattern / direction ───────────────────────────────────────
4668    // Note: `last_search_forward()` getter already exists at line ~1909.
4669    // `set_last_search()` combined mutator exists at line ~1918.
4670    // Only new / complementary accessors are added here.
4671
4672    /// Return the most recently committed search pattern, or `None`.
4673    pub fn last_search_pattern(&self) -> Option<&str> {
4674        self.vim.last_search.as_deref()
4675    }
4676
4677    /// Overwrite the stored last-search pattern without changing direction
4678    /// (use the existing `set_last_search` for the combined update).
4679    pub fn set_last_search_pattern_only(&mut self, pattern: Option<String>) {
4680        self.vim.last_search = pattern;
4681    }
4682
4683    /// Overwrite only the last-search direction flag.
4684    pub fn set_last_search_forward_only(&mut self, forward: bool) {
4685        self.vim.last_search_forward = forward;
4686    }
4687
4688    // ── Search history ────────────────────────────────────────────────────────
4689
4690    /// Borrow the committed search-pattern history (oldest first).
4691    pub fn search_history(&self) -> &[String] {
4692        &self.vim.search_history
4693    }
4694
4695    /// Borrow the search history mutably (e.g. to push a new entry).
4696    pub fn search_history_mut(&mut self) -> &mut Vec<String> {
4697        &mut self.vim.search_history
4698    }
4699
4700    /// Return the current search-history navigation cursor index.
4701    pub fn search_history_cursor(&self) -> Option<usize> {
4702        self.vim.search_history_cursor
4703    }
4704
4705    /// Overwrite the search-history navigation cursor.
4706    pub fn set_search_history_cursor(&mut self, idx: Option<usize>) {
4707        self.vim.search_history_cursor = idx;
4708    }
4709
4710    // ── Jump lists ────────────────────────────────────────────────────────────
4711
4712    /// Borrow the back half of the jump list (entries Ctrl-o pops from).
4713    pub fn jump_back_list(&self) -> &[(usize, usize)] {
4714        &self.vim.jump_back
4715    }
4716
4717    /// Borrow the back jump list mutably (push / pop).
4718    pub fn jump_back_list_mut(&mut self) -> &mut Vec<(usize, usize)> {
4719        &mut self.vim.jump_back
4720    }
4721
4722    /// Borrow the forward half of the jump list (entries Ctrl-i pops from).
4723    pub fn jump_fwd_list(&self) -> &[(usize, usize)] {
4724        &self.vim.jump_fwd
4725    }
4726
4727    /// Borrow the forward jump list mutably (push / pop / clear).
4728    pub fn jump_fwd_list_mut(&mut self) -> &mut Vec<(usize, usize)> {
4729        &mut self.vim.jump_fwd
4730    }
4731
4732    // ── Phase 6.6c: search + jump helpers (public Editor API) ───────────────
4733    //
4734    // `push_search_pattern`, `push_jump`, `record_search_history`, and
4735    // `walk_search_history` are public `Editor` methods so that `hjkl-vim`'s
4736    // search-prompt and normal-mode FSM can call them via the public API.
4737
4738    /// Compile `pattern` into a regex and install it as the active search
4739    /// pattern. Respects `:set ignorecase` / `:set smartcase`. An empty or
4740    /// invalid pattern clears the highlight without raising an error.
4741    pub fn push_search_pattern(&mut self, pattern: &str) {
4742        let compiled = if pattern.is_empty() {
4743            None
4744        } else {
4745            let case_insensitive = self.settings().ignore_case
4746                && !(self.settings().smartcase && pattern.chars().any(|c| c.is_uppercase()));
4747            let effective: std::borrow::Cow<'_, str> = if case_insensitive {
4748                std::borrow::Cow::Owned(format!("(?i){pattern}"))
4749            } else {
4750                std::borrow::Cow::Borrowed(pattern)
4751            };
4752            regex::Regex::new(&effective).ok()
4753        };
4754        let wrap = self.settings().wrapscan;
4755        self.set_search_pattern(compiled);
4756        self.search_state_mut().wrap_around = wrap;
4757    }
4758
4759    /// Record a pre-jump cursor position onto the back jumplist. Called
4760    /// before any "big jump" motion (`gg`/`G`, `%`, `*`/`#`, `n`/`N`,
4761    /// committed `/` or `?`, …). Branching off the history clears the
4762    /// forward half, matching vim's "redo-is-lost" semantics.
4763    pub fn push_jump(&mut self, from: (usize, usize)) {
4764        self.vim.jump_back.push(from);
4765        if self.vim.jump_back.len() > vim::JUMPLIST_MAX {
4766            self.vim.jump_back.remove(0);
4767        }
4768        self.vim.jump_fwd.clear();
4769    }
4770
4771    /// Push `pattern` onto the committed search history. Skips if the
4772    /// most recent entry already matches (consecutive dedupe) and trims
4773    /// the oldest entries beyond the history cap.
4774    pub fn record_search_history(&mut self, pattern: &str) {
4775        if pattern.is_empty() {
4776            return;
4777        }
4778        if self.vim.search_history.last().map(String::as_str) == Some(pattern) {
4779            return;
4780        }
4781        self.vim.search_history.push(pattern.to_string());
4782        let len = self.vim.search_history.len();
4783        if len > vim::SEARCH_HISTORY_MAX {
4784            self.vim
4785                .search_history
4786                .drain(0..len - vim::SEARCH_HISTORY_MAX);
4787        }
4788    }
4789
4790    /// Walk the search-prompt history by `dir` steps. `dir = -1` moves
4791    /// toward older entries (Ctrl-P / Up); `dir = 1` toward newer ones
4792    /// (Ctrl-N / Down). Stops at the ends; does nothing if there is no
4793    /// active search prompt.
4794    pub fn walk_search_history(&mut self, dir: isize) {
4795        if self.vim.search_history.is_empty() || self.vim.search_prompt.is_none() {
4796            return;
4797        }
4798        let len = self.vim.search_history.len();
4799        let next_idx = match (self.vim.search_history_cursor, dir) {
4800            (None, -1) => Some(len - 1),
4801            (None, 1) => return,
4802            (Some(i), -1) => i.checked_sub(1),
4803            (Some(i), 1) if i + 1 < len => Some(i + 1),
4804            _ => None,
4805        };
4806        let Some(idx) = next_idx else {
4807            return;
4808        };
4809        self.vim.search_history_cursor = Some(idx);
4810        let text = self.vim.search_history[idx].clone();
4811        if let Some(prompt) = self.vim.search_prompt.as_mut() {
4812            prompt.cursor = text.chars().count();
4813            prompt.text = text.clone();
4814        }
4815        self.push_search_pattern(&text);
4816    }
4817
4818    // ── Phase 6.6d: pre/post FSM bookkeeping ────────────────────────────────
4819    //
4820    // `begin_step` and `end_step` are the bookkeeping prelude/epilogue that
4821    // `hjkl_vim::dispatch_input` wraps around its per-mode FSM dispatch.
4822
4823    /// Pre-dispatch bookkeeping that must run before every per-mode FSM step.
4824    ///
4825    /// Call this at the start of every step; pass the returned
4826    /// [`StepBookkeeping`] to [`end_step`] after the FSM body finishes.
4827    ///
4828    /// Returns `Ok(bk)` when the caller should proceed with FSM dispatch.
4829    /// Returns `Err(consumed)` when the prelude itself handled the input
4830    /// (macro-stop chord); in that case skip the FSM body and do NOT call
4831    /// `end_step` — the macro-stop path is a true short-circuit with no
4832    /// epilogue needed.
4833    ///
4834    /// This method does NOT handle the search-prompt intercept — callers
4835    /// must check `search_prompt_state().is_some()` before calling `begin_step`
4836    /// and dispatch to the search-prompt FSM body directly.
4837    pub fn begin_step(&mut self, input: Input) -> Result<StepBookkeeping, bool> {
4838        use crate::input::Key;
4839        use vim::{Mode, Pending};
4840        // ── Timestamps ───────────────────────────────────────────────────────
4841        // Phase 7f: sync buffer before motion handlers see it.
4842        self.sync_buffer_content_from_textarea();
4843        // `:set timeoutlen` chord-timeout handling.
4844        let now = std::time::Instant::now();
4845        let host_now = self.host.now();
4846        let timed_out = match self.vim.last_input_host_at {
4847            Some(prev) => host_now.saturating_sub(prev) > self.settings.timeout_len,
4848            None => false,
4849        };
4850        if timed_out {
4851            let chord_in_flight = !matches!(self.vim.pending, Pending::None)
4852                || self.vim.count != 0
4853                || self.vim.pending_register.is_some()
4854                || self.vim.insert_pending_register;
4855            if chord_in_flight {
4856                self.vim.clear_pending_prefix();
4857            }
4858        }
4859        self.vim.last_input_at = Some(now);
4860        self.vim.last_input_host_at = Some(host_now);
4861        // ── Macro-stop: bare `q` outside Insert ends the recording ───────────
4862        if self.vim.recording_macro.is_some()
4863            && !self.vim.replaying_macro
4864            && matches!(self.vim.pending, Pending::None)
4865            && self.vim.mode != Mode::Insert
4866            && input.key == Key::Char('q')
4867            && !input.ctrl
4868            && !input.alt
4869        {
4870            let reg = self.vim.recording_macro.take().unwrap();
4871            let keys = std::mem::take(&mut self.vim.recording_keys);
4872            let text = crate::input::encode_macro(&keys);
4873            self.set_named_register_text(reg.to_ascii_lowercase(), text);
4874            return Err(true);
4875        }
4876        // ── Snapshots for epilogue ────────────────────────────────────────────
4877        let pending_was_macro_chord = matches!(
4878            self.vim.pending,
4879            Pending::RecordMacroTarget | Pending::PlayMacroTarget { .. }
4880        );
4881        let was_insert = self.vim.mode == Mode::Insert;
4882        let pre_visual_snapshot = match self.vim.mode {
4883            Mode::Visual => Some(vim::LastVisual {
4884                mode: Mode::Visual,
4885                anchor: self.vim.visual_anchor,
4886                cursor: self.cursor(),
4887                block_vcol: 0,
4888            }),
4889            Mode::VisualLine => Some(vim::LastVisual {
4890                mode: Mode::VisualLine,
4891                anchor: (self.vim.visual_line_anchor, 0),
4892                cursor: self.cursor(),
4893                block_vcol: 0,
4894            }),
4895            Mode::VisualBlock => Some(vim::LastVisual {
4896                mode: Mode::VisualBlock,
4897                anchor: self.vim.block_anchor,
4898                cursor: self.cursor(),
4899                block_vcol: self.vim.block_vcol,
4900            }),
4901            _ => None,
4902        };
4903        Ok(StepBookkeeping {
4904            pending_was_macro_chord,
4905            was_insert,
4906            pre_visual_snapshot,
4907        })
4908    }
4909
4910    /// Post-dispatch bookkeeping that must run after every per-mode FSM step.
4911    ///
4912    /// `input` is the same input that was passed to `begin_step`.
4913    /// `bk` is the [`StepBookkeeping`] returned by `begin_step`.
4914    /// `consumed` is the return value of the FSM body; this method returns
4915    /// it after running all epilogue invariants.
4916    ///
4917    /// Must NOT be called when `begin_step` returned `Err(...)`.
4918    pub fn end_step(&mut self, input: Input, bk: StepBookkeeping, consumed: bool) -> bool {
4919        use crate::input::Key;
4920        use vim::{Mode, Pending};
4921        let StepBookkeeping {
4922            pending_was_macro_chord,
4923            was_insert,
4924            pre_visual_snapshot,
4925        } = bk;
4926        // ── Visual-exit: set `<`/`>` marks and stash `last_visual` ───────────
4927        if let Some(snap) = pre_visual_snapshot
4928            && !matches!(
4929                self.vim.mode,
4930                Mode::Visual | Mode::VisualLine | Mode::VisualBlock
4931            )
4932        {
4933            let (lo, hi) = match snap.mode {
4934                Mode::Visual => {
4935                    if snap.anchor <= snap.cursor {
4936                        (snap.anchor, snap.cursor)
4937                    } else {
4938                        (snap.cursor, snap.anchor)
4939                    }
4940                }
4941                Mode::VisualLine => {
4942                    let r_lo = snap.anchor.0.min(snap.cursor.0);
4943                    let r_hi = snap.anchor.0.max(snap.cursor.0);
4944                    let last_col = self
4945                        .buffer()
4946                        .lines()
4947                        .get(r_hi)
4948                        .map(|l| l.chars().count().saturating_sub(1))
4949                        .unwrap_or(0);
4950                    ((r_lo, 0), (r_hi, last_col))
4951                }
4952                Mode::VisualBlock => {
4953                    let (r1, c1) = snap.anchor;
4954                    let (r2, c2) = snap.cursor;
4955                    ((r1.min(r2), c1.min(c2)), (r1.max(r2), c1.max(c2)))
4956                }
4957                _ => {
4958                    if snap.anchor <= snap.cursor {
4959                        (snap.anchor, snap.cursor)
4960                    } else {
4961                        (snap.cursor, snap.anchor)
4962                    }
4963                }
4964            };
4965            self.set_mark('<', lo);
4966            self.set_mark('>', hi);
4967            self.vim.last_visual = Some(snap);
4968        }
4969        // ── Ctrl-o one-shot-normal return to Insert ───────────────────────────
4970        if !was_insert
4971            && self.vim.one_shot_normal
4972            && self.vim.mode == Mode::Normal
4973            && matches!(self.vim.pending, Pending::None)
4974        {
4975            self.vim.one_shot_normal = false;
4976            self.vim.mode = Mode::Insert;
4977        }
4978        // ── Content + viewport sync ───────────────────────────────────────────
4979        self.sync_buffer_content_from_textarea();
4980        if !self.vim.viewport_pinned {
4981            self.ensure_cursor_in_scrolloff();
4982        }
4983        self.vim.viewport_pinned = false;
4984        // ── Recorder hook ─────────────────────────────────────────────────────
4985        if self.vim.recording_macro.is_some()
4986            && !self.vim.replaying_macro
4987            && input.key != Key::Char('q')
4988            && !pending_was_macro_chord
4989        {
4990            self.vim.recording_keys.push(input);
4991        }
4992        // ── Phase 6.3: current_mode sync ─────────────────────────────────────
4993        self.vim.current_mode = self.vim.public_mode();
4994        consumed
4995    }
4996
4997    // ── Phase 6.6e: additional public primitives for hjkl-vim::normal ─────────
4998
4999    /// `true` when the editor is in any visual mode (Visual / VisualLine /
5000    /// VisualBlock). Convenience wrapper around `vim_mode()` for hjkl-vim.
5001    pub fn is_visual(&self) -> bool {
5002        matches!(
5003            self.vim.mode,
5004            vim::Mode::Visual | vim::Mode::VisualLine | vim::Mode::VisualBlock
5005        )
5006    }
5007
5008    /// Compute the VisualBlock rectangle corners: `(top_row, bot_row,
5009    /// left_col, right_col)`. Uses `block_anchor` and `block_vcol` (the
5010    /// virtual column, which survives j/k clamping to shorter rows).
5011    ///
5012    /// Promoted in Phase 6.6e so `hjkl-vim::normal` can compute the block
5013    /// extents needed for VisualBlock `I` / `A` / `r` without accessing
5014    /// engine-private helpers.
5015    pub fn visual_block_bounds(&self) -> (usize, usize, usize, usize) {
5016        let (ar, ac) = self.vim.block_anchor;
5017        let (cr, _) = self.cursor();
5018        let cc = self.vim.block_vcol;
5019        let top = ar.min(cr);
5020        let bot = ar.max(cr);
5021        let left = ac.min(cc);
5022        let right = ac.max(cc);
5023        (top, bot, left, right)
5024    }
5025
5026    /// Return the character count (code-point count) of line `row`, or `0`
5027    /// when `row` is out of range. Used by hjkl-vim::normal for VisualBlock
5028    /// I / A column computations.
5029    pub fn line_char_count(&self, row: usize) -> usize {
5030        buf_line_chars(&self.buffer, row)
5031    }
5032
5033    /// Apply operator over `motion` with `count` repetitions. The full
5034    /// vim-quirks path (operator context for `l`, clamping, etc.) is applied.
5035    ///
5036    /// Promoted to the public surface in Phase 6.6e so `hjkl-vim::normal`'s
5037    /// relocated `handle_after_op` can call it directly with a parsed `Motion`
5038    /// without re-entering the engine FSM.
5039    pub fn apply_op_with_motion_direct(
5040        &mut self,
5041        op: crate::vim::Operator,
5042        motion: &crate::vim::Motion,
5043        count: usize,
5044    ) {
5045        vim::apply_op_with_motion(self, op, motion, count);
5046    }
5047
5048    /// `Ctrl-a` / `Ctrl-x` — adjust the number under or after the cursor.
5049    /// `delta = 1` increments; `delta = -1` decrements; larger deltas
5050    /// multiply as in vim's `5<C-a>`. Promoted in Phase 6.6e so
5051    /// `hjkl-vim::normal` can dispatch `Ctrl-a` / `Ctrl-x`.
5052    pub fn adjust_number(&mut self, delta: i64) {
5053        vim::adjust_number(self, delta);
5054    }
5055
5056    /// Open the `/` or `?` search prompt. `forward = true` for `/`,
5057    /// `false` for `?`. Promoted in Phase 6.6e so `hjkl-vim::normal` can
5058    /// dispatch `/` and `?` without re-entering the engine FSM.
5059    pub fn enter_search(&mut self, forward: bool) {
5060        vim::enter_search(self, forward);
5061    }
5062
5063    /// Enter Insert mode at the left edge of a VisualBlock selection for
5064    /// `I`. Moves the cursor to `(top, col)`, resets to Normal internally,
5065    /// then begins an insert session with `InsertReason::BlockEdge`.
5066    ///
5067    /// Promoted in Phase 6.6e so `hjkl-vim::normal` can dispatch the
5068    /// VisualBlock `I` command without accessing engine-private helpers.
5069    pub fn visual_block_insert_at_left(&mut self, top: usize, bot: usize, col: usize) {
5070        self.jump_cursor(top, col);
5071        self.vim.mode = vim::Mode::Normal;
5072        vim::begin_insert(self, 1, vim::InsertReason::BlockEdge { top, bot, col });
5073    }
5074
5075    /// Enter Insert mode at the right edge of a VisualBlock selection for
5076    /// `A`. Moves the cursor to `(top, col)`, resets to Normal internally,
5077    /// then begins an insert session with `InsertReason::BlockEdge`.
5078    ///
5079    /// Promoted in Phase 6.6e so `hjkl-vim::normal` can dispatch the
5080    /// VisualBlock `A` command without accessing engine-private helpers.
5081    pub fn visual_block_append_at_right(&mut self, top: usize, bot: usize, col: usize) {
5082        self.jump_cursor(top, col);
5083        self.vim.mode = vim::Mode::Normal;
5084        vim::begin_insert(self, 1, vim::InsertReason::BlockEdge { top, bot, col });
5085    }
5086
5087    /// Execute a motion (cursor movement), push to the jumplist for big jumps,
5088    /// and update the sticky column. Mirrors the engine FSM's `execute_motion`
5089    /// free function. Promoted in Phase 6.6e for `hjkl-vim::normal`.
5090    pub fn execute_motion(&mut self, motion: crate::vim::Motion, count: usize) {
5091        vim::execute_motion(self, motion, count);
5092    }
5093
5094    /// Update the VisualBlock virtual column after a motion in VisualBlock mode.
5095    /// Horizontal motions sync `block_vcol` to the cursor column; vertical /
5096    /// non-h/l motions leave it alone so the intended column survives clamping
5097    /// to shorter rows. Promoted in Phase 6.6e for `hjkl-vim::normal`.
5098    pub fn update_block_vcol(&mut self, motion: &crate::vim::Motion) {
5099        vim::update_block_vcol(self, motion);
5100    }
5101
5102    /// Apply `op` over the current visual selection (char-wise, linewise, or
5103    /// block). Mirrors the engine's internal `apply_visual_operator` free fn.
5104    /// Promoted in Phase 6.6e for `hjkl-vim::normal`.
5105    pub fn apply_visual_operator(&mut self, op: crate::vim::Operator) {
5106        vim::apply_visual_operator(self, op);
5107    }
5108
5109    /// Replace each character cell in the current VisualBlock selection with
5110    /// `ch`. Mirrors the engine's `block_replace` free fn. Promoted in Phase
5111    /// 6.6e for the VisualBlock `r<ch>` command in `hjkl-vim::normal`.
5112    pub fn replace_block_char(&mut self, ch: char) {
5113        vim::block_replace(self, ch);
5114    }
5115
5116    /// Extend the current visual selection to cover the text object identified
5117    /// by `ch` and `inner`. Maps `ch` to a `TextObject`, resolves its range
5118    /// via `text_object_range`, then updates the visual anchor and cursor.
5119    ///
5120    /// Promoted in Phase 6.6e for the visual-mode `i<ch>` / `a<ch>` commands
5121    /// in `hjkl-vim::normal::handle_visual_text_obj`.
5122    pub fn visual_text_obj_extend(&mut self, ch: char, inner: bool) {
5123        use crate::vim::{Mode, TextObject};
5124        let obj = match ch {
5125            'w' => TextObject::Word { big: false },
5126            'W' => TextObject::Word { big: true },
5127            '"' | '\'' | '`' => TextObject::Quote(ch),
5128            '(' | ')' | 'b' => TextObject::Bracket('('),
5129            '[' | ']' => TextObject::Bracket('['),
5130            '{' | '}' | 'B' => TextObject::Bracket('{'),
5131            '<' | '>' => TextObject::Bracket('<'),
5132            'p' => TextObject::Paragraph,
5133            't' => TextObject::XmlTag,
5134            's' => TextObject::Sentence,
5135            _ => return,
5136        };
5137        let Some((start, end, kind)) = vim::text_object_range(self, obj, inner) else {
5138            return;
5139        };
5140        match kind {
5141            crate::vim::RangeKind::Linewise => {
5142                self.vim.visual_line_anchor = start.0;
5143                self.vim.mode = Mode::VisualLine;
5144                self.vim.current_mode = VimMode::VisualLine;
5145                self.jump_cursor(end.0, 0);
5146            }
5147            _ => {
5148                self.vim.mode = Mode::Visual;
5149                self.vim.current_mode = VimMode::Visual;
5150                self.vim.visual_anchor = (start.0, start.1);
5151                let (er, ec) = vim::retreat_one(self, end);
5152                self.jump_cursor(er, ec);
5153            }
5154        }
5155    }
5156}
5157
5158/// Visual column of the character at `char_col` in `line`, treating `\t`
5159/// as expansion to the next `tab_width` stop and every other char as
5160/// 1 cell wide. Wide-char support (CJK, emoji) is a separate concern —
5161/// the cursor math elsewhere also assumes single-cell chars.
5162fn visual_col_for_char(line: &str, char_col: usize, tab_width: usize) -> usize {
5163    let mut visual = 0usize;
5164    for (i, ch) in line.chars().enumerate() {
5165        if i >= char_col {
5166            break;
5167        }
5168        if ch == '\t' {
5169            visual += tab_width - (visual % tab_width);
5170        } else {
5171            visual += 1;
5172        }
5173    }
5174    visual
5175}
5176
5177#[cfg(feature = "crossterm")]
5178impl From<KeyEvent> for Input {
5179    fn from(key: KeyEvent) -> Self {
5180        let k = match key.code {
5181            KeyCode::Char(c) => Key::Char(c),
5182            KeyCode::Backspace => Key::Backspace,
5183            KeyCode::Delete => Key::Delete,
5184            KeyCode::Enter => Key::Enter,
5185            KeyCode::Left => Key::Left,
5186            KeyCode::Right => Key::Right,
5187            KeyCode::Up => Key::Up,
5188            KeyCode::Down => Key::Down,
5189            KeyCode::Home => Key::Home,
5190            KeyCode::End => Key::End,
5191            KeyCode::Tab => Key::Tab,
5192            KeyCode::Esc => Key::Esc,
5193            _ => Key::Null,
5194        };
5195        Input {
5196            key: k,
5197            ctrl: key.modifiers.contains(KeyModifiers::CONTROL),
5198            alt: key.modifiers.contains(KeyModifiers::ALT),
5199            shift: key.modifiers.contains(KeyModifiers::SHIFT),
5200        }
5201    }
5202}
5203
5204/// Crossterm `KeyEvent` → engine `Input`. Thin wrapper that delegates
5205/// to the [`From`] impl above; kept as a free fn for the in-tree
5206/// callers in the legacy ratatui-coupled paths.
5207#[cfg(feature = "crossterm")]
5208pub fn crossterm_to_input(key: KeyEvent) -> Input {
5209    Input::from(key)
5210}
5211
5212#[cfg(all(test, feature = "crossterm", feature = "ratatui"))]
5213mod tests {
5214    use super::*;
5215    use crate::types::Host;
5216    use crossterm::event::KeyEvent;
5217
5218    #[allow(dead_code)]
5219    fn key(code: KeyCode) -> KeyEvent {
5220        KeyEvent::new(code, KeyModifiers::NONE)
5221    }
5222    #[allow(dead_code)]
5223    fn shift_key(code: KeyCode) -> KeyEvent {
5224        KeyEvent::new(code, KeyModifiers::SHIFT)
5225    }
5226    #[allow(dead_code)]
5227    fn ctrl_key(code: KeyCode) -> KeyEvent {
5228        KeyEvent::new(code, KeyModifiers::CONTROL)
5229    }
5230
5231    #[test]
5232    fn intern_style_dedups_engine_native_styles() {
5233        use crate::types::{Attrs, Color, Style};
5234        let mut e = Editor::new(
5235            hjkl_buffer::Buffer::new(),
5236            crate::types::DefaultHost::new(),
5237            crate::types::Options::default(),
5238        );
5239        let s = Style {
5240            fg: Some(Color(255, 0, 0)),
5241            bg: None,
5242            attrs: Attrs::BOLD,
5243        };
5244        let id_a = e.intern_style(s);
5245        // Re-interning the same engine style returns the same id.
5246        let id_b = e.intern_style(s);
5247        assert_eq!(id_a, id_b);
5248        // Engine accessor returns the same style back.
5249        let back = e.engine_style_at(id_a).expect("interned");
5250        assert_eq!(back, s);
5251    }
5252
5253    #[test]
5254    fn engine_style_at_out_of_range_returns_none() {
5255        let e = Editor::new(
5256            hjkl_buffer::Buffer::new(),
5257            crate::types::DefaultHost::new(),
5258            crate::types::Options::default(),
5259        );
5260        assert!(e.engine_style_at(99).is_none());
5261    }
5262
5263    #[test]
5264    fn options_bridge_roundtrip() {
5265        let mut e = Editor::new(
5266            hjkl_buffer::Buffer::new(),
5267            crate::types::DefaultHost::new(),
5268            crate::types::Options::default(),
5269        );
5270        let opts = e.current_options();
5271        // 0.2.0: defaults flipped to modern editor norms — 4-space soft tabs.
5272        assert_eq!(opts.shiftwidth, 4);
5273        assert_eq!(opts.tabstop, 4);
5274
5275        let new_opts = crate::types::Options {
5276            shiftwidth: 4,
5277            tabstop: 2,
5278            ignorecase: true,
5279            ..crate::types::Options::default()
5280        };
5281        e.apply_options(&new_opts);
5282
5283        let after = e.current_options();
5284        assert_eq!(after.shiftwidth, 4);
5285        assert_eq!(after.tabstop, 2);
5286        assert!(after.ignorecase);
5287    }
5288
5289    #[test]
5290    fn selection_highlight_none_in_normal() {
5291        let mut e = Editor::new(
5292            hjkl_buffer::Buffer::new(),
5293            crate::types::DefaultHost::new(),
5294            crate::types::Options::default(),
5295        );
5296        e.set_content("hello");
5297        assert!(e.selection_highlight().is_none());
5298    }
5299
5300    #[test]
5301    fn highlights_emit_search_matches() {
5302        use crate::types::HighlightKind;
5303        let mut e = Editor::new(
5304            hjkl_buffer::Buffer::new(),
5305            crate::types::DefaultHost::new(),
5306            crate::types::Options::default(),
5307        );
5308        e.set_content("foo bar foo\nbaz qux\n");
5309        // 0.0.35: arm via the engine search state. The buffer
5310        // accessor still works (deprecated) but new code goes
5311        // through Editor.
5312        e.set_search_pattern(Some(regex::Regex::new("foo").unwrap()));
5313        let hs = e.highlights_for_line(0);
5314        assert_eq!(hs.len(), 2);
5315        for h in &hs {
5316            assert_eq!(h.kind, HighlightKind::SearchMatch);
5317            assert_eq!(h.range.start.line, 0);
5318            assert_eq!(h.range.end.line, 0);
5319        }
5320    }
5321
5322    #[test]
5323    fn highlights_empty_without_pattern() {
5324        let mut e = Editor::new(
5325            hjkl_buffer::Buffer::new(),
5326            crate::types::DefaultHost::new(),
5327            crate::types::Options::default(),
5328        );
5329        e.set_content("foo bar");
5330        assert!(e.highlights_for_line(0).is_empty());
5331    }
5332
5333    #[test]
5334    fn highlights_empty_for_out_of_range_line() {
5335        let mut e = Editor::new(
5336            hjkl_buffer::Buffer::new(),
5337            crate::types::DefaultHost::new(),
5338            crate::types::Options::default(),
5339        );
5340        e.set_content("foo");
5341        e.set_search_pattern(Some(regex::Regex::new("foo").unwrap()));
5342        assert!(e.highlights_for_line(99).is_empty());
5343    }
5344
5345    #[test]
5346    fn snapshot_roundtrips_through_restore() {
5347        use crate::types::SnapshotMode;
5348        let mut e = Editor::new(
5349            hjkl_buffer::Buffer::new(),
5350            crate::types::DefaultHost::new(),
5351            crate::types::Options::default(),
5352        );
5353        e.set_content("alpha\nbeta\ngamma");
5354        e.jump_cursor(2, 3);
5355        let snap = e.take_snapshot();
5356        assert_eq!(snap.mode, SnapshotMode::Normal);
5357        assert_eq!(snap.cursor, (2, 3));
5358        assert_eq!(snap.lines.len(), 3);
5359
5360        let mut other = Editor::new(
5361            hjkl_buffer::Buffer::new(),
5362            crate::types::DefaultHost::new(),
5363            crate::types::Options::default(),
5364        );
5365        other.restore_snapshot(snap).expect("restore");
5366        assert_eq!(other.cursor(), (2, 3));
5367        assert_eq!(other.buffer().lines().len(), 3);
5368    }
5369
5370    #[test]
5371    fn restore_snapshot_rejects_version_mismatch() {
5372        let mut e = Editor::new(
5373            hjkl_buffer::Buffer::new(),
5374            crate::types::DefaultHost::new(),
5375            crate::types::Options::default(),
5376        );
5377        let mut snap = e.take_snapshot();
5378        snap.version = 9999;
5379        match e.restore_snapshot(snap) {
5380            Err(crate::EngineError::SnapshotVersion(got, want)) => {
5381                assert_eq!(got, 9999);
5382                assert_eq!(want, crate::types::EditorSnapshot::VERSION);
5383            }
5384            other => panic!("expected SnapshotVersion err, got {other:?}"),
5385        }
5386    }
5387
5388    #[test]
5389    fn take_content_change_returns_some_on_first_dirty() {
5390        let mut e = Editor::new(
5391            hjkl_buffer::Buffer::new(),
5392            crate::types::DefaultHost::new(),
5393            crate::types::Options::default(),
5394        );
5395        e.set_content("hello");
5396        let first = e.take_content_change();
5397        assert!(first.is_some());
5398        let second = e.take_content_change();
5399        assert!(second.is_none());
5400    }
5401
5402    fn many_lines(n: usize) -> String {
5403        (0..n)
5404            .map(|i| format!("line{i}"))
5405            .collect::<Vec<_>>()
5406            .join("\n")
5407    }
5408
5409    #[allow(dead_code)]
5410    fn prime_viewport<H: Host>(e: &mut Editor<hjkl_buffer::Buffer, H>, height: u16) {
5411        e.set_viewport_height(height);
5412    }
5413
5414    /// Contract that the TUI drain relies on: `set_content` flags the
5415    /// editor dirty (so the next `take_dirty` call reports the change),
5416    /// and a second `take_dirty` returns `false` after consumption. The
5417    /// TUI drains this flag after every programmatic content load so
5418    /// opening a tab doesn't get mistaken for a user edit and mark the
5419    /// tab dirty (which would then trigger the quit-prompt on `:q`).
5420    #[test]
5421    fn set_content_dirties_then_take_dirty_clears() {
5422        let mut e = Editor::new(
5423            hjkl_buffer::Buffer::new(),
5424            crate::types::DefaultHost::new(),
5425            crate::types::Options::default(),
5426        );
5427        e.set_content("hello");
5428        assert!(
5429            e.take_dirty(),
5430            "set_content should leave content_dirty=true"
5431        );
5432        assert!(!e.take_dirty(), "take_dirty should clear the flag");
5433    }
5434
5435    #[test]
5436    fn content_arc_cache_invalidated_by_set_content() {
5437        let mut e = Editor::new(
5438            hjkl_buffer::Buffer::new(),
5439            crate::types::DefaultHost::new(),
5440            crate::types::Options::default(),
5441        );
5442        e.set_content("one");
5443        let a = e.content_arc();
5444        e.set_content("two");
5445        let b = e.content_arc();
5446        assert!(!std::sync::Arc::ptr_eq(&a, &b));
5447        assert!(b.starts_with("two"));
5448    }
5449
5450    // ── doc-coord mouse primitives (Phase 1 — issue #114) ──────────────────
5451
5452    #[test]
5453    fn mouse_click_doc_moves_cursor_to_doc_coords() {
5454        let mut e = Editor::new(
5455            hjkl_buffer::Buffer::new(),
5456            crate::types::DefaultHost::new(),
5457            crate::types::Options::default(),
5458        );
5459        e.set_content("hello\nworld");
5460        e.mouse_click_doc(1, 2);
5461        assert_eq!(e.cursor(), (1, 2));
5462    }
5463
5464    #[test]
5465    fn mouse_click_doc_normal_mode_clamps_past_eol_to_last_char() {
5466        let mut e = Editor::new(
5467            hjkl_buffer::Buffer::new(),
5468            crate::types::DefaultHost::new(),
5469            crate::types::Options::default(),
5470        );
5471        e.set_content("hello");
5472        // Normal mode (default after construction): "hello" has 5 chars,
5473        // past-EOL click clamps to col=4 (last char 'o' — never on the
5474        // implicit \n, vim/neovim convention).
5475        e.mouse_click_doc(0, 99);
5476        assert_eq!(e.cursor(), (0, 4));
5477    }
5478
5479    #[test]
5480    fn mouse_click_doc_normal_mode_clamps_past_eol_multibyte() {
5481        let mut e = Editor::new(
5482            hjkl_buffer::Buffer::new(),
5483            crate::types::DefaultHost::new(),
5484            crate::types::Options::default(),
5485        );
5486        // 5 chars, 6 bytes — clamping must be char-counted, not byte-counted.
5487        e.set_content("héllo");
5488        e.mouse_click_doc(0, 99);
5489        assert_eq!(e.cursor(), (0, 4));
5490    }
5491
5492    #[test]
5493    fn mouse_click_doc_insert_mode_allows_one_past_eol() {
5494        let mut e = Editor::new(
5495            hjkl_buffer::Buffer::new(),
5496            crate::types::DefaultHost::new(),
5497            crate::types::Options::default(),
5498        );
5499        e.set_content("hello");
5500        e.enter_insert_i(1);
5501        // Insert mode allows the one-past-EOL position (col=5 for 5-char
5502        // line) — that's the canonical insert-here sentinel.
5503        e.mouse_click_doc(0, 99);
5504        assert_eq!(e.cursor(), (0, 5));
5505    }
5506
5507    #[test]
5508    fn mouse_click_doc_resets_sticky_col() {
5509        let mut e = Editor::new(
5510            hjkl_buffer::Buffer::new(),
5511            crate::types::DefaultHost::new(),
5512            crate::types::Options::default(),
5513        );
5514        e.set_content("aaaaa\nbb\naaaaa");
5515        // Pretend a previous keyboard motion put intended col at 4 (e.g.
5516        // user navigated $ on row 0).
5517        e.sticky_col = Some(4);
5518        // Click on row 1, col 1 (the second 'b' on a short line).
5519        e.mouse_click_doc(1, 1);
5520        assert_eq!(e.cursor(), (1, 1));
5521        assert_eq!(
5522            e.sticky_col,
5523            Some(1),
5524            "click must reset sticky_col so a subsequent j/k uses the clicked column \
5525             as the intended visual column (not the previous keyboard-tracked col)"
5526        );
5527    }
5528
5529    #[test]
5530    fn mouse_click_doc_exits_visual_mode() {
5531        use crate::VimMode;
5532        let mut e = Editor::new(
5533            hjkl_buffer::Buffer::new(),
5534            crate::types::DefaultHost::new(),
5535            crate::types::Options::default(),
5536        );
5537        e.set_content("hello");
5538        e.enter_visual_char();
5539        assert_eq!(e.vim_mode(), VimMode::Visual);
5540        e.mouse_click_doc(0, 2);
5541        assert_eq!(e.vim_mode(), VimMode::Normal);
5542        assert_eq!(e.cursor(), (0, 2));
5543    }
5544
5545    #[test]
5546    fn set_cursor_doc_clamps_past_last_row() {
5547        let mut e = Editor::new(
5548            hjkl_buffer::Buffer::new(),
5549            crate::types::DefaultHost::new(),
5550            crate::types::Options::default(),
5551        );
5552        e.set_content("one\ntwo");
5553        // doc has 2 rows (0 and 1); row 99 clamps to 1.
5554        e.set_cursor_doc(99, 0);
5555        assert_eq!(e.cursor(), (1, 0));
5556    }
5557
5558    #[test]
5559    fn mouse_begin_drag_enters_visual_char() {
5560        use crate::VimMode;
5561        let mut e = Editor::new(
5562            hjkl_buffer::Buffer::new(),
5563            crate::types::DefaultHost::new(),
5564            crate::types::Options::default(),
5565        );
5566        e.set_content("hello");
5567        e.mouse_begin_drag();
5568        assert_eq!(e.vim_mode(), VimMode::Visual);
5569    }
5570
5571    #[test]
5572    fn mouse_extend_drag_doc_moves_cursor_leaving_visual_anchor() {
5573        use crate::VimMode;
5574        let mut e = Editor::new(
5575            hjkl_buffer::Buffer::new(),
5576            crate::types::DefaultHost::new(),
5577            crate::types::Options::default(),
5578        );
5579        e.set_content("hello world");
5580        e.mouse_begin_drag(); // anchor at (0,0)
5581        e.mouse_extend_drag_doc(0, 5);
5582        assert_eq!(e.vim_mode(), VimMode::Visual);
5583        assert_eq!(e.cursor(), (0, 5));
5584    }
5585
5586    // ── Patch B (0.0.29): Host trait wired into Editor ──
5587
5588    #[test]
5589    fn host_clipboard_round_trip_via_default_host() {
5590        // DefaultHost stores write_clipboard in-memory; read_clipboard
5591        // returns the most recent payload.
5592        let mut e = Editor::new(
5593            hjkl_buffer::Buffer::new(),
5594            crate::types::DefaultHost::new(),
5595            crate::types::Options::default(),
5596        );
5597        e.host_mut().write_clipboard("payload".to_string());
5598        assert_eq!(e.host_mut().read_clipboard().as_deref(), Some("payload"));
5599    }
5600
5601    // ── ContentEdit emission ─────────────────────────────────────────
5602
5603    fn fresh_editor(initial: &str) -> Editor {
5604        let buffer = hjkl_buffer::Buffer::from_str(initial);
5605        Editor::new(
5606            buffer,
5607            crate::types::DefaultHost::new(),
5608            crate::types::Options::default(),
5609        )
5610    }
5611
5612    #[test]
5613    fn content_edit_insert_char_at_origin() {
5614        let mut e = fresh_editor("");
5615        let _ = e.mutate_edit(hjkl_buffer::Edit::InsertChar {
5616            at: hjkl_buffer::Position::new(0, 0),
5617            ch: 'a',
5618        });
5619        let edits = e.take_content_edits();
5620        assert_eq!(edits.len(), 1);
5621        let ce = &edits[0];
5622        assert_eq!(ce.start_byte, 0);
5623        assert_eq!(ce.old_end_byte, 0);
5624        assert_eq!(ce.new_end_byte, 1);
5625        assert_eq!(ce.start_position, (0, 0));
5626        assert_eq!(ce.old_end_position, (0, 0));
5627        assert_eq!(ce.new_end_position, (0, 1));
5628    }
5629
5630    #[test]
5631    fn content_edit_insert_str_multiline() {
5632        // Buffer "x\ny" — insert "ab\ncd" at end of row 0.
5633        let mut e = fresh_editor("x\ny");
5634        let _ = e.mutate_edit(hjkl_buffer::Edit::InsertStr {
5635            at: hjkl_buffer::Position::new(0, 1),
5636            text: "ab\ncd".into(),
5637        });
5638        let edits = e.take_content_edits();
5639        assert_eq!(edits.len(), 1);
5640        let ce = &edits[0];
5641        assert_eq!(ce.start_byte, 1);
5642        assert_eq!(ce.old_end_byte, 1);
5643        assert_eq!(ce.new_end_byte, 1 + 5);
5644        assert_eq!(ce.start_position, (0, 1));
5645        // Insertion contains one '\n', so row+1, col = bytes after last '\n' = 2.
5646        assert_eq!(ce.new_end_position, (1, 2));
5647    }
5648
5649    #[test]
5650    fn content_edit_delete_range_charwise() {
5651        // "abcdef" — delete chars 1..4 ("bcd").
5652        let mut e = fresh_editor("abcdef");
5653        let _ = e.mutate_edit(hjkl_buffer::Edit::DeleteRange {
5654            start: hjkl_buffer::Position::new(0, 1),
5655            end: hjkl_buffer::Position::new(0, 4),
5656            kind: hjkl_buffer::MotionKind::Char,
5657        });
5658        let edits = e.take_content_edits();
5659        assert_eq!(edits.len(), 1);
5660        let ce = &edits[0];
5661        assert_eq!(ce.start_byte, 1);
5662        assert_eq!(ce.old_end_byte, 4);
5663        assert_eq!(ce.new_end_byte, 1);
5664        assert!(ce.old_end_byte > ce.new_end_byte);
5665    }
5666
5667    #[test]
5668    fn content_edit_set_content_resets() {
5669        let mut e = fresh_editor("foo");
5670        let _ = e.mutate_edit(hjkl_buffer::Edit::InsertChar {
5671            at: hjkl_buffer::Position::new(0, 0),
5672            ch: 'X',
5673        });
5674        // set_content should clear queued edits and raise the reset
5675        // flag on the next take_content_reset.
5676        e.set_content("brand new");
5677        assert!(e.take_content_reset());
5678        // Subsequent call clears the flag.
5679        assert!(!e.take_content_reset());
5680        // Edits cleared on reset.
5681        assert!(e.take_content_edits().is_empty());
5682    }
5683
5684    #[test]
5685    fn content_edit_multiple_replaces_in_order() {
5686        // Three Replace edits applied left-to-right (mimics the
5687        // substitute path's per-match Replace fan-out). Verify each
5688        // mutation queues exactly one ContentEdit and they're drained
5689        // in source-order with structurally valid byte spans.
5690        let mut e = fresh_editor("xax xbx xcx");
5691        let _ = e.take_content_edits();
5692        let _ = e.take_content_reset();
5693        // Replace each "x" with "yy", left to right. After each replace,
5694        // the next match's char-col shifts by +1 (since "yy" is 1 char
5695        // longer than "x" but they're both ASCII so byte = char here).
5696        let positions = [(0usize, 0usize), (0, 4), (0, 8)];
5697        for (row, col) in positions {
5698            let _ = e.mutate_edit(hjkl_buffer::Edit::Replace {
5699                start: hjkl_buffer::Position::new(row, col),
5700                end: hjkl_buffer::Position::new(row, col + 1),
5701                with: "yy".into(),
5702            });
5703        }
5704        let edits = e.take_content_edits();
5705        assert_eq!(edits.len(), 3);
5706        for ce in &edits {
5707            assert!(ce.start_byte <= ce.old_end_byte);
5708            assert!(ce.start_byte <= ce.new_end_byte);
5709        }
5710        // Document order.
5711        for w in edits.windows(2) {
5712            assert!(w[0].start_byte <= w[1].start_byte);
5713        }
5714    }
5715
5716    #[test]
5717    fn replace_char_at_replaces_single_char_under_cursor() {
5718        // Matches vim's `rx` semantics: replace char under cursor.
5719        let mut e = fresh_editor("abc");
5720        e.jump_cursor(0, 1); // cursor on 'b'
5721        e.replace_char_at('X', 1);
5722        let got = e.content();
5723        let got = got.trim_end_matches('\n');
5724        assert_eq!(
5725            got, "aXc",
5726            "replace_char_at(X, 1) must replace 'b' with 'X'"
5727        );
5728        // Cursor stays on the replaced char.
5729        assert_eq!(e.cursor(), (0, 1));
5730    }
5731
5732    #[test]
5733    fn replace_char_at_count_replaces_multiple_chars() {
5734        // `3rx` in vim replaces 3 chars starting at cursor.
5735        let mut e = fresh_editor("abcde");
5736        e.jump_cursor(0, 0);
5737        e.replace_char_at('Z', 3);
5738        let got = e.content();
5739        let got = got.trim_end_matches('\n');
5740        assert_eq!(
5741            got, "ZZZde",
5742            "replace_char_at(Z, 3) must replace first 3 chars"
5743        );
5744    }
5745
5746    #[test]
5747    fn find_char_method_moves_to_target() {
5748        // buffer "abcabc", cursor (0,0), f<c> → cursor (0,2).
5749        let mut e = fresh_editor("abcabc");
5750        e.jump_cursor(0, 0);
5751        e.find_char('c', true, false, 1);
5752        assert_eq!(
5753            e.cursor(),
5754            (0, 2),
5755            "find_char('c', forward=true, till=false, count=1) must land on 'c' at col 2"
5756        );
5757    }
5758
5759    // ── after_g unit tests (Phase 2b-ii) ────────────────────────────────────
5760
5761    #[test]
5762    fn after_g_gg_jumps_to_top() {
5763        let content: String = (0..20).map(|i| format!("line {i}\n")).collect();
5764        let mut e = fresh_editor(&content);
5765        e.jump_cursor(15, 0);
5766        e.after_g('g', 1);
5767        assert_eq!(e.cursor().0, 0, "gg must move cursor to row 0");
5768    }
5769
5770    #[test]
5771    fn after_g_gg_with_count_jumps_line() {
5772        // 5gg → row 4 (0-indexed).
5773        let content: String = (0..20).map(|i| format!("line {i}\n")).collect();
5774        let mut e = fresh_editor(&content);
5775        e.jump_cursor(0, 0);
5776        e.after_g('g', 5);
5777        assert_eq!(e.cursor().0, 4, "5gg must land on row 4");
5778    }
5779
5780    #[test]
5781    fn after_g_gj_moves_down() {
5782        let mut e = fresh_editor("line0\nline1\nline2\n");
5783        e.jump_cursor(0, 0);
5784        e.after_g('j', 1);
5785        assert_eq!(e.cursor().0, 1, "gj must move down one display row");
5786    }
5787
5788    #[test]
5789    fn after_g_gu_sets_operator_pending() {
5790        // gU enters operator-pending with Uppercase op; next key applies it.
5791        let mut e = fresh_editor("hello\n");
5792        e.after_g('U', 1);
5793        // The engine should now be chord-pending (Pending::Op set).
5794        assert!(
5795            e.is_chord_pending(),
5796            "gU must set engine chord-pending (Pending::Op)"
5797        );
5798    }
5799
5800    #[test]
5801    fn after_g_g_star_searches_forward_non_whole_word() {
5802        // g* on word "foo" in "foobar" should find the match.
5803        let mut e = fresh_editor("foo foobar\n");
5804        e.jump_cursor(0, 0); // cursor on 'f' of "foo"
5805        e.after_g('*', 1);
5806        // After g* the cursor should have moved (ScreenDown motion is
5807        // not applicable here; WordAtCursor forward moves to next match).
5808        // At minimum: no panic and mode stays Normal.
5809        assert_eq!(e.vim_mode(), VimMode::Normal, "g* must stay in Normal mode");
5810    }
5811
5812    // ── apply_motion controller tests (Phase 3a) ────────────────────────────
5813
5814    #[test]
5815    fn apply_motion_char_left_moves_cursor() {
5816        let mut e = fresh_editor("hello\n");
5817        e.jump_cursor(0, 3);
5818        e.apply_motion(crate::MotionKind::CharLeft, 1);
5819        assert_eq!(e.cursor(), (0, 2), "CharLeft moves one col left");
5820    }
5821
5822    #[test]
5823    fn apply_motion_char_left_clamps_at_col_zero() {
5824        let mut e = fresh_editor("hello\n");
5825        e.jump_cursor(0, 0);
5826        e.apply_motion(crate::MotionKind::CharLeft, 1);
5827        assert_eq!(e.cursor(), (0, 0), "CharLeft at col 0 must not wrap");
5828    }
5829
5830    #[test]
5831    fn apply_motion_char_left_with_count() {
5832        let mut e = fresh_editor("hello\n");
5833        e.jump_cursor(0, 4);
5834        e.apply_motion(crate::MotionKind::CharLeft, 3);
5835        assert_eq!(e.cursor(), (0, 1), "CharLeft count=3 moves three cols left");
5836    }
5837
5838    #[test]
5839    fn apply_motion_char_right_moves_cursor() {
5840        let mut e = fresh_editor("hello\n");
5841        e.jump_cursor(0, 0);
5842        e.apply_motion(crate::MotionKind::CharRight, 1);
5843        assert_eq!(e.cursor(), (0, 1), "CharRight moves one col right");
5844    }
5845
5846    #[test]
5847    fn apply_motion_char_right_clamps_at_last_char() {
5848        let mut e = fresh_editor("hello\n");
5849        // "hello" has chars at 0..=4; normal mode clamps at 4.
5850        e.jump_cursor(0, 4);
5851        e.apply_motion(crate::MotionKind::CharRight, 1);
5852        assert_eq!(
5853            e.cursor(),
5854            (0, 4),
5855            "CharRight at end must not go past last char"
5856        );
5857    }
5858
5859    #[test]
5860    fn apply_motion_line_down_moves_cursor() {
5861        let mut e = fresh_editor("line0\nline1\nline2\n");
5862        e.jump_cursor(0, 0);
5863        e.apply_motion(crate::MotionKind::LineDown, 1);
5864        assert_eq!(e.cursor().0, 1, "LineDown moves one row down");
5865    }
5866
5867    #[test]
5868    fn apply_motion_line_down_with_count() {
5869        let mut e = fresh_editor("line0\nline1\nline2\n");
5870        e.jump_cursor(0, 0);
5871        e.apply_motion(crate::MotionKind::LineDown, 2);
5872        assert_eq!(e.cursor().0, 2, "LineDown count=2 moves two rows down");
5873    }
5874
5875    #[test]
5876    fn apply_motion_line_up_moves_cursor() {
5877        let mut e = fresh_editor("line0\nline1\nline2\n");
5878        e.jump_cursor(2, 0);
5879        e.apply_motion(crate::MotionKind::LineUp, 1);
5880        assert_eq!(e.cursor().0, 1, "LineUp moves one row up");
5881    }
5882
5883    #[test]
5884    fn apply_motion_line_up_clamps_at_top() {
5885        let mut e = fresh_editor("line0\nline1\n");
5886        e.jump_cursor(0, 0);
5887        e.apply_motion(crate::MotionKind::LineUp, 1);
5888        assert_eq!(e.cursor().0, 0, "LineUp at top must not go negative");
5889    }
5890
5891    #[test]
5892    fn apply_motion_first_non_blank_down_moves_and_lands_on_non_blank() {
5893        // Line 0: "  hello" (indent 2), line 1: "  world" (indent 2).
5894        let mut e = fresh_editor("  hello\n  world\n");
5895        e.jump_cursor(0, 0);
5896        e.apply_motion(crate::MotionKind::FirstNonBlankDown, 1);
5897        assert_eq!(e.cursor().0, 1, "FirstNonBlankDown must move to next row");
5898        assert_eq!(
5899            e.cursor().1,
5900            2,
5901            "FirstNonBlankDown must land on first non-blank col"
5902        );
5903    }
5904
5905    #[test]
5906    fn apply_motion_first_non_blank_up_moves_and_lands_on_non_blank() {
5907        let mut e = fresh_editor("  hello\n  world\n");
5908        e.jump_cursor(1, 4);
5909        e.apply_motion(crate::MotionKind::FirstNonBlankUp, 1);
5910        assert_eq!(e.cursor().0, 0, "FirstNonBlankUp must move to prev row");
5911        assert_eq!(
5912            e.cursor().1,
5913            2,
5914            "FirstNonBlankUp must land on first non-blank col"
5915        );
5916    }
5917
5918    #[test]
5919    fn apply_motion_count_zero_treated_as_one() {
5920        // count=0 must be normalised to 1 (count.max(1) in apply_motion_kind).
5921        let mut e = fresh_editor("hello\n");
5922        e.jump_cursor(0, 3);
5923        e.apply_motion(crate::MotionKind::CharLeft, 0);
5924        assert_eq!(e.cursor(), (0, 2), "count=0 treated as 1 for CharLeft");
5925    }
5926
5927    // ── apply_motion controller tests (Phase 3b) — word motions ─────────────
5928
5929    #[test]
5930    fn apply_motion_word_forward_moves_to_next_word() {
5931        // "hello world\n": 'w' from col 0 lands on 'w' of "world" at col 6.
5932        let mut e = fresh_editor("hello world\n");
5933        e.jump_cursor(0, 0);
5934        e.apply_motion(crate::MotionKind::WordForward, 1);
5935        assert_eq!(
5936            e.cursor(),
5937            (0, 6),
5938            "WordForward moves to start of next word"
5939        );
5940    }
5941
5942    #[test]
5943    fn apply_motion_word_forward_with_count() {
5944        // "one two three\n": 2w from col 0 → start of "three" at col 8.
5945        let mut e = fresh_editor("one two three\n");
5946        e.jump_cursor(0, 0);
5947        e.apply_motion(crate::MotionKind::WordForward, 2);
5948        assert_eq!(e.cursor(), (0, 8), "WordForward count=2 skips two words");
5949    }
5950
5951    #[test]
5952    fn apply_motion_big_word_forward_moves_to_next_big_word() {
5953        // "foo.bar baz\n": W from col 0 skips entire "foo.bar" (one WORD) to 'b' at col 8.
5954        let mut e = fresh_editor("foo.bar baz\n");
5955        e.jump_cursor(0, 0);
5956        e.apply_motion(crate::MotionKind::BigWordForward, 1);
5957        assert_eq!(e.cursor(), (0, 8), "BigWordForward skips the whole WORD");
5958    }
5959
5960    #[test]
5961    fn apply_motion_big_word_forward_with_count() {
5962        // "aa bb cc\n": 2W from col 0 → start of "cc" at col 6.
5963        let mut e = fresh_editor("aa bb cc\n");
5964        e.jump_cursor(0, 0);
5965        e.apply_motion(crate::MotionKind::BigWordForward, 2);
5966        assert_eq!(e.cursor(), (0, 6), "BigWordForward count=2 skips two WORDs");
5967    }
5968
5969    #[test]
5970    fn apply_motion_word_backward_moves_to_prev_word() {
5971        // "hello world\n": 'b' from col 6 ('w') lands back at col 0 ('h').
5972        let mut e = fresh_editor("hello world\n");
5973        e.jump_cursor(0, 6);
5974        e.apply_motion(crate::MotionKind::WordBackward, 1);
5975        assert_eq!(
5976            e.cursor(),
5977            (0, 0),
5978            "WordBackward moves to start of prev word"
5979        );
5980    }
5981
5982    #[test]
5983    fn apply_motion_word_backward_with_count() {
5984        // "one two three\n": 2b from col 8 ('t' of "three") → col 0 ('o' of "one").
5985        let mut e = fresh_editor("one two three\n");
5986        e.jump_cursor(0, 8);
5987        e.apply_motion(crate::MotionKind::WordBackward, 2);
5988        assert_eq!(
5989            e.cursor(),
5990            (0, 0),
5991            "WordBackward count=2 skips two words back"
5992        );
5993    }
5994
5995    #[test]
5996    fn apply_motion_big_word_backward_moves_to_prev_big_word() {
5997        // "foo.bar baz\n": B from col 8 ('b' of "baz") → col 0 (start of "foo.bar" WORD).
5998        let mut e = fresh_editor("foo.bar baz\n");
5999        e.jump_cursor(0, 8);
6000        e.apply_motion(crate::MotionKind::BigWordBackward, 1);
6001        assert_eq!(
6002            e.cursor(),
6003            (0, 0),
6004            "BigWordBackward jumps to start of prev WORD"
6005        );
6006    }
6007
6008    #[test]
6009    fn apply_motion_big_word_backward_with_count() {
6010        // "aa bb cc\n": 2B from col 6 ('c') → col 0 ('a').
6011        let mut e = fresh_editor("aa bb cc\n");
6012        e.jump_cursor(0, 6);
6013        e.apply_motion(crate::MotionKind::BigWordBackward, 2);
6014        assert_eq!(
6015            e.cursor(),
6016            (0, 0),
6017            "BigWordBackward count=2 skips two WORDs back"
6018        );
6019    }
6020
6021    #[test]
6022    fn apply_motion_word_end_moves_to_end_of_word() {
6023        // "hello world\n": 'e' from col 0 lands on 'o' of "hello" at col 4.
6024        let mut e = fresh_editor("hello world\n");
6025        e.jump_cursor(0, 0);
6026        e.apply_motion(crate::MotionKind::WordEnd, 1);
6027        assert_eq!(e.cursor(), (0, 4), "WordEnd moves to end of current word");
6028    }
6029
6030    #[test]
6031    fn apply_motion_word_end_with_count() {
6032        // "one two three\n": 2e from col 0 → end of "two" at col 6.
6033        let mut e = fresh_editor("one two three\n");
6034        e.jump_cursor(0, 0);
6035        e.apply_motion(crate::MotionKind::WordEnd, 2);
6036        assert_eq!(
6037            e.cursor(),
6038            (0, 6),
6039            "WordEnd count=2 lands on end of second word"
6040        );
6041    }
6042
6043    #[test]
6044    fn apply_motion_big_word_end_moves_to_end_of_big_word() {
6045        // "foo.bar baz\n": E from col 0 → end of "foo.bar" WORD at col 6.
6046        let mut e = fresh_editor("foo.bar baz\n");
6047        e.jump_cursor(0, 0);
6048        e.apply_motion(crate::MotionKind::BigWordEnd, 1);
6049        assert_eq!(e.cursor(), (0, 6), "BigWordEnd lands on end of WORD");
6050    }
6051
6052    #[test]
6053    fn apply_motion_big_word_end_with_count() {
6054        // "aa bb cc\n": 2E from col 0 → end of "bb" at col 4.
6055        let mut e = fresh_editor("aa bb cc\n");
6056        e.jump_cursor(0, 0);
6057        e.apply_motion(crate::MotionKind::BigWordEnd, 2);
6058        assert_eq!(
6059            e.cursor(),
6060            (0, 4),
6061            "BigWordEnd count=2 lands on end of second WORD"
6062        );
6063    }
6064
6065    // ── apply_motion controller tests (Phase 3c) — line-anchor motions ────────
6066
6067    #[test]
6068    fn apply_motion_line_start_lands_at_col_zero() {
6069        // "  foo bar  \n": `0` from col 5 → col 0 unconditionally.
6070        let mut e = fresh_editor("  foo bar  \n");
6071        e.jump_cursor(0, 5);
6072        e.apply_motion(crate::MotionKind::LineStart, 1);
6073        assert_eq!(e.cursor(), (0, 0), "LineStart lands at col 0");
6074    }
6075
6076    #[test]
6077    fn apply_motion_line_start_from_beginning_stays_at_col_zero() {
6078        // Already at col 0 — motion is a no-op but must not panic.
6079        let mut e = fresh_editor("  foo bar  \n");
6080        e.jump_cursor(0, 0);
6081        e.apply_motion(crate::MotionKind::LineStart, 1);
6082        assert_eq!(e.cursor(), (0, 0), "LineStart from col 0 stays at col 0");
6083    }
6084
6085    #[test]
6086    fn apply_motion_first_non_blank_lands_on_first_non_blank() {
6087        // "  foo bar  \n": `^` from col 0 → col 2 ('f').
6088        let mut e = fresh_editor("  foo bar  \n");
6089        e.jump_cursor(0, 0);
6090        e.apply_motion(crate::MotionKind::FirstNonBlank, 1);
6091        assert_eq!(
6092            e.cursor(),
6093            (0, 2),
6094            "FirstNonBlank lands on first non-blank char"
6095        );
6096    }
6097
6098    #[test]
6099    fn apply_motion_first_non_blank_on_blank_line_lands_at_zero() {
6100        // "   \n": all whitespace — `^` must land at col 0.
6101        let mut e = fresh_editor("   \n");
6102        e.jump_cursor(0, 2);
6103        e.apply_motion(crate::MotionKind::FirstNonBlank, 1);
6104        assert_eq!(
6105            e.cursor(),
6106            (0, 0),
6107            "FirstNonBlank on blank line stays at col 0"
6108        );
6109    }
6110
6111    #[test]
6112    fn apply_motion_line_end_lands_on_last_char() {
6113        // "  foo bar  \n": last char is the second space at col 10.
6114        let mut e = fresh_editor("  foo bar  \n");
6115        e.jump_cursor(0, 0);
6116        e.apply_motion(crate::MotionKind::LineEnd, 1);
6117        assert_eq!(e.cursor(), (0, 10), "LineEnd lands on last char of line");
6118    }
6119
6120    #[test]
6121    fn apply_motion_line_end_on_empty_line_stays_at_zero() {
6122        // "\n": empty line — `$` must stay at col 0.
6123        let mut e = fresh_editor("\n");
6124        e.jump_cursor(0, 0);
6125        e.apply_motion(crate::MotionKind::LineEnd, 1);
6126        assert_eq!(e.cursor(), (0, 0), "LineEnd on empty line stays at col 0");
6127    }
6128
6129    // ── apply_motion controller tests (Phase 3d) — doc-level motion ───────────
6130
6131    #[test]
6132    fn goto_line_count_1_lands_on_last_line() {
6133        // "foo\nbar\nbaz\n": bare `G` (count=1) → last content line (row 2).
6134        // Count convention: apply_motion_kind normalises 1 → execute_motion
6135        // with count=1 → FileBottom arm sees count <= 1 → move_bottom(0) =
6136        // last content row.
6137        let mut e = fresh_editor("foo\nbar\nbaz\n");
6138        e.jump_cursor(0, 0);
6139        e.apply_motion(crate::MotionKind::GotoLine, 1);
6140        assert_eq!(e.cursor(), (2, 0), "bare G lands on last content row");
6141    }
6142
6143    #[test]
6144    fn goto_line_count_5_lands_on_line_5() {
6145        // 6-line buffer (rows 0-5); `5G` → row 4 (1-based line 5).
6146        let mut e = fresh_editor("a\nb\nc\nd\ne\nf\n");
6147        e.jump_cursor(0, 0);
6148        e.apply_motion(crate::MotionKind::GotoLine, 5);
6149        assert_eq!(e.cursor(), (4, 0), "5G lands on row 4 (1-based line 5)");
6150    }
6151
6152    #[test]
6153    fn goto_line_count_past_buffer_clamps_to_last_line() {
6154        // "foo\nbar\nbaz\n": `100G` → last content line (row 2), clamped.
6155        let mut e = fresh_editor("foo\nbar\nbaz\n");
6156        e.jump_cursor(0, 0);
6157        e.apply_motion(crate::MotionKind::GotoLine, 100);
6158        assert_eq!(e.cursor(), (2, 0), "100G clamps to last content row");
6159    }
6160
6161    // ── FindRepeat / FindRepeatReverse controller tests (Phase 3e) ────────────
6162
6163    #[test]
6164    fn find_repeat_after_f_finds_next_occurrence() {
6165        // "abcabc", cursor at (0,0). `fc` lands on (0,2). `;` repeats → (0,5).
6166        let mut e = fresh_editor("abcabc");
6167        e.jump_cursor(0, 0);
6168        e.find_char('c', true, false, 1);
6169        assert_eq!(e.cursor(), (0, 2), "fc must land on first 'c'");
6170        e.apply_motion(crate::MotionKind::FindRepeat, 1);
6171        assert_eq!(
6172            e.cursor(),
6173            (0, 5),
6174            "find_repeat (;) must advance to second 'c'"
6175        );
6176    }
6177
6178    #[test]
6179    fn find_repeat_reverse_after_f_finds_prev_occurrence() {
6180        // "abcabc", cursor at (0,0). `fc` lands on (0,2). `;` → (0,5). `,` back → (0,2).
6181        let mut e = fresh_editor("abcabc");
6182        e.jump_cursor(0, 0);
6183        e.find_char('c', true, false, 1);
6184        assert_eq!(e.cursor(), (0, 2), "fc must land on first 'c'");
6185        e.apply_motion(crate::MotionKind::FindRepeat, 1);
6186        assert_eq!(e.cursor(), (0, 5), "; must advance to second 'c'");
6187        e.apply_motion(crate::MotionKind::FindRepeatReverse, 1);
6188        assert_eq!(
6189            e.cursor(),
6190            (0, 2),
6191            "find_repeat_reverse (,) must go back to first 'c'"
6192        );
6193    }
6194
6195    #[test]
6196    fn find_repeat_with_no_prior_find_is_noop() {
6197        // Fresh editor, no prior find — `;` must not move cursor.
6198        let mut e = fresh_editor("abcabc");
6199        e.jump_cursor(0, 3);
6200        e.apply_motion(crate::MotionKind::FindRepeat, 1);
6201        assert_eq!(
6202            e.cursor(),
6203            (0, 3),
6204            "find_repeat with no prior find must be a no-op"
6205        );
6206    }
6207
6208    #[test]
6209    fn find_repeat_with_count_advances_count_times() {
6210        // "aXaXaX", cursor (0,0). `fX` → (0,1). `3;` → repeats 3× → (0,5).
6211        let mut e = fresh_editor("aXaXaX");
6212        e.jump_cursor(0, 0);
6213        e.find_char('X', true, false, 1);
6214        assert_eq!(e.cursor(), (0, 1), "fX must land on first 'X' at col 1");
6215        e.apply_motion(crate::MotionKind::FindRepeat, 3);
6216        assert_eq!(
6217            e.cursor(),
6218            (0, 5),
6219            "3; must advance 3 times from col 1 to col 5"
6220        );
6221    }
6222
6223    // ── BracketMatch controller tests (Phase 3f) ───────────────────────────────
6224
6225    #[test]
6226    fn bracket_match_jumps_to_matching_close_paren() {
6227        // "(abc)", cursor at (0,0) on `(` — `%` must jump to `)` at (0,4).
6228        let mut e = fresh_editor("(abc)");
6229        e.jump_cursor(0, 0);
6230        e.apply_motion(crate::MotionKind::BracketMatch, 1);
6231        assert_eq!(
6232            e.cursor(),
6233            (0, 4),
6234            "% on '(' must land on matching ')' at col 4"
6235        );
6236    }
6237
6238    #[test]
6239    fn bracket_match_jumps_to_matching_open_paren() {
6240        // "(abc)", cursor at (0,4) on `)` — `%` must jump back to `(` at (0,0).
6241        let mut e = fresh_editor("(abc)");
6242        e.jump_cursor(0, 4);
6243        e.apply_motion(crate::MotionKind::BracketMatch, 1);
6244        assert_eq!(
6245            e.cursor(),
6246            (0, 0),
6247            "% on ')' must land on matching '(' at col 0"
6248        );
6249    }
6250
6251    #[test]
6252    fn bracket_match_with_no_match_on_line_is_noop_or_engine_behaviour() {
6253        // "abcd", cursor at (0,2) — no bracket under cursor; engine returns
6254        // false from matching_bracket, cursor must not move.
6255        let mut e = fresh_editor("abcd");
6256        e.jump_cursor(0, 2);
6257        e.apply_motion(crate::MotionKind::BracketMatch, 1);
6258        assert_eq!(
6259            e.cursor(),
6260            (0, 2),
6261            "% with no bracket under cursor must be a no-op"
6262        );
6263    }
6264
6265    // ── Scroll / viewport motion controller tests (Phase 3g) ──────────────────
6266
6267    /// Helper: build a 20-line buffer, set viewport to rows [5..14] (height=10).
6268    fn fresh_viewport_editor() -> Editor {
6269        let content = many_lines(20);
6270        let mut e = Editor::new(
6271            hjkl_buffer::Buffer::from_str(&content),
6272            crate::types::DefaultHost::new(),
6273            crate::types::Options::default(),
6274        );
6275        // height=10, top_row=5 → visible rows 5..14.
6276        // set_viewport_height stores to the atomic; sync_buffer_from_textarea
6277        // propagates it to host.viewport_mut().height so motion helpers see it.
6278        e.set_viewport_height(10);
6279        e.sync_buffer_from_textarea();
6280        e.host_mut().viewport_mut().top_row = 5;
6281        e
6282    }
6283
6284    #[test]
6285    fn viewport_top_lands_on_first_visible_row() {
6286        // Viewport top=5, height=10. H (count=1) should land on row 5
6287        // (the first visible row, offset = count-1 = 0).
6288        let mut e = fresh_viewport_editor();
6289        e.jump_cursor(10, 0);
6290        e.apply_motion(crate::MotionKind::ViewportTop, 1);
6291        assert_eq!(
6292            e.cursor().0,
6293            5,
6294            "H (count=1) must land on viewport top row (5)"
6295        );
6296    }
6297
6298    #[test]
6299    fn viewport_top_with_count_offsets_down() {
6300        // H with count=3 → viewport top + (3-1) = 5 + 2 = row 7.
6301        let mut e = fresh_viewport_editor();
6302        e.jump_cursor(12, 0);
6303        e.apply_motion(crate::MotionKind::ViewportTop, 3);
6304        assert_eq!(e.cursor().0, 7, "3H must land at viewport top + 2 = row 7");
6305    }
6306
6307    #[test]
6308    fn viewport_middle_lands_on_middle_visible_row() {
6309        // Viewport top=5, height=10 → last visible = 14, mid = 5 + (14-5)/2 = 9.
6310        let mut e = fresh_viewport_editor();
6311        e.jump_cursor(0, 0);
6312        e.apply_motion(crate::MotionKind::ViewportMiddle, 1);
6313        assert_eq!(e.cursor().0, 9, "M must land on middle visible row (9)");
6314    }
6315
6316    #[test]
6317    fn viewport_bottom_lands_on_last_visible_row() {
6318        // L (count=1) → viewport bottom, offset = count-1 = 0 → row 14.
6319        let mut e = fresh_viewport_editor();
6320        e.jump_cursor(5, 0);
6321        e.apply_motion(crate::MotionKind::ViewportBottom, 1);
6322        assert_eq!(
6323            e.cursor().0,
6324            14,
6325            "L (count=1) must land on viewport bottom row (14)"
6326        );
6327    }
6328
6329    #[test]
6330    fn half_page_down_moves_cursor_by_half_window() {
6331        // viewport height=10, so half=5. Cursor at row 0 → row 5 after C-d.
6332        let mut e = Editor::new(
6333            hjkl_buffer::Buffer::from_str(&many_lines(30)),
6334            crate::types::DefaultHost::new(),
6335            crate::types::Options::default(),
6336        );
6337        e.set_viewport_height(10);
6338        e.jump_cursor(0, 0);
6339        e.apply_motion(crate::MotionKind::HalfPageDown, 1);
6340        assert_eq!(
6341            e.cursor().0,
6342            5,
6343            "<C-d> from row 0 with viewport height=10 must land on row 5"
6344        );
6345    }
6346
6347    #[test]
6348    fn half_page_up_moves_cursor_by_half_window_reverse() {
6349        // viewport height=10, half=5. Cursor at row 10 → row 5 after C-u.
6350        let mut e = Editor::new(
6351            hjkl_buffer::Buffer::from_str(&many_lines(30)),
6352            crate::types::DefaultHost::new(),
6353            crate::types::Options::default(),
6354        );
6355        e.set_viewport_height(10);
6356        e.jump_cursor(10, 0);
6357        e.apply_motion(crate::MotionKind::HalfPageUp, 1);
6358        assert_eq!(
6359            e.cursor().0,
6360            5,
6361            "<C-u> from row 10 with viewport height=10 must land on row 5"
6362        );
6363    }
6364
6365    #[test]
6366    fn full_page_down_moves_cursor_by_full_window() {
6367        // viewport height=10, full = 10 - 2 = 8. Cursor at row 0 → row 8.
6368        let mut e = Editor::new(
6369            hjkl_buffer::Buffer::from_str(&many_lines(30)),
6370            crate::types::DefaultHost::new(),
6371            crate::types::Options::default(),
6372        );
6373        e.set_viewport_height(10);
6374        e.jump_cursor(0, 0);
6375        e.apply_motion(crate::MotionKind::FullPageDown, 1);
6376        assert_eq!(
6377            e.cursor().0,
6378            8,
6379            "<C-f> from row 0 with viewport height=10 must land on row 8"
6380        );
6381    }
6382
6383    #[test]
6384    fn full_page_up_moves_cursor_by_full_window_reverse() {
6385        // viewport height=10, full=8. Cursor at row 10 → row 2.
6386        let mut e = Editor::new(
6387            hjkl_buffer::Buffer::from_str(&many_lines(30)),
6388            crate::types::DefaultHost::new(),
6389            crate::types::Options::default(),
6390        );
6391        e.set_viewport_height(10);
6392        e.jump_cursor(10, 0);
6393        e.apply_motion(crate::MotionKind::FullPageUp, 1);
6394        assert_eq!(
6395            e.cursor().0,
6396            2,
6397            "<C-b> from row 10 with viewport height=10 must land on row 2"
6398        );
6399    }
6400
6401    // ── set_mark_at_cursor unit tests ─────────────────────────────────────────
6402
6403    #[test]
6404    fn set_mark_at_cursor_alphabetic_records() {
6405        // `ma` at (0, 2) — mark 'a' must store (0, 2).
6406        let mut e = fresh_editor("hello");
6407        e.jump_cursor(0, 2);
6408        e.set_mark_at_cursor('a');
6409        assert_eq!(
6410            e.mark('a'),
6411            Some((0, 2)),
6412            "mark 'a' must record current pos"
6413        );
6414    }
6415
6416    #[test]
6417    fn set_mark_at_cursor_invalid_char_no_op() {
6418        // Invalid chars (digits, special) must not store a mark.
6419        let mut e = fresh_editor("hello");
6420        e.jump_cursor(0, 1);
6421        e.set_mark_at_cursor('1'); // digit — not alphanumeric in vim mark sense
6422        assert_eq!(e.mark('1'), None, "digit mark must be a no-op");
6423        e.set_mark_at_cursor('['); // special — only goto uses '[', not set_mark
6424        assert_eq!(
6425            e.mark('['),
6426            None,
6427            "bracket char must be a no-op for set_mark"
6428        );
6429    }
6430
6431    #[test]
6432    fn set_mark_at_cursor_special_left_bracket() {
6433        // Confirm '[' is NOT stored by set_mark_at_cursor (vim's `m[` is invalid).
6434        // The `[` mark is only set automatically by operator paths, not `m[`.
6435        let mut e = fresh_editor("hello");
6436        e.jump_cursor(0, 3);
6437        e.set_mark_at_cursor('[');
6438        assert_eq!(
6439            e.mark('['),
6440            None,
6441            "set_mark_at_cursor must reject '[' (vim: m[ is invalid)"
6442        );
6443    }
6444
6445    // ── goto_mark_line unit tests ─────────────────────────────────────────────
6446
6447    #[test]
6448    fn goto_mark_line_jumps_to_first_non_blank() {
6449        // Set mark 'a' at (1, 3), then jump back to (0, 0).
6450        // `'a` (linewise) must land on row 1, first non-blank column.
6451        let mut e = fresh_editor("hello\n  world\n");
6452        e.jump_cursor(1, 3);
6453        e.set_mark_at_cursor('a');
6454        e.jump_cursor(0, 0);
6455        e.goto_mark_line('a');
6456        assert_eq!(e.cursor().0, 1, "goto_mark_line must jump to mark row");
6457        // "  world" — first non-blank is col 2.
6458        assert_eq!(
6459            e.cursor().1,
6460            2,
6461            "goto_mark_line must land on first non-blank column"
6462        );
6463    }
6464
6465    #[test]
6466    fn goto_mark_line_unset_mark_no_op() {
6467        // Jumping to an unset mark must not move the cursor.
6468        let mut e = fresh_editor("hello\nworld\n");
6469        e.jump_cursor(1, 2);
6470        e.goto_mark_line('z'); // 'z' not set
6471        assert_eq!(e.cursor(), (1, 2), "unset mark jump must be a no-op");
6472    }
6473
6474    #[test]
6475    fn goto_mark_line_invalid_char_no_op() {
6476        // '!' is not a valid mark char — must not move cursor.
6477        let mut e = fresh_editor("hello\nworld\n");
6478        e.jump_cursor(0, 0);
6479        e.goto_mark_line('!');
6480        assert_eq!(e.cursor(), (0, 0), "invalid mark char must be a no-op");
6481    }
6482
6483    // ── goto_mark_char unit tests ─────────────────────────────────────────────
6484
6485    #[test]
6486    fn goto_mark_char_jumps_to_exact_pos() {
6487        // Set mark 'b' at (1, 4), then jump back to (0, 0).
6488        // `` `b `` (charwise) must land on (1, 4) exactly.
6489        let mut e = fresh_editor("hello\nworld\n");
6490        e.jump_cursor(1, 4);
6491        e.set_mark_at_cursor('b');
6492        e.jump_cursor(0, 0);
6493        e.goto_mark_char('b');
6494        assert_eq!(
6495            e.cursor(),
6496            (1, 4),
6497            "goto_mark_char must jump to exact mark position"
6498        );
6499    }
6500
6501    #[test]
6502    fn goto_mark_char_unset_mark_no_op() {
6503        // Jumping to an unset mark must not move the cursor.
6504        let mut e = fresh_editor("hello\nworld\n");
6505        e.jump_cursor(1, 1);
6506        e.goto_mark_char('x'); // 'x' not set
6507        assert_eq!(
6508            e.cursor(),
6509            (1, 1),
6510            "unset charwise mark jump must be a no-op"
6511        );
6512    }
6513
6514    #[test]
6515    fn goto_mark_char_invalid_char_no_op() {
6516        // '#' is not a valid mark char — must not move cursor.
6517        let mut e = fresh_editor("hello\nworld\n");
6518        e.jump_cursor(0, 2);
6519        e.goto_mark_char('#');
6520        assert_eq!(
6521            e.cursor(),
6522            (0, 2),
6523            "invalid charwise mark char must be a no-op"
6524        );
6525    }
6526
6527    // ── Macro controller API tests (Phase 5b) ─────────────────────────────────
6528
6529    #[test]
6530    fn start_macro_record_records_register() {
6531        let mut e = fresh_editor("hello");
6532        assert!(!e.is_recording_macro());
6533        e.start_macro_record('a');
6534        assert!(e.is_recording_macro());
6535        assert_eq!(e.recording_register(), Some('a'));
6536    }
6537
6538    #[test]
6539    fn start_macro_record_capital_seeds_existing() {
6540        // `qa` records "h", stop. Then `qA` should seed from existing 'a' reg.
6541        let mut e = fresh_editor("hello");
6542        e.start_macro_record('a');
6543        e.record_input(crate::input::Input {
6544            key: crate::input::Key::Char('h'),
6545            ..Default::default()
6546        });
6547        e.stop_macro_record();
6548        // Start capital 'A' — should seed from existing 'a' register.
6549        e.start_macro_record('A');
6550        // recording_keys should now contain 1 input (the seeded 'h').
6551        assert_eq!(
6552            e.vim.recording_keys.len(),
6553            1,
6554            "capital record must seed from existing lowercase reg"
6555        );
6556    }
6557
6558    #[test]
6559    fn stop_macro_record_writes_register() {
6560        let mut e = fresh_editor("hello");
6561        e.start_macro_record('a');
6562        e.record_input(crate::input::Input {
6563            key: crate::input::Key::Char('h'),
6564            ..Default::default()
6565        });
6566        e.record_input(crate::input::Input {
6567            key: crate::input::Key::Char('l'),
6568            ..Default::default()
6569        });
6570        e.stop_macro_record();
6571        assert!(!e.is_recording_macro());
6572        // Register 'a' should contain "hl".
6573        let text = e
6574            .registers()
6575            .read('a')
6576            .map(|s| s.text.clone())
6577            .unwrap_or_default();
6578        assert_eq!(
6579            text, "hl",
6580            "stop_macro_record must write encoded keys to register"
6581        );
6582    }
6583
6584    #[test]
6585    fn is_recording_macro_reflects_state() {
6586        let mut e = fresh_editor("hello");
6587        assert!(!e.is_recording_macro());
6588        e.start_macro_record('b');
6589        assert!(e.is_recording_macro());
6590        e.stop_macro_record();
6591        assert!(!e.is_recording_macro());
6592    }
6593
6594    #[test]
6595    fn play_macro_returns_decoded_inputs() {
6596        let mut e = fresh_editor("hello");
6597        // Write "jj" into register 'a'.
6598        e.set_named_register_text('a', "jj".to_string());
6599        let inputs = e.play_macro('a', 1);
6600        assert_eq!(inputs.len(), 2);
6601        assert_eq!(inputs[0].key, crate::input::Key::Char('j'));
6602        assert_eq!(inputs[1].key, crate::input::Key::Char('j'));
6603        assert!(e.is_replaying_macro(), "play_macro must set replaying flag");
6604        e.end_macro_replay();
6605        assert!(!e.is_replaying_macro());
6606    }
6607
6608    #[test]
6609    fn play_macro_at_uses_last_macro() {
6610        let mut e = fresh_editor("hello");
6611        e.set_named_register_text('a', "k".to_string());
6612        // Play 'a' first to set last_macro.
6613        let _ = e.play_macro('a', 1);
6614        e.end_macro_replay();
6615        // Now `@@` should replay 'a' again.
6616        let inputs = e.play_macro('@', 1);
6617        assert_eq!(inputs.len(), 1);
6618        assert_eq!(inputs[0].key, crate::input::Key::Char('k'));
6619        e.end_macro_replay();
6620    }
6621
6622    #[test]
6623    fn play_macro_with_count_repeats() {
6624        let mut e = fresh_editor("hello");
6625        e.set_named_register_text('a', "j".to_string());
6626        let inputs = e.play_macro('a', 3);
6627        assert_eq!(inputs.len(), 3, "3@a must produce 3 inputs");
6628        e.end_macro_replay();
6629    }
6630
6631    #[test]
6632    fn record_input_appends_when_recording() {
6633        let mut e = fresh_editor("hello");
6634        // Not recording: record_input is a no-op.
6635        e.record_input(crate::input::Input {
6636            key: crate::input::Key::Char('j'),
6637            ..Default::default()
6638        });
6639        assert_eq!(e.vim.recording_keys.len(), 0);
6640        // Start recording: record_input appends.
6641        e.start_macro_record('a');
6642        e.record_input(crate::input::Input {
6643            key: crate::input::Key::Char('j'),
6644            ..Default::default()
6645        });
6646        e.record_input(crate::input::Input {
6647            key: crate::input::Key::Char('k'),
6648            ..Default::default()
6649        });
6650        assert_eq!(e.vim.recording_keys.len(), 2);
6651        // During replay: record_input must NOT append.
6652        e.vim.replaying_macro = true;
6653        e.record_input(crate::input::Input {
6654            key: crate::input::Key::Char('l'),
6655            ..Default::default()
6656        });
6657        assert_eq!(
6658            e.vim.recording_keys.len(),
6659            2,
6660            "record_input must skip during replay"
6661        );
6662        e.vim.replaying_macro = false;
6663        e.stop_macro_record();
6664    }
6665
6666    // ── Phase 6.1 insert-mode primitive tests (kryptic-sh/hjkl#87) ────────────
6667
6668    /// Helper: enter insert mode via the public bridge, then call the method under test.
6669    fn enter_insert(e: &mut Editor) {
6670        e.enter_insert_i(1);
6671        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
6672    }
6673
6674    #[test]
6675    fn insert_char_basic() {
6676        let mut e = fresh_editor("hello");
6677        enter_insert(&mut e);
6678        e.insert_char('X');
6679        assert_eq!(e.buffer().lines()[0], "Xhello");
6680        assert!(e.take_dirty());
6681    }
6682
6683    #[test]
6684    fn insert_newline_splits_line() {
6685        let mut e = fresh_editor("hello");
6686        // Move to col 3 so we split "hel" | "lo".
6687        e.jump_cursor(0, 3);
6688        enter_insert(&mut e);
6689        e.insert_newline();
6690        let lines = e.buffer().lines().to_vec();
6691        assert_eq!(lines[0], "hel");
6692        assert_eq!(lines[1], "lo");
6693    }
6694
6695    #[test]
6696    fn insert_tab_expandtab_inserts_spaces() {
6697        let mut e = fresh_editor("");
6698        // Default options: expandtab=true, softtabstop=4, tabstop=4.
6699        enter_insert(&mut e);
6700        e.insert_tab();
6701        // At col 0 with sts=4: 4 spaces inserted.
6702        assert_eq!(e.buffer().lines()[0], "    ");
6703    }
6704
6705    #[test]
6706    fn insert_tab_real_tab_when_noexpandtab() {
6707        let opts = crate::types::Options {
6708            expandtab: false,
6709            ..crate::types::Options::default()
6710        };
6711        let mut e = Editor::new(
6712            hjkl_buffer::Buffer::new(),
6713            crate::types::DefaultHost::new(),
6714            opts,
6715        );
6716        e.set_content("");
6717        enter_insert(&mut e);
6718        e.insert_tab();
6719        assert_eq!(e.buffer().lines()[0], "\t");
6720    }
6721
6722    #[test]
6723    fn insert_backspace_single_char() {
6724        // Cursor at col 3 in "hello", backspace deletes 'l'.
6725        let mut e = fresh_editor("hello");
6726        e.jump_cursor(0, 3);
6727        enter_insert(&mut e);
6728        e.insert_backspace();
6729        assert_eq!(e.buffer().lines()[0], "helo");
6730    }
6731
6732    #[test]
6733    fn insert_backspace_softtabstop() {
6734        // With sts=4, expandtab: 4 spaces at col 4 → one backspace deletes all 4.
6735        let mut e = fresh_editor("    hello");
6736        e.jump_cursor(0, 4);
6737        enter_insert(&mut e);
6738        e.insert_backspace();
6739        assert_eq!(e.buffer().lines()[0], "hello");
6740    }
6741
6742    #[test]
6743    fn insert_backspace_join_up() {
6744        // At col 0 on row 1, backspace joins with the previous line.
6745        let mut e = fresh_editor("foo\nbar");
6746        e.jump_cursor(1, 0);
6747        enter_insert(&mut e);
6748        e.insert_backspace();
6749        // Two rows merged into one.
6750        assert_eq!(e.buffer().lines().len(), 1);
6751        assert_eq!(e.buffer().lines()[0], "foobar");
6752    }
6753
6754    #[test]
6755    fn leave_insert_steps_back_col() {
6756        // Esc in insert mode should move the cursor one cell left (vim convention).
6757        let mut e = fresh_editor("hello");
6758        e.jump_cursor(0, 3);
6759        enter_insert(&mut e);
6760        // Type one char so cursor is at col 4, then call leave_insert_to_normal.
6761        e.insert_char('X');
6762        // cursor is now at col 4 (after the inserted 'X').
6763        let pre_col = e.cursor().1;
6764        e.leave_insert_to_normal();
6765        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
6766        // Cursor stepped back one.
6767        assert_eq!(e.cursor().1, pre_col - 1);
6768    }
6769
6770    #[test]
6771    fn insert_ctrl_w_word_back() {
6772        // Ctrl-W deletes from cursor back to word start.
6773        // "hello world" — cursor at end of "world" (col 11).
6774        let mut e = fresh_editor("hello world");
6775        // Normal mode clamps cursor to col 10 (last char); jump_cursor doesn't clamp.
6776        e.jump_cursor(0, 11);
6777        enter_insert(&mut e);
6778        e.insert_ctrl_w();
6779        // "world" (5 chars) deleted, leaving "hello ".
6780        assert_eq!(e.buffer().lines()[0], "hello ");
6781    }
6782
6783    #[test]
6784    fn insert_ctrl_u_deletes_to_line_start() {
6785        let mut e = fresh_editor("hello world");
6786        e.jump_cursor(0, 5);
6787        enter_insert(&mut e);
6788        e.insert_ctrl_u();
6789        assert_eq!(e.buffer().lines()[0], " world");
6790    }
6791
6792    #[test]
6793    fn insert_ctrl_h_single_backspace() {
6794        // Ctrl-H is an alias for Backspace in insert mode.
6795        let mut e = fresh_editor("hello");
6796        e.jump_cursor(0, 3);
6797        enter_insert(&mut e);
6798        e.insert_ctrl_h();
6799        assert_eq!(e.buffer().lines()[0], "helo");
6800    }
6801
6802    #[test]
6803    fn insert_ctrl_h_join_up() {
6804        let mut e = fresh_editor("foo\nbar");
6805        e.jump_cursor(1, 0);
6806        enter_insert(&mut e);
6807        e.insert_ctrl_h();
6808        assert_eq!(e.buffer().lines().len(), 1);
6809        assert_eq!(e.buffer().lines()[0], "foobar");
6810    }
6811
6812    #[test]
6813    fn insert_ctrl_t_indents_current_line() {
6814        let mut e = Editor::new(
6815            hjkl_buffer::Buffer::new(),
6816            crate::types::DefaultHost::new(),
6817            crate::types::Options {
6818                shiftwidth: 4,
6819                ..crate::types::Options::default()
6820            },
6821        );
6822        e.set_content("hello");
6823        enter_insert(&mut e);
6824        e.insert_ctrl_t();
6825        assert_eq!(e.buffer().lines()[0], "    hello");
6826    }
6827
6828    #[test]
6829    fn insert_ctrl_d_outdents_current_line() {
6830        let mut e = Editor::new(
6831            hjkl_buffer::Buffer::new(),
6832            crate::types::DefaultHost::new(),
6833            crate::types::Options {
6834                shiftwidth: 4,
6835                ..crate::types::Options::default()
6836            },
6837        );
6838        e.set_content("    hello");
6839        enter_insert(&mut e);
6840        e.insert_ctrl_d();
6841        assert_eq!(e.buffer().lines()[0], "hello");
6842    }
6843
6844    #[test]
6845    fn insert_ctrl_o_arm_sets_one_shot_normal() {
6846        let mut e = fresh_editor("hello");
6847        enter_insert(&mut e);
6848        e.insert_ctrl_o_arm();
6849        // Mode should flip to Normal (one-shot).
6850        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
6851    }
6852
6853    #[test]
6854    fn insert_ctrl_r_arm_sets_pending_register() {
6855        let mut e = fresh_editor("hello");
6856        enter_insert(&mut e);
6857        e.insert_ctrl_r_arm();
6858        // pending register flag set; mode stays Insert.
6859        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
6860        assert!(e.vim.insert_pending_register);
6861    }
6862
6863    #[test]
6864    fn insert_delete_removes_char_under_cursor() {
6865        let mut e = fresh_editor("hello");
6866        e.jump_cursor(0, 2);
6867        enter_insert(&mut e);
6868        e.insert_delete();
6869        assert_eq!(e.buffer().lines()[0], "helo");
6870    }
6871
6872    #[test]
6873    fn insert_delete_joins_lines_at_eol() {
6874        let mut e = fresh_editor("foo\nbar");
6875        // Position at end of row 0 (col 3 = past last char).
6876        e.jump_cursor(0, 3);
6877        enter_insert(&mut e);
6878        e.insert_delete();
6879        assert_eq!(e.buffer().lines().len(), 1);
6880        assert_eq!(e.buffer().lines()[0], "foobar");
6881    }
6882
6883    #[test]
6884    fn insert_arrow_left_moves_cursor() {
6885        let mut e = fresh_editor("hello");
6886        e.jump_cursor(0, 3);
6887        enter_insert(&mut e);
6888        e.insert_arrow(crate::vim::InsertDir::Left);
6889        assert_eq!(e.cursor().1, 2);
6890    }
6891
6892    #[test]
6893    fn insert_arrow_right_moves_cursor() {
6894        let mut e = fresh_editor("hello");
6895        e.jump_cursor(0, 2);
6896        enter_insert(&mut e);
6897        e.insert_arrow(crate::vim::InsertDir::Right);
6898        assert_eq!(e.cursor().1, 3);
6899    }
6900
6901    #[test]
6902    fn insert_arrow_up_moves_cursor() {
6903        let mut e = fresh_editor("foo\nbar");
6904        e.jump_cursor(1, 0);
6905        enter_insert(&mut e);
6906        e.insert_arrow(crate::vim::InsertDir::Up);
6907        assert_eq!(e.cursor().0, 0);
6908    }
6909
6910    #[test]
6911    fn insert_arrow_down_moves_cursor() {
6912        let mut e = fresh_editor("foo\nbar");
6913        e.jump_cursor(0, 0);
6914        enter_insert(&mut e);
6915        e.insert_arrow(crate::vim::InsertDir::Down);
6916        assert_eq!(e.cursor().0, 1);
6917    }
6918
6919    #[test]
6920    fn insert_home_moves_to_line_start() {
6921        let mut e = fresh_editor("hello");
6922        e.jump_cursor(0, 4);
6923        enter_insert(&mut e);
6924        e.insert_home();
6925        assert_eq!(e.cursor().1, 0);
6926    }
6927
6928    #[test]
6929    fn insert_end_moves_to_line_end() {
6930        let mut e = fresh_editor("hello");
6931        e.jump_cursor(0, 0);
6932        enter_insert(&mut e);
6933        e.insert_end();
6934        // move_line_end lands on the last char (col 4) for "hello".
6935        assert_eq!(e.cursor().1, 4);
6936    }
6937
6938    #[test]
6939    fn insert_pageup_does_not_panic() {
6940        let mut e = fresh_editor("line1\nline2\nline3");
6941        e.jump_cursor(2, 0);
6942        enter_insert(&mut e);
6943        // Viewport height 0 → no crash (viewport_h saturates to 1 row effectively).
6944        e.insert_pageup(24);
6945    }
6946
6947    #[test]
6948    fn insert_pagedown_does_not_panic() {
6949        let mut e = fresh_editor("line1\nline2\nline3");
6950        e.jump_cursor(0, 0);
6951        enter_insert(&mut e);
6952        e.insert_pagedown(24);
6953    }
6954
6955    #[test]
6956    fn leave_insert_to_normal_exits_mode() {
6957        let mut e = fresh_editor("hello");
6958        enter_insert(&mut e);
6959        e.leave_insert_to_normal();
6960        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
6961    }
6962
6963    #[test]
6964    fn insert_backspace_at_buffer_start_is_noop() {
6965        let mut e = fresh_editor("hello");
6966        e.jump_cursor(0, 0);
6967        enter_insert(&mut e);
6968        // No previous char and no previous row — should not panic.
6969        e.insert_backspace();
6970        assert_eq!(e.buffer().lines()[0], "hello");
6971    }
6972
6973    #[test]
6974    fn insert_delete_at_buffer_end_is_noop() {
6975        let mut e = fresh_editor("hello");
6976        // Cursor at col 5 (past last char index of 4), no next row.
6977        e.jump_cursor(0, 5);
6978        enter_insert(&mut e);
6979        // col 5 >= line_chars (5), no next row → no-op.
6980        e.insert_delete();
6981        assert_eq!(e.buffer().lines()[0], "hello");
6982    }
6983
6984    // ── Phase 6.2: normal-mode primitive tests (kryptic-sh/hjkl#88) ─────────
6985
6986    // Helper: set content and ensure we are in Normal mode.
6987    fn normal_editor(initial: &str) -> Editor {
6988        let e = fresh_editor(initial);
6989        // fresh_editor starts in Normal; this is just a readability alias.
6990        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
6991        e
6992    }
6993
6994    // ── Insert-mode entry ────────────────────────────────────────────────────
6995
6996    #[test]
6997    fn enter_insert_i_lands_in_insert_at_cursor() {
6998        let mut e = normal_editor("hello");
6999        e.jump_cursor(0, 2);
7000        e.enter_insert_i(1);
7001        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7002        assert_eq!(e.cursor(), (0, 2));
7003    }
7004
7005    #[test]
7006    fn enter_insert_shift_i_moves_to_first_non_blank_then_insert() {
7007        let mut e = normal_editor("  hello");
7008        e.jump_cursor(0, 5);
7009        e.enter_insert_shift_i(1);
7010        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7011        // First non-blank of "  hello" is col 2.
7012        assert_eq!(e.cursor().1, 2);
7013    }
7014
7015    #[test]
7016    fn enter_insert_a_advances_one_then_insert() {
7017        let mut e = normal_editor("hello");
7018        e.jump_cursor(0, 0);
7019        e.enter_insert_a(1);
7020        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7021        assert_eq!(e.cursor().1, 1);
7022    }
7023
7024    #[test]
7025    fn enter_insert_shift_a_lands_at_eol() {
7026        let mut e = normal_editor("hello");
7027        e.enter_insert_shift_a(1);
7028        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7029        assert_eq!(e.cursor().1, 5);
7030    }
7031
7032    #[test]
7033    fn open_line_below_creates_new_line_and_insert() {
7034        let mut e = normal_editor("hello\nworld");
7035        e.open_line_below(1);
7036        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7037        assert_eq!(e.buffer().lines().len(), 3);
7038    }
7039
7040    #[test]
7041    fn open_line_above_creates_line_before_cursor() {
7042        let mut e = normal_editor("hello\nworld");
7043        e.jump_cursor(1, 0);
7044        e.open_line_above(1);
7045        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7046        assert_eq!(e.buffer().lines().len(), 3);
7047        assert_eq!(e.cursor().0, 1);
7048    }
7049
7050    #[test]
7051    fn open_line_above_at_row_0_creates_blank_first_line() {
7052        let mut e = normal_editor("hello");
7053        e.open_line_above(1);
7054        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7055        // New blank line is row 0; old "hello" is row 1.
7056        assert_eq!(e.cursor().0, 0);
7057        assert_eq!(e.buffer().lines()[1], "hello");
7058    }
7059
7060    #[test]
7061    fn enter_replace_mode_sets_insert_mode() {
7062        let mut e = normal_editor("hello");
7063        e.enter_replace_mode(1);
7064        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7065    }
7066
7067    // ── Char / line ops ──────────────────────────────────────────────────────
7068
7069    #[test]
7070    fn delete_char_forward_removes_one_char() {
7071        let mut e = normal_editor("hello");
7072        e.jump_cursor(0, 1);
7073        e.delete_char_forward(1);
7074        assert_eq!(e.buffer().lines()[0], "hllo");
7075    }
7076
7077    #[test]
7078    fn delete_char_forward_count_5_removes_five() {
7079        let mut e = normal_editor("hello world");
7080        e.delete_char_forward(5);
7081        assert_eq!(e.buffer().lines()[0], " world");
7082    }
7083
7084    #[test]
7085    fn delete_char_forward_noop_on_empty_line() {
7086        let mut e = normal_editor("");
7087        let before = e.content().to_string();
7088        e.delete_char_forward(1);
7089        // Empty buffer: no chars to delete, content unchanged.
7090        assert_eq!(e.content(), before.as_str());
7091    }
7092
7093    #[test]
7094    fn delete_char_backward_removes_char_before_cursor() {
7095        let mut e = normal_editor("hello");
7096        e.jump_cursor(0, 3);
7097        e.delete_char_backward(1);
7098        assert_eq!(e.buffer().lines()[0], "helo");
7099    }
7100
7101    #[test]
7102    fn delete_char_backward_noop_at_col_0() {
7103        let mut e = normal_editor("hello");
7104        e.jump_cursor(0, 0);
7105        e.delete_char_backward(1);
7106        assert_eq!(e.buffer().lines()[0], "hello");
7107    }
7108
7109    #[test]
7110    fn substitute_char_deletes_and_enters_insert() {
7111        let mut e = normal_editor("hello");
7112        e.jump_cursor(0, 0);
7113        e.substitute_char(1);
7114        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7115        assert_eq!(e.buffer().lines()[0], "ello");
7116    }
7117
7118    #[test]
7119    fn substitute_char_count_3_deletes_three() {
7120        let mut e = normal_editor("hello");
7121        e.substitute_char(3);
7122        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7123        assert_eq!(e.buffer().lines()[0], "lo");
7124    }
7125
7126    #[test]
7127    fn substitute_line_clears_content_and_enters_insert() {
7128        let mut e = normal_editor("hello world");
7129        e.substitute_line(1);
7130        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7131        assert_eq!(e.buffer().lines()[0], "");
7132    }
7133
7134    #[test]
7135    fn delete_to_eol_removes_from_cursor_to_end() {
7136        let mut e = normal_editor("hello world");
7137        e.jump_cursor(0, 5);
7138        e.delete_to_eol();
7139        // col 5 is ' ' — deletes " world", leaving "hello".
7140        assert_eq!(e.buffer().lines()[0], "hello");
7141    }
7142
7143    #[test]
7144    fn delete_to_eol_noop_when_cursor_past_end() {
7145        let mut e = normal_editor("hi");
7146        e.jump_cursor(0, 2);
7147        e.delete_to_eol();
7148        assert_eq!(e.buffer().lines()[0], "hi");
7149    }
7150
7151    #[test]
7152    fn change_to_eol_enters_insert() {
7153        let mut e = normal_editor("hello world");
7154        e.jump_cursor(0, 5);
7155        e.change_to_eol();
7156        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7157        // col 5 is ' ' — deletes " world", leaving "hello".
7158        assert_eq!(e.buffer().lines()[0], "hello");
7159    }
7160
7161    #[test]
7162    fn yank_to_eol_fills_register() {
7163        let mut e = normal_editor("hello world");
7164        e.jump_cursor(0, 6);
7165        e.yank_to_eol(1);
7166        // Yank does not change mode.
7167        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
7168        // Unnamed register holds the yanked text (col 6 is 'w' in "world").
7169        assert!(
7170            e.registers().unnamed.text.starts_with("world")
7171                || e.registers().unnamed.text.contains("world")
7172        );
7173    }
7174
7175    #[test]
7176    fn join_line_merges_next_line_with_space() {
7177        let mut e = normal_editor("foo\nbar");
7178        e.join_line(1);
7179        assert_eq!(e.buffer().lines()[0], "foo bar");
7180    }
7181
7182    #[test]
7183    fn join_line_count_2_merges_three_lines() {
7184        let mut e = normal_editor("a\nb\nc");
7185        e.join_line(2);
7186        // Our bridge calls join_line() `count` times, each joining the
7187        // current line with the next → 2 iterations: "a b c".
7188        assert_eq!(e.buffer().lines()[0], "a b c");
7189    }
7190
7191    #[test]
7192    fn join_line_noop_on_last_line() {
7193        let mut e = normal_editor("only");
7194        e.join_line(1);
7195        assert_eq!(e.buffer().lines()[0], "only");
7196    }
7197
7198    #[test]
7199    fn toggle_case_at_cursor_flips_letter() {
7200        let mut e = normal_editor("hello");
7201        e.toggle_case_at_cursor(1);
7202        assert_eq!(e.buffer().lines()[0], "Hello");
7203    }
7204
7205    #[test]
7206    fn toggle_case_at_cursor_count_3_flips_three() {
7207        let mut e = normal_editor("hello");
7208        e.toggle_case_at_cursor(3);
7209        assert_eq!(e.buffer().lines()[0], "HELlo");
7210    }
7211
7212    // ── Undo / redo round-trip ───────────────────────────────────────────────
7213
7214    #[test]
7215    fn undo_redo_roundtrip_via_public_methods() {
7216        let mut e = normal_editor("hello");
7217        e.delete_char_forward(1);
7218        assert_eq!(e.buffer().lines()[0], "ello");
7219        e.undo();
7220        assert_eq!(e.buffer().lines()[0], "hello");
7221        e.redo();
7222        assert_eq!(e.buffer().lines()[0], "ello");
7223    }
7224
7225    // ── Jump / scroll ────────────────────────────────────────────────────────
7226
7227    #[test]
7228    fn jump_back_and_forward_roundtrip() {
7229        let mut e = fresh_editor("a\nb\nc\nd");
7230        e.set_viewport_height(10);
7231        e.jump_cursor(3, 0);
7232        // Push current pos onto jumplist (big motion done externally; use
7233        // `run_keys` shortcut: `gg` pushes jump then `G` jumps).
7234        // Simpler: just call jump_back with empty stack → no-op (shouldn't panic).
7235        e.jump_back(1);
7236        e.jump_forward(1);
7237    }
7238
7239    #[test]
7240    fn scroll_full_page_down_moves_cursor() {
7241        use crate::vim::ScrollDir;
7242        let lines = (0..30)
7243            .map(|i| format!("line{i}"))
7244            .collect::<Vec<_>>()
7245            .join("\n");
7246        let mut e = fresh_editor(&lines);
7247        e.set_viewport_height(10);
7248        let before = e.cursor().0;
7249        e.scroll_full_page(ScrollDir::Down, 1);
7250        assert!(e.cursor().0 > before);
7251    }
7252
7253    #[test]
7254    fn scroll_full_page_up_moves_cursor() {
7255        use crate::vim::ScrollDir;
7256        let lines = (0..30)
7257            .map(|i| format!("line{i}"))
7258            .collect::<Vec<_>>()
7259            .join("\n");
7260        let mut e = fresh_editor(&lines);
7261        e.set_viewport_height(10);
7262        e.jump_cursor(25, 0);
7263        let before = e.cursor().0;
7264        e.scroll_full_page(ScrollDir::Up, 1);
7265        assert!(e.cursor().0 < before);
7266    }
7267
7268    #[test]
7269    fn scroll_half_page_down_moves_cursor() {
7270        use crate::vim::ScrollDir;
7271        let lines = (0..30)
7272            .map(|i| format!("line{i}"))
7273            .collect::<Vec<_>>()
7274            .join("\n");
7275        let mut e = fresh_editor(&lines);
7276        e.set_viewport_height(10);
7277        let before = e.cursor().0;
7278        e.scroll_half_page(ScrollDir::Down, 1);
7279        assert!(e.cursor().0 > before);
7280    }
7281
7282    #[test]
7283    fn scroll_half_page_up_at_top_is_noop() {
7284        use crate::vim::ScrollDir;
7285        let lines = (0..30)
7286            .map(|i| format!("line{i}"))
7287            .collect::<Vec<_>>()
7288            .join("\n");
7289        let mut e = fresh_editor(&lines);
7290        e.set_viewport_height(10);
7291        // Already at top, scrolling up should not panic and cursor stays at 0.
7292        e.scroll_half_page(ScrollDir::Up, 1);
7293        assert_eq!(e.cursor().0, 0);
7294    }
7295
7296    #[test]
7297    fn scroll_line_down_shifts_viewport_without_moving_cursor() {
7298        use crate::vim::ScrollDir;
7299        let lines = (0..30)
7300            .map(|i| format!("line{i}"))
7301            .collect::<Vec<_>>()
7302            .join("\n");
7303        let mut e = fresh_editor(&lines);
7304        e.set_viewport_height(10);
7305        // Park cursor in the middle of a large buffer.
7306        e.jump_cursor(15, 0);
7307        e.set_viewport_top(10);
7308        let cursor_before = e.cursor().0;
7309        e.scroll_line(ScrollDir::Down, 1);
7310        // Viewport top advances; cursor stays.
7311        assert_eq!(e.cursor().0, cursor_before);
7312        assert_eq!(e.host().viewport().top_row, 11);
7313    }
7314
7315    #[test]
7316    fn scroll_line_up_shifts_viewport() {
7317        use crate::vim::ScrollDir;
7318        let lines = (0..30)
7319            .map(|i| format!("line{i}"))
7320            .collect::<Vec<_>>()
7321            .join("\n");
7322        let mut e = fresh_editor(&lines);
7323        e.set_viewport_height(10);
7324        e.jump_cursor(15, 0);
7325        e.set_viewport_top(10);
7326        let cursor_before = e.cursor().0;
7327        e.scroll_line(ScrollDir::Up, 1);
7328        assert_eq!(e.cursor().0, cursor_before);
7329        assert_eq!(e.host().viewport().top_row, 9);
7330    }
7331
7332    #[test]
7333    fn scroll_line_clamps_cursor_when_off_screen() {
7334        use crate::vim::ScrollDir;
7335        let lines = (0..30)
7336            .map(|i| format!("line{i}"))
7337            .collect::<Vec<_>>()
7338            .join("\n");
7339        let mut e = fresh_editor(&lines);
7340        e.set_viewport_height(10);
7341        // Cursor at viewport top; scrolling down pushes it off — must clamp.
7342        e.jump_cursor(5, 0);
7343        e.set_viewport_top(5);
7344        e.scroll_line(ScrollDir::Down, 3);
7345        // New top = 8; cursor was at 5, which is now off-screen (< 8).
7346        // Cursor clamped to new top.
7347        assert!(e.cursor().0 >= 8);
7348    }
7349
7350    #[test]
7351    fn scroll_doesnt_crash_at_buffer_edges() {
7352        use crate::vim::ScrollDir;
7353        let mut e = normal_editor("single line");
7354        e.set_viewport_height(10);
7355        // Should not panic on any of these at-the-edge scrolls.
7356        e.scroll_full_page(ScrollDir::Down, 99);
7357        e.scroll_full_page(ScrollDir::Up, 99);
7358        e.scroll_half_page(ScrollDir::Down, 99);
7359        e.scroll_half_page(ScrollDir::Up, 99);
7360        e.scroll_line(ScrollDir::Down, 99);
7361        e.scroll_line(ScrollDir::Up, 99);
7362    }
7363
7364    // ── Horizontal scroll ────────────────────────────────────────────────────
7365
7366    #[test]
7367    fn scroll_right_advances_top_col() {
7368        let mut e = fresh_editor("hello world");
7369        e.set_viewport_height(10);
7370        e.scroll_right(5);
7371        assert_eq!(e.host().viewport().top_col, 5);
7372    }
7373
7374    #[test]
7375    fn scroll_left_does_not_underflow() {
7376        let mut e = fresh_editor("hello world");
7377        e.set_viewport_height(10);
7378        e.scroll_right(2);
7379        e.scroll_left(10);
7380        assert_eq!(e.host().viewport().top_col, 0);
7381    }
7382
7383    #[test]
7384    fn scroll_left_then_right_roundtrip() {
7385        let mut e = fresh_editor("hello world");
7386        e.set_viewport_height(10);
7387        e.scroll_right(10);
7388        e.scroll_left(3);
7389        assert_eq!(e.host().viewport().top_col, 7);
7390    }
7391
7392    // ── Search ───────────────────────────────────────────────────────────────
7393
7394    #[test]
7395    fn search_repeat_advances_to_next_match() {
7396        let mut e = fresh_editor("foo bar foo baz");
7397        // Use word_search to seed the search state (no search prompt needed).
7398        // `*` on "foo" at col 0 finds the second "foo" and sets last_search.
7399        e.word_search(true, true, 1);
7400        // Repeating forward wraps and finds the first "foo" again at col 0.
7401        e.search_repeat(true, 1);
7402        // Just ensure no panic and search state is valid.
7403        assert!(e.cursor().0 < e.buffer().lines().len());
7404    }
7405
7406    #[test]
7407    fn search_repeat_no_pattern_is_noop() {
7408        let mut e = normal_editor("hello world");
7409        let before = e.cursor();
7410        // No search pattern loaded — should not panic.
7411        e.search_repeat(true, 1);
7412        assert_eq!(e.cursor(), before);
7413    }
7414
7415    #[test]
7416    fn word_search_finds_word_under_cursor() {
7417        let mut e = fresh_editor("foo bar foo");
7418        // cursor starts at col 0 on "foo"
7419        e.word_search(true, true, 1);
7420        // Should jump to the second "foo" at col 8.
7421        assert_eq!(e.cursor().1, 8);
7422    }
7423
7424    #[test]
7425    fn word_search_whole_word_false_extracts_word_under_cursor() {
7426        // `g*` on "foo" (no `\b`) — use two lines so wrap can find the next match.
7427        let mut e = fresh_editor("foobar\nfoo baz");
7428        // Cursor on second line "foo" at col 0.
7429        e.jump_cursor(1, 0);
7430        // g* with whole_word=false: pattern = "foo", advance forward (skip current).
7431        // Starting at (1, 0), skip "foo" at (1,0), wrap to (0, 0) which matches "foo"
7432        // inside "foobar".
7433        e.word_search(true, false, 1);
7434        // Cursor should land on "foo" at row 0, col 0.
7435        assert_eq!(e.cursor(), (0, 0));
7436    }
7437
7438    #[test]
7439    fn word_search_backward_finds_previous_match() {
7440        let mut e = fresh_editor("foo bar foo");
7441        e.jump_cursor(0, 8); // on second "foo"
7442        e.word_search(false, true, 1);
7443        // Cursor should land on col 0 (first "foo").
7444        assert_eq!(e.cursor().1, 0);
7445    }
7446
7447    // ── Edge cases ───────────────────────────────────────────────────────────
7448
7449    #[test]
7450    fn delete_char_forward_on_single_char_line() {
7451        let mut e = normal_editor("x");
7452        e.delete_char_forward(1);
7453        assert_eq!(e.buffer().lines()[0], "");
7454    }
7455
7456    #[test]
7457    fn substitute_char_on_empty_line_is_noop_for_delete() {
7458        let mut e = normal_editor("");
7459        e.substitute_char(1);
7460        // Nothing to delete — but should enter Insert mode.
7461        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7462    }
7463
7464    #[test]
7465    fn join_line_10_iterations_clamps_gracefully() {
7466        let mut e = normal_editor("a\nb");
7467        // Joining 10 times on a 2-line buffer should not panic.
7468        e.join_line(10);
7469        // After the first join succeeds, the rest are no-ops.
7470        assert_eq!(e.buffer().lines()[0], "a b");
7471    }
7472
7473    #[test]
7474    fn toggle_case_past_line_end_is_noop() {
7475        let mut e = normal_editor("ab");
7476        e.jump_cursor(0, 5); // way past end
7477        e.toggle_case_at_cursor(1);
7478        // Should not panic.
7479        assert_eq!(e.buffer().lines()[0], "ab");
7480    }
7481
7482    // ── Phase 6.3: visual-mode primitive tests (kryptic-sh/hjkl#89) ──────────
7483
7484    // ── Visual entry ─────────────────────────────────────────────────────────
7485
7486    #[test]
7487    fn enter_visual_char_lands_in_visual_at_cursor() {
7488        let mut e = normal_editor("hello world");
7489        e.jump_cursor(0, 3);
7490        e.enter_visual_char();
7491        assert_eq!(e.vim_mode(), crate::VimMode::Visual);
7492        // Anchor should be at the cursor position we entered from.
7493        assert_eq!(e.vim.visual_anchor, (0, 3));
7494    }
7495
7496    #[test]
7497    fn enter_visual_line_lands_in_visual_line() {
7498        let mut e = normal_editor("hello\nworld");
7499        e.jump_cursor(1, 2);
7500        e.enter_visual_line();
7501        assert_eq!(e.vim_mode(), crate::VimMode::VisualLine);
7502        // Line anchor should be the current row.
7503        assert_eq!(e.vim.visual_line_anchor, 1);
7504    }
7505
7506    #[test]
7507    fn enter_visual_block_lands_in_visual_block() {
7508        let mut e = normal_editor("hello\nworld");
7509        e.jump_cursor(0, 2);
7510        e.enter_visual_block();
7511        assert_eq!(e.vim_mode(), crate::VimMode::VisualBlock);
7512        // Block anchor and vcol should match the cursor column.
7513        assert_eq!(e.vim.block_anchor, (0, 2));
7514        assert_eq!(e.vim.block_vcol, 2);
7515    }
7516
7517    // ── Visual exit ──────────────────────────────────────────────────────────
7518
7519    #[test]
7520    fn exit_visual_to_normal_sets_marks_and_returns_to_normal() {
7521        let mut e = normal_editor("hello world");
7522        // Enter charwise visual at col 2, extend to col 5.
7523        e.jump_cursor(0, 2);
7524        e.enter_visual_char();
7525        e.jump_cursor(0, 5);
7526        e.exit_visual_to_normal();
7527        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
7528        // `<` = (0, 2), `>` = (0, 5).
7529        assert_eq!(e.mark('<'), Some((0, 2)));
7530        assert_eq!(e.mark('>'), Some((0, 5)));
7531    }
7532
7533    #[test]
7534    fn exit_visual_to_normal_stores_last_visual() {
7535        let mut e = normal_editor("hello world");
7536        e.jump_cursor(0, 1);
7537        e.enter_visual_char();
7538        e.jump_cursor(0, 4);
7539        e.exit_visual_to_normal();
7540        // last_visual should be set so gv can restore it.
7541        assert!(e.vim.last_visual.is_some());
7542        let lv = e.vim.last_visual.unwrap();
7543        assert_eq!(lv.anchor, (0, 1));
7544        assert_eq!(lv.cursor, (0, 4));
7545    }
7546
7547    #[test]
7548    fn exit_visual_line_sets_marks_at_line_boundaries() {
7549        let mut e = normal_editor("alpha\nbeta\ngamma");
7550        e.enter_visual_line(); // row 0
7551        e.jump_cursor(1, 3);
7552        e.exit_visual_to_normal();
7553        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
7554        // `<` snaps to (min_row, 0), `>` snaps to (max_row, last_col).
7555        assert_eq!(e.mark('<'), Some((0, 0)));
7556        let last_col_of_beta = "beta".chars().count() - 1;
7557        assert_eq!(e.mark('>'), Some((1, last_col_of_beta)));
7558    }
7559
7560    // ── visual_o_toggle ───────────────────────────────────────────────────────
7561
7562    #[test]
7563    fn visual_o_toggle_swaps_anchor_and_cursor_charwise() {
7564        let mut e = normal_editor("hello world");
7565        // Enter visual at col 0, extend to col 4.
7566        e.enter_visual_char(); // anchor = (0,0)
7567        e.jump_cursor(0, 4); // cursor at col 4
7568        // Selection bounds before toggle: anchor=0, cursor=4.
7569        let pre_anchor = e.vim.visual_anchor;
7570        let pre_cursor = e.cursor();
7571        e.visual_o_toggle();
7572        // After toggle: cursor jumps to old anchor, anchor = old cursor.
7573        assert_eq!(e.cursor(), pre_anchor, "cursor should move to old anchor");
7574        assert_eq!(
7575            e.vim.visual_anchor, pre_cursor,
7576            "anchor should take old cursor position"
7577        );
7578        // Mode is unchanged.
7579        assert_eq!(e.vim_mode(), crate::VimMode::Visual);
7580    }
7581
7582    #[test]
7583    fn visual_o_toggle_double_returns_to_start() {
7584        let mut e = normal_editor("hello world");
7585        e.enter_visual_char();
7586        e.jump_cursor(0, 4);
7587        let anchor0 = e.vim.visual_anchor;
7588        let cursor0 = e.cursor();
7589        e.visual_o_toggle();
7590        e.visual_o_toggle();
7591        // Two toggles restore original positions.
7592        assert_eq!(e.vim.visual_anchor, anchor0);
7593        assert_eq!(e.cursor(), cursor0);
7594    }
7595
7596    #[test]
7597    fn visual_o_toggle_linewise_swaps_anchor_row() {
7598        let mut e = normal_editor("alpha\nbeta\ngamma");
7599        e.enter_visual_line(); // anchor row = 0
7600        e.jump_cursor(2, 0); // cursor on row 2
7601        e.visual_o_toggle();
7602        // Cursor should jump to old anchor row.
7603        assert_eq!(e.cursor().0, 0, "cursor row should be old anchor row");
7604        // Anchor row should now be the old cursor row.
7605        assert_eq!(e.vim.visual_line_anchor, 2);
7606    }
7607
7608    // ── reenter_last_visual ───────────────────────────────────────────────────
7609
7610    #[test]
7611    fn reenter_last_visual_after_vdollar_esc_restores() {
7612        let mut e = normal_editor("hello world");
7613        // v$ then Esc via FSM to store a real last_visual.
7614        e.enter_visual_char(); // anchor = (0,0)
7615        e.jump_cursor(0, 5); // move cursor to col 5 to create a range
7616        e.exit_visual_to_normal();
7617        // Should be back to Normal.
7618        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
7619        // gv — should restore Visual mode.
7620        e.reenter_last_visual();
7621        assert_eq!(e.vim_mode(), crate::VimMode::Visual);
7622        // Cursor should be at the stored last position (col 5).
7623        assert_eq!(e.cursor().1, 5);
7624    }
7625
7626    #[test]
7627    fn reenter_last_visual_noop_when_no_history() {
7628        let mut e = normal_editor("hello");
7629        // No prior visual — should be a no-op, not a panic.
7630        e.reenter_last_visual();
7631        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
7632    }
7633
7634    // ── set_mode ─────────────────────────────────────────────────────────────
7635
7636    #[test]
7637    fn set_mode_insert_flips_vim_mode_to_insert() {
7638        let mut e = normal_editor("hello");
7639        e.set_mode(crate::VimMode::Insert);
7640        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7641    }
7642
7643    #[test]
7644    fn set_mode_roundtrip_normal_insert_normal() {
7645        let mut e = normal_editor("hello");
7646        e.set_mode(crate::VimMode::Insert);
7647        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7648        e.set_mode(crate::VimMode::Normal);
7649        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
7650    }
7651
7652    #[test]
7653    fn set_mode_visual_variants() {
7654        let mut e = normal_editor("hello");
7655        e.set_mode(crate::VimMode::Visual);
7656        assert_eq!(e.vim_mode(), crate::VimMode::Visual);
7657        e.set_mode(crate::VimMode::VisualLine);
7658        assert_eq!(e.vim_mode(), crate::VimMode::VisualLine);
7659        e.set_mode(crate::VimMode::VisualBlock);
7660        assert_eq!(e.vim_mode(), crate::VimMode::VisualBlock);
7661        e.set_mode(crate::VimMode::Normal);
7662        assert_eq!(e.vim_mode(), crate::VimMode::Normal);
7663    }
7664
7665    // ── current_mode / vim_mode consistency ───────────────────────────────────
7666
7667    // ── Phase 6.6b: FSM state accessor smoke tests ────────────────────────────
7668
7669    #[test]
7670    fn pending_round_trips() {
7671        let mut e = normal_editor("hello");
7672        assert!(matches!(e.pending(), crate::vim::Pending::None));
7673        e.set_pending(crate::vim::Pending::G);
7674        assert!(matches!(e.pending(), crate::vim::Pending::G));
7675        let taken = e.take_pending();
7676        assert!(matches!(taken, crate::vim::Pending::G));
7677        assert!(matches!(e.pending(), crate::vim::Pending::None));
7678    }
7679
7680    #[test]
7681    fn count_round_trips() {
7682        let mut e = normal_editor("hello");
7683        assert_eq!(e.count(), 0);
7684        e.set_count(5);
7685        assert_eq!(e.count(), 5);
7686        e.accumulate_count_digit(3);
7687        assert_eq!(e.count(), 53);
7688        e.reset_count();
7689        assert_eq!(e.count(), 0);
7690    }
7691
7692    #[test]
7693    fn take_count_returns_one_when_zero() {
7694        let mut e = normal_editor("hello");
7695        assert_eq!(e.take_count(), 1);
7696    }
7697
7698    #[test]
7699    fn take_count_returns_value_and_resets() {
7700        let mut e = normal_editor("hello");
7701        e.set_count(7);
7702        assert_eq!(e.take_count(), 7);
7703        assert_eq!(e.count(), 0);
7704    }
7705
7706    #[test]
7707    fn fsm_mode_round_trips() {
7708        let mut e = normal_editor("hello");
7709        assert_eq!(e.fsm_mode(), crate::vim::Mode::Normal);
7710        e.set_fsm_mode(crate::vim::Mode::Insert);
7711        assert_eq!(e.fsm_mode(), crate::vim::Mode::Insert);
7712        assert_eq!(e.vim_mode(), crate::VimMode::Insert);
7713        e.set_fsm_mode(crate::vim::Mode::Normal);
7714        assert_eq!(e.fsm_mode(), crate::vim::Mode::Normal);
7715    }
7716
7717    #[test]
7718    fn replaying_flag_round_trips() {
7719        let mut e = normal_editor("hello");
7720        assert!(!e.is_replaying());
7721        e.set_replaying(true);
7722        assert!(e.is_replaying());
7723        e.set_replaying(false);
7724        assert!(!e.is_replaying());
7725    }
7726
7727    #[test]
7728    fn one_shot_normal_flag_round_trips() {
7729        let mut e = normal_editor("hello");
7730        assert!(!e.is_one_shot_normal());
7731        e.set_one_shot_normal(true);
7732        assert!(e.is_one_shot_normal());
7733        e.set_one_shot_normal(false);
7734        assert!(!e.is_one_shot_normal());
7735    }
7736
7737    #[test]
7738    fn last_find_round_trips() {
7739        let mut e = normal_editor("hello");
7740        assert_eq!(e.last_find(), None);
7741        e.set_last_find(Some(('x', true, false)));
7742        assert_eq!(e.last_find(), Some(('x', true, false)));
7743        e.set_last_find(None);
7744        assert_eq!(e.last_find(), None);
7745    }
7746
7747    #[test]
7748    fn last_change_round_trips() {
7749        let mut e = normal_editor("hello");
7750        assert!(e.last_change().is_none());
7751        e.set_last_change(Some(crate::vim::LastChange::ToggleCase { count: 2 }));
7752        let lc = e.last_change();
7753        assert!(matches!(
7754            lc,
7755            Some(crate::vim::LastChange::ToggleCase { count: 2 })
7756        ));
7757        e.set_last_change(None);
7758        assert!(e.last_change().is_none());
7759    }
7760
7761    #[test]
7762    fn last_change_mut_allows_in_place_edit() {
7763        let mut e = normal_editor("hello");
7764        e.set_last_change(Some(crate::vim::LastChange::ToggleCase { count: 1 }));
7765        if let Some(crate::vim::LastChange::ToggleCase { count }) = e.last_change_mut() {
7766            *count = 42;
7767        }
7768        assert!(matches!(
7769            e.last_change(),
7770            Some(crate::vim::LastChange::ToggleCase { count: 42 })
7771        ));
7772    }
7773
7774    #[test]
7775    fn insert_session_round_trips() {
7776        let mut e = normal_editor("hello");
7777        assert!(e.insert_session().is_none());
7778        e.set_insert_session(Some(crate::vim::InsertSession {
7779            count: 3,
7780            row_min: 0,
7781            row_max: 0,
7782            before_lines: vec!["hello".to_string()],
7783            reason: crate::vim::InsertReason::Enter(crate::vim::InsertEntry::I),
7784        }));
7785        assert_eq!(e.insert_session().map(|s| s.count), Some(3));
7786        let taken = e.take_insert_session();
7787        assert!(taken.is_some());
7788        assert!(e.insert_session().is_none());
7789    }
7790
7791    #[test]
7792    fn visual_anchor_round_trips() {
7793        let mut e = normal_editor("hello");
7794        e.set_visual_anchor((1, 3));
7795        assert_eq!(e.visual_anchor(), (1, 3));
7796    }
7797
7798    #[test]
7799    fn visual_line_anchor_round_trips() {
7800        let mut e = normal_editor("hello\nworld");
7801        e.set_visual_line_anchor(1);
7802        assert_eq!(e.visual_line_anchor(), 1);
7803    }
7804
7805    #[test]
7806    fn block_anchor_and_vcol_round_trip() {
7807        let mut e = normal_editor("hello");
7808        e.set_block_anchor((0, 2));
7809        e.set_block_vcol(4);
7810        assert_eq!(e.block_anchor(), (0, 2));
7811        assert_eq!(e.block_vcol(), 4);
7812    }
7813
7814    #[test]
7815    fn yank_linewise_round_trips() {
7816        let mut e = normal_editor("hello");
7817        assert!(!e.yank_linewise());
7818        e.set_yank_linewise(true);
7819        assert!(e.yank_linewise());
7820    }
7821
7822    #[test]
7823    fn pending_register_raw_round_trips() {
7824        let mut e = normal_editor("hello");
7825        assert_eq!(e.pending_register(), None);
7826        e.set_pending_register_raw(Some('a'));
7827        assert_eq!(e.pending_register(), Some('a'));
7828        let taken = e.take_pending_register_raw();
7829        assert_eq!(taken, Some('a'));
7830        assert_eq!(e.pending_register(), None);
7831    }
7832
7833    #[test]
7834    fn recording_macro_round_trips() {
7835        let mut e = normal_editor("hello");
7836        assert_eq!(e.recording_macro(), None);
7837        e.set_recording_macro(Some('q'));
7838        assert_eq!(e.recording_macro(), Some('q'));
7839        e.set_recording_macro(None);
7840        assert_eq!(e.recording_macro(), None);
7841    }
7842
7843    #[test]
7844    fn recording_keys_round_trips() {
7845        let mut e = normal_editor("hello");
7846        let input = crate::Input {
7847            key: crate::Key::Char('j'),
7848            ctrl: false,
7849            alt: false,
7850            shift: false,
7851        };
7852        e.push_recording_key(input);
7853        assert_eq!(e.take_recording_keys(), vec![input]);
7854        assert!(e.take_recording_keys().is_empty());
7855    }
7856
7857    #[test]
7858    fn replaying_macro_raw_round_trips() {
7859        let mut e = normal_editor("hello");
7860        assert!(!e.is_replaying_macro_raw());
7861        e.set_replaying_macro_raw(true);
7862        assert!(e.is_replaying_macro_raw());
7863        e.set_replaying_macro_raw(false);
7864        assert!(!e.is_replaying_macro_raw());
7865    }
7866
7867    #[test]
7868    fn last_macro_round_trips() {
7869        let mut e = normal_editor("hello");
7870        assert_eq!(e.last_macro(), None);
7871        e.set_last_macro(Some('m'));
7872        assert_eq!(e.last_macro(), Some('m'));
7873    }
7874
7875    #[test]
7876    fn last_insert_pos_round_trips() {
7877        let mut e = normal_editor("hello");
7878        assert_eq!(e.last_insert_pos(), None);
7879        e.set_last_insert_pos(Some((1, 2)));
7880        assert_eq!(e.last_insert_pos(), Some((1, 2)));
7881    }
7882
7883    #[test]
7884    fn last_visual_round_trips() {
7885        let mut e = normal_editor("hello");
7886        assert!(e.last_visual().is_none());
7887        let snap = crate::vim::LastVisual {
7888            mode: crate::vim::Mode::Visual,
7889            anchor: (0, 0),
7890            cursor: (0, 3),
7891            block_vcol: 0,
7892        };
7893        e.set_last_visual(Some(snap));
7894        assert!(e.last_visual().is_some());
7895        e.set_last_visual(None);
7896        assert!(e.last_visual().is_none());
7897    }
7898
7899    #[test]
7900    fn viewport_pinned_round_trips() {
7901        let mut e = normal_editor("hello");
7902        assert!(!e.viewport_pinned());
7903        e.set_viewport_pinned(true);
7904        assert!(e.viewport_pinned());
7905        e.set_viewport_pinned(false);
7906        assert!(!e.viewport_pinned());
7907    }
7908
7909    #[test]
7910    fn insert_pending_register_round_trips() {
7911        let mut e = normal_editor("hello");
7912        assert!(!e.insert_pending_register());
7913        e.set_insert_pending_register(true);
7914        assert!(e.insert_pending_register());
7915    }
7916
7917    #[test]
7918    fn change_mark_start_round_trips() {
7919        let mut e = normal_editor("hello");
7920        assert_eq!(e.change_mark_start(), None);
7921        e.set_change_mark_start(Some((2, 5)));
7922        assert_eq!(e.change_mark_start(), Some((2, 5)));
7923        let taken = e.take_change_mark_start();
7924        assert_eq!(taken, Some((2, 5)));
7925        assert_eq!(e.change_mark_start(), None);
7926    }
7927
7928    #[test]
7929    fn search_prompt_state_round_trips() {
7930        let mut e = normal_editor("hello");
7931        assert!(e.search_prompt_state().is_none());
7932        e.set_search_prompt_state(Some(crate::vim::SearchPrompt {
7933            text: "foo".to_string(),
7934            cursor: 3,
7935            forward: true,
7936        }));
7937        assert_eq!(
7938            e.search_prompt_state().map(|p| p.text.as_str()),
7939            Some("foo")
7940        );
7941        let taken = e.take_search_prompt_state();
7942        assert!(taken.is_some());
7943        assert!(e.search_prompt_state().is_none());
7944    }
7945
7946    #[test]
7947    fn last_search_pattern_and_direction_round_trips() {
7948        let mut e = normal_editor("hello");
7949        assert_eq!(e.last_search_pattern(), None);
7950        e.set_last_search_pattern_only(Some("world".to_string()));
7951        assert_eq!(e.last_search_pattern(), Some("world"));
7952        e.set_last_search_forward_only(false);
7953        assert!(!e.last_search_forward());
7954    }
7955
7956    #[test]
7957    fn search_history_round_trips() {
7958        let mut e = normal_editor("hello");
7959        assert!(e.search_history().is_empty());
7960        e.search_history_mut().push("pattern1".to_string());
7961        assert_eq!(e.search_history(), &["pattern1"]);
7962        e.set_search_history_cursor(Some(0));
7963        assert_eq!(e.search_history_cursor(), Some(0));
7964        e.set_search_history_cursor(None);
7965        assert_eq!(e.search_history_cursor(), None);
7966    }
7967
7968    #[test]
7969    fn jump_lists_round_trips() {
7970        let mut e = normal_editor("hello");
7971        assert!(e.jump_back_list().is_empty());
7972        assert!(e.jump_fwd_list().is_empty());
7973        e.jump_back_list_mut().push((1, 2));
7974        e.jump_fwd_list_mut().push((3, 4));
7975        assert_eq!(e.jump_back_list(), &[(1, 2)]);
7976        assert_eq!(e.jump_fwd_list(), &[(3, 4)]);
7977    }
7978
7979    #[test]
7980    fn last_input_timing_round_trips() {
7981        let mut e = normal_editor("hello");
7982        assert!(e.last_input_at().is_none());
7983        assert!(e.last_input_host_at().is_none());
7984        let now = std::time::Instant::now();
7985        e.set_last_input_at(Some(now));
7986        assert!(e.last_input_at().is_some());
7987        let dur = core::time::Duration::from_millis(100);
7988        e.set_last_input_host_at(Some(dur));
7989        assert_eq!(e.last_input_host_at(), Some(dur));
7990    }
7991
7992    // ── auto_indent_range tests ──────────────────────────────────────────────
7993
7994    /// Helper: build an editor with `expandtab=true` and the given shiftwidth.
7995    fn indent_editor(initial: &str, shiftwidth: usize, expandtab: bool) -> Editor {
7996        let mut e = fresh_editor(initial);
7997        e.settings_mut().shiftwidth = shiftwidth;
7998        e.settings_mut().expandtab = expandtab;
7999        e
8000    }
8001
8002    #[test]
8003    fn auto_indent_single_line_under_open_brace() {
8004        // `{\nfoo\n}` — "foo" is at depth 1 under the `{`.
8005        // With shiftwidth=4 expandtab=true it should become "    foo".
8006        let mut e = indent_editor("{\nfoo\n}", 4, true);
8007        // auto-indent only row 1 ("foo").
8008        e.auto_indent_range((1, 0), (1, 0));
8009        let lines = e.buffer().lines();
8010        assert_eq!(lines[1], "    foo", "foo should be indented by 4 spaces");
8011    }
8012
8013    #[test]
8014    fn auto_indent_close_brace_outdents() {
8015        // `{\n    inner\n}` — the `}` is at depth 1 but starts with a close
8016        // bracket so effective_depth = 0.
8017        let mut e = indent_editor("{\n    inner\n}", 4, true);
8018        e.auto_indent_range((2, 0), (2, 0));
8019        let lines = e.buffer().lines();
8020        assert_eq!(lines[2], "}", "`}}` should have zero indent");
8021    }
8022
8023    #[test]
8024    fn auto_indent_whole_buffer_normalizes_mixed_indent() {
8025        // Mixed-indent input: first line un-indented `{`, second line 1-tab
8026        // indented body, third line un-indented `}`.
8027        let src = "{\n\tbody\n}";
8028        let mut e = indent_editor(src, 4, true);
8029        let total = e.buffer().lines().len();
8030        e.auto_indent_range((0, 0), (total - 1, 0));
8031        let lines = e.buffer().lines();
8032        // `{` — depth 0 at start.
8033        assert_eq!(lines[0], "{");
8034        // `body` — depth 1 after `{`.
8035        assert_eq!(lines[1], "    body");
8036        // `}` — depth 1 but starts with close → effective_depth 0.
8037        assert_eq!(lines[2], "}");
8038    }
8039
8040    #[test]
8041    fn auto_indent_respects_expandtab_false_uses_tabs() {
8042        // Same buffer, but expandtab=false → indent unit is `\t`.
8043        let src = "{\nbody\n}";
8044        let mut e = indent_editor(src, 4, false);
8045        let total = e.buffer().lines().len();
8046        e.auto_indent_range((0, 0), (total - 1, 0));
8047        let lines = e.buffer().lines();
8048        assert_eq!(lines[0], "{");
8049        assert_eq!(lines[1], "\tbody");
8050        assert_eq!(lines[2], "}");
8051    }
8052
8053    #[test]
8054    fn auto_indent_empty_line_stays_empty() {
8055        // `{\n\nfoo\n}` — blank line in the middle should stay blank.
8056        let src = "{\n\nfoo\n}";
8057        let mut e = indent_editor(src, 4, true);
8058        let total = e.buffer().lines().len();
8059        e.auto_indent_range((0, 0), (total - 1, 0));
8060        let lines = e.buffer().lines();
8061        assert_eq!(lines[1], "", "blank line should stay blank");
8062        assert_eq!(lines[2], "    foo");
8063    }
8064
8065    #[test]
8066    fn auto_indent_cursor_lands_on_first_nonws_of_start_row() {
8067        // After `==` / `auto_indent_range` the cursor should be at the first
8068        // non-whitespace character of start_row (vim parity).
8069        let src = "{\nfoo\n}";
8070        let mut e = indent_editor(src, 4, true);
8071        // Reindent only row 1.
8072        e.auto_indent_range((1, 0), (1, 0));
8073        // Row 1 after reindent is "    foo"; first non-ws is col 4.
8074        let (row, col) = e.cursor();
8075        assert_eq!(row, 1, "cursor should stay on start_row");
8076        assert_eq!(col, 4, "cursor should land on first non-ws char (col 4)");
8077    }
8078
8079    #[test]
8080    fn auto_indent_sets_last_indent_range() {
8081        // After `auto_indent_range` the engine must store the touched row span.
8082        let src = "{\nfoo\nbar\n}";
8083        let mut e = indent_editor(src, 4, true);
8084        let total = e.buffer().lines().len();
8085        e.auto_indent_range((0, 0), (total - 1, 0));
8086        assert_eq!(
8087            e.take_last_indent_range(),
8088            Some((0, total - 1)),
8089            "take_last_indent_range must return Some with the touched rows"
8090        );
8091    }
8092
8093    #[test]
8094    fn take_last_indent_range_clears() {
8095        // A second call after draining must return None.
8096        let src = "{\nfoo\n}";
8097        let mut e = indent_editor(src, 4, true);
8098        e.auto_indent_range((0, 0), (2, 0));
8099        let _ = e.take_last_indent_range(); // drain
8100        assert_eq!(
8101            e.take_last_indent_range(),
8102            None,
8103            "second take_last_indent_range must return None"
8104        );
8105    }
8106
8107    // ── Diagnostic: auto_indent vs cargo fmt on a real source file ────────
8108    //
8109    // Loads `motions.rs` (~1400 LOC, mixed real-world Rust patterns: method
8110    // chains, multi-line fn args, match arms, where clauses, closures, nested
8111    // types) at compile time, runs `auto_indent_range` over every row, and
8112    // diffs per-line leading-whitespace counts against the cargo-fmt'd source
8113    // (the file is in the repo, fmt'd by CI on every commit).
8114    //
8115    // The test PRINTS divergences and only fails if more than `THRESHOLD`
8116    // lines disagree — the dumb shiftwidth+bracket algorithm is documented
8117    // to mishandle some patterns (chains, where clauses, etc.). A full
8118    // language-aware indenter is a v2 follow-up. The point of this test is
8119    // to surface the divergence list so we can decide which patterns the
8120    // dumb algo CAN be taught to handle without going full tree-sitter.
8121    //
8122    // To diagnose: run with `--nocapture` to see the full diff.
8123    #[test]
8124    #[ignore = "diagnostic — run with --ignored --nocapture to see auto-indent vs cargo fmt diffs"]
8125    fn auto_indent_vs_cargo_fmt_motions_diagnostic() {
8126        let original = include_str!("motions.rs");
8127
8128        let mut e = Editor::new(
8129            hjkl_buffer::Buffer::new(),
8130            crate::types::DefaultHost::new(),
8131            crate::types::Options {
8132                shiftwidth: 4,
8133                expandtab: true,
8134                tabstop: 4,
8135                ..crate::types::Options::default()
8136            },
8137        );
8138        e.set_content(original);
8139
8140        let row_count = buf_row_count(&e.buffer);
8141        e.auto_indent_range((0, 0), (row_count.saturating_sub(1), 0));
8142
8143        let after_lines: Vec<String> = (0..row_count)
8144            .filter_map(|r| buf_line(&e.buffer, r).map(str::to_owned))
8145            .collect();
8146        let original_lines: Vec<&str> = original.lines().collect();
8147
8148        let leading_ws = |s: &str| s.chars().take_while(|c| c.is_whitespace()).count();
8149
8150        let mut diffs: Vec<(usize, String, usize, usize)> = Vec::new();
8151        for (i, (orig, after)) in original_lines.iter().zip(after_lines.iter()).enumerate() {
8152            let want = leading_ws(orig);
8153            let got = leading_ws(after);
8154            if want != got {
8155                diffs.push((i + 1, orig.trim().chars().take(80).collect(), want, got));
8156            }
8157        }
8158
8159        // Print the first 50 divergences for diagnosis.
8160        eprintln!(
8161            "auto_indent_vs_cargo_fmt: {} lines differ out of {} ({}%)",
8162            diffs.len(),
8163            original_lines.len(),
8164            (diffs.len() * 100) / original_lines.len().max(1),
8165        );
8166        for (line_no, content, want, got) in diffs.iter().take(50) {
8167            eprintln!("  L{line_no:5} want={want:2} got={got:2}  {content}");
8168        }
8169        if diffs.len() > 50 {
8170            eprintln!("  ... and {} more", diffs.len() - 50);
8171        }
8172
8173        // Soft assertion — track divergence count over time. If the algo
8174        // gets smarter, this number should drop. If a regression makes it
8175        // jump, we'll notice. Set the cap generously above current baseline.
8176        let pct = (diffs.len() * 100) / original_lines.len().max(1);
8177        // 2026-05-16 baseline after fixing bracket scan + chain continuation:
8178        // 5 divergences / 1416 lines (<1%). Remaining lines are a single
8179        // \`let X = if {} else {};\` trailing-\`=\` continuation pattern —
8180        // documented v2 follow-up. Cap at 2% so any regression in the
8181        // bracket scan or chain detection trips the test.
8182        assert!(
8183            pct < 2,
8184            "auto_indent diverges from cargo fmt on {pct}% of lines — regression from <1% baseline"
8185        );
8186    }
8187}