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;
10use crate::vim::{self, VimState};
11use crate::{KeybindingMode, VimMode};
12use std::sync::atomic::{AtomicU16, Ordering};
13use std::time::SystemTime;
14
15/// A single entry in the undo or redo stack.
16///
17/// The `timestamp` records the wall-clock time at which the snapshot was
18/// taken (i.e. when `push_undo` was called), enabling the `:earlier` /
19/// `:later` time-travel ex commands to walk the stack by duration rather
20/// than by step count.
21pub(crate) struct UndoEntry {
22    pub(crate) rope: ropey::Rope,
23    pub(crate) cursor: (usize, usize),
24    pub(crate) timestamp: SystemTime,
25}
26
27/// Map a [`hjkl_buffer::Edit`] to one or more SPEC
28/// [`crate::types::Edit`] (`EditOp`) records.
29///
30/// Most buffer edits map to a single EditOp. Block ops
31/// ([`hjkl_buffer::Edit::InsertBlock`] /
32/// [`hjkl_buffer::Edit::DeleteBlockChunks`]) emit one EditOp per row
33/// touched — they edit non-contiguous cells and a single
34/// `range..range` can't represent the rectangle.
35///
36/// Returns an empty vec when the edit isn't representable (no buffer
37/// variant currently fails this check).
38fn edit_to_editops(edit: &hjkl_buffer::Edit) -> Vec<crate::types::Edit> {
39    use crate::types::{Edit as Op, Pos};
40    use hjkl_buffer::Edit as B;
41    let to_pos = |p: hjkl_buffer::Position| Pos {
42        line: p.row as u32,
43        col: p.col as u32,
44    };
45    match edit {
46        B::InsertChar { at, ch } => vec![Op {
47            range: to_pos(*at)..to_pos(*at),
48            replacement: ch.to_string(),
49        }],
50        B::InsertStr { at, text } => vec![Op {
51            range: to_pos(*at)..to_pos(*at),
52            replacement: text.clone(),
53        }],
54        B::DeleteRange { start, end, .. } => vec![Op {
55            range: to_pos(*start)..to_pos(*end),
56            replacement: String::new(),
57        }],
58        B::Replace { start, end, with } => vec![Op {
59            range: to_pos(*start)..to_pos(*end),
60            replacement: with.clone(),
61        }],
62        B::JoinLines {
63            row,
64            count,
65            with_space,
66        } => {
67            // Joining `count` rows after `row` collapses
68            // [(row+1, 0) .. (row+count, EOL)] into the joined
69            // sentinel. The replacement is either an empty string
70            // (gJ) or " " between segments (J).
71            let start = Pos {
72                line: *row as u32 + 1,
73                col: 0,
74            };
75            let end = Pos {
76                line: (*row + *count) as u32,
77                col: u32::MAX, // covers to EOL of the last source row
78            };
79            vec![Op {
80                range: start..end,
81                replacement: if *with_space {
82                    " ".into()
83                } else {
84                    String::new()
85                },
86            }]
87        }
88        B::SplitLines {
89            row,
90            cols,
91            inserted_space: _,
92        } => {
93            // SplitLines reverses a JoinLines: insert a `\n`
94            // (and optional dropped space) at each col on `row`.
95            cols.iter()
96                .map(|c| {
97                    let p = Pos {
98                        line: *row as u32,
99                        col: *c as u32,
100                    };
101                    Op {
102                        range: p..p,
103                        replacement: "\n".into(),
104                    }
105                })
106                .collect()
107        }
108        B::InsertBlock { at, chunks } => {
109            // One EditOp per row in the block — non-contiguous edits.
110            chunks
111                .iter()
112                .enumerate()
113                .map(|(i, chunk)| {
114                    let p = Pos {
115                        line: at.row as u32 + i as u32,
116                        col: at.col as u32,
117                    };
118                    Op {
119                        range: p..p,
120                        replacement: chunk.clone(),
121                    }
122                })
123                .collect()
124        }
125        B::DeleteBlockChunks { at, widths } => {
126            // One EditOp per row, deleting `widths[i]` chars at
127            // `(at.row + i, at.col)`.
128            widths
129                .iter()
130                .enumerate()
131                .map(|(i, w)| {
132                    let start = Pos {
133                        line: at.row as u32 + i as u32,
134                        col: at.col as u32,
135                    };
136                    let end = Pos {
137                        line: at.row as u32 + i as u32,
138                        col: at.col as u32 + *w as u32,
139                    };
140                    Op {
141                        range: start..end,
142                        replacement: String::new(),
143                    }
144                })
145                .collect()
146        }
147    }
148}
149
150/// Sum of bytes from the start of the buffer to the start of `row`.
151/// Byte offset of the first byte of `row` within the canonical
152/// `lines().join("\n")` byte rendering. Pre-rope this walked every row
153/// from 0 to `row` allocating a `String` per row to read its `.len()` —
154/// O(row) allocations per call, fired from `position_to_byte_coords` on
155/// every `insert_char`. At the bottom of a 1.86 M-line buffer that was
156/// 1.86 M String allocations per keystroke (the dominant cost of the
157/// "edits at the bottom of the file are slow" symptom).
158///
159/// Now O(log N): ropey's `line_to_byte` walks the B-tree's per-node
160/// byte counts. No String materialization.
161#[inline]
162fn buffer_byte_of_row(buf: &hjkl_buffer::Buffer, row: usize) -> usize {
163    let rope = buf.rope();
164    let row = row.min(rope.len_lines());
165    rope.line_to_byte(row)
166}
167
168/// Convert an `hjkl_buffer::Position` (char-indexed col) into byte
169/// coordinates `(byte_within_buffer, (row, col_byte))` against the
170/// **pre-edit** buffer.
171fn position_to_byte_coords(
172    buf: &hjkl_buffer::Buffer,
173    pos: hjkl_buffer::Position,
174) -> (usize, (u32, u32)) {
175    let row = pos.row.min(buf.row_count().saturating_sub(1));
176    let rope = buf.rope();
177    let line = hjkl_buffer::rope_line_str(&rope, row);
178    let col_byte = pos.byte_offset(&line);
179    let byte = buffer_byte_of_row(buf, row) + col_byte;
180    (byte, (row as u32, col_byte as u32))
181}
182
183/// Walk `bytes[..end]` counting newlines and return the (row, col_byte)
184/// position at byte offset `end`. `col_byte` is the byte distance from
185/// the most recent `\n` (or buffer start). Used to translate a byte
186/// offset into a tree-sitter `Point`.
187fn byte_to_row_col(bytes: &[u8], end: usize) -> (u32, u32) {
188    let end = end.min(bytes.len());
189    let mut row: u32 = 0;
190    let mut row_start: usize = 0;
191    for (i, &b) in bytes[..end].iter().enumerate() {
192        if b == b'\n' {
193            row += 1;
194            row_start = i + 1;
195        }
196    }
197    (row, (end - row_start) as u32)
198}
199
200/// Rope-backed minimal content-edit diff for the undo/redo
201/// `restore_text` path. Walks `old_rope` chunk-by-chunk for the
202/// common-prefix / common-suffix scan instead of forcing a full
203/// `content_joined()` materialization (~3 MB per undo on huge files).
204///
205/// `ropey::Rope::bytes()` and `bytes_at(n).reversed()` give O(log N)
206/// seek + O(1)-per-byte step, so the scan cost matches the contiguous
207/// `&[u8]` version without the materialization alloc.
208fn minimal_content_edit_rope(old_rope: &ropey::Rope, new_text: &str) -> crate::types::ContentEdit {
209    let new_bytes = new_text.as_bytes();
210    let old_len = old_rope.len_bytes();
211    let new_len = new_bytes.len();
212    let common = old_len.min(new_len);
213
214    // Common prefix length — forward walk through rope bytes.
215    let mut prefix = 0;
216    let mut fwd = old_rope.bytes();
217    while prefix < common {
218        match fwd.next() {
219            Some(b) if b == new_bytes[prefix] => prefix += 1,
220            _ => break,
221        }
222    }
223    while prefix > 0 && prefix < old_len && (old_rope.byte(prefix) & 0b1100_0000) == 0b1000_0000 {
224        prefix -= 1;
225    }
226
227    // Common suffix length — backward walk through rope bytes.
228    let mut suffix = 0;
229    let max_suffix = (old_len - prefix).min(new_len - prefix);
230    let mut rev = old_rope.bytes_at(old_len).reversed();
231    while suffix < max_suffix {
232        match rev.next() {
233            Some(b) if b == new_bytes[new_len - 1 - suffix] => suffix += 1,
234            _ => break,
235        }
236    }
237    while suffix > 0
238        && suffix < old_len
239        && (old_rope.byte(old_len - suffix) & 0b1100_0000) == 0b1000_0000
240    {
241        suffix -= 1;
242    }
243
244    let start_byte = prefix;
245    let old_end_byte = old_len - suffix;
246    let new_end_byte = new_len - suffix;
247
248    crate::types::ContentEdit {
249        start_byte,
250        old_end_byte,
251        new_end_byte,
252        start_position: rope_byte_to_row_col(old_rope, start_byte),
253        old_end_position: rope_byte_to_row_col(old_rope, old_end_byte),
254        new_end_position: byte_to_row_col(new_bytes, new_end_byte),
255    }
256}
257
258#[inline]
259fn rope_byte_to_row_col(rope: &ropey::Rope, byte_idx: usize) -> (u32, u32) {
260    let byte_idx = byte_idx.min(rope.len_bytes());
261    let line = rope.byte_to_line(byte_idx);
262    let line_start = rope.line_to_byte(line);
263    (line as u32, (byte_idx - line_start) as u32)
264}
265
266/// Compute the byte position after inserting `text` starting at
267/// `start_byte` / `start_pos`. Returns `(end_byte, end_position)`.
268fn advance_by_text(text: &str, start_byte: usize, start_pos: (u32, u32)) -> (usize, (u32, u32)) {
269    let new_end_byte = start_byte + text.len();
270    let newlines = text.bytes().filter(|&b| b == b'\n').count();
271    let end_pos = if newlines == 0 {
272        (start_pos.0, start_pos.1 + text.len() as u32)
273    } else {
274        // Bytes after the last newline determine the trailing column.
275        let last_nl = text.rfind('\n').unwrap();
276        let tail_bytes = (text.len() - last_nl - 1) as u32;
277        (start_pos.0 + newlines as u32, tail_bytes)
278    };
279    (new_end_byte, end_pos)
280}
281
282/// Translate a single `hjkl_buffer::Edit` into one or more
283/// [`crate::types::ContentEdit`] records using the **pre-edit** buffer
284/// state for byte/position lookups. Block ops fan out to one entry per
285/// touched row (matches `edit_to_editops`).
286fn content_edits_from_buffer_edit(
287    buf: &hjkl_buffer::Buffer,
288    edit: &hjkl_buffer::Edit,
289) -> Vec<crate::types::ContentEdit> {
290    use hjkl_buffer::Edit as B;
291    use hjkl_buffer::Position;
292
293    let mut out: Vec<crate::types::ContentEdit> = Vec::new();
294
295    match edit {
296        B::InsertChar { at, ch } => {
297            let (start_byte, start_pos) = position_to_byte_coords(buf, *at);
298            let new_end_byte = start_byte + ch.len_utf8();
299            let new_end_pos = (start_pos.0, start_pos.1 + ch.len_utf8() as u32);
300            out.push(crate::types::ContentEdit {
301                start_byte,
302                old_end_byte: start_byte,
303                new_end_byte,
304                start_position: start_pos,
305                old_end_position: start_pos,
306                new_end_position: new_end_pos,
307            });
308        }
309        B::InsertStr { at, text } => {
310            let (start_byte, start_pos) = position_to_byte_coords(buf, *at);
311            let (new_end_byte, new_end_pos) = advance_by_text(text, start_byte, start_pos);
312            out.push(crate::types::ContentEdit {
313                start_byte,
314                old_end_byte: start_byte,
315                new_end_byte,
316                start_position: start_pos,
317                old_end_position: start_pos,
318                new_end_position: new_end_pos,
319            });
320        }
321        B::DeleteRange { start, end, kind } => {
322            let (start, end) = if start <= end {
323                (*start, *end)
324            } else {
325                (*end, *start)
326            };
327            match kind {
328                hjkl_buffer::MotionKind::Char => {
329                    let (start_byte, start_pos) = position_to_byte_coords(buf, start);
330                    let (old_end_byte, old_end_pos) = position_to_byte_coords(buf, end);
331                    out.push(crate::types::ContentEdit {
332                        start_byte,
333                        old_end_byte,
334                        new_end_byte: start_byte,
335                        start_position: start_pos,
336                        old_end_position: old_end_pos,
337                        new_end_position: start_pos,
338                    });
339                }
340                hjkl_buffer::MotionKind::Line => {
341                    // Linewise delete drops rows [start.row..=end.row]. Map
342                    // to a span from start of `start.row` through start of
343                    // (end.row + 1). The buffer's own `do_delete_range`
344                    // collapses to row `start.row` after dropping.
345                    let lo = start.row;
346                    let hi = end.row.min(buf.row_count().saturating_sub(1));
347                    let start_byte = buffer_byte_of_row(buf, lo);
348                    let next_row_byte = if hi + 1 < buf.row_count() {
349                        buffer_byte_of_row(buf, hi + 1)
350                    } else {
351                        // No row after; clamp to end-of-buffer byte.
352                        let last_row = buf.row_count().saturating_sub(1);
353                        buffer_byte_of_row(buf, buf.row_count())
354                            + hjkl_buffer::rope_line_bytes(&buf.rope(), last_row)
355                    };
356                    out.push(crate::types::ContentEdit {
357                        start_byte,
358                        old_end_byte: next_row_byte,
359                        new_end_byte: start_byte,
360                        start_position: (lo as u32, 0),
361                        old_end_position: ((hi + 1) as u32, 0),
362                        new_end_position: (lo as u32, 0),
363                    });
364                }
365                hjkl_buffer::MotionKind::Block => {
366                    // Block delete removes a rectangle of chars per row.
367                    // Fan out to one ContentEdit per row.
368                    let (left_col, right_col) = (start.col.min(end.col), start.col.max(end.col));
369                    for row in start.row..=end.row {
370                        let row_start_pos = Position::new(row, left_col);
371                        let row_end_pos = Position::new(row, right_col + 1);
372                        let (sb, sp) = position_to_byte_coords(buf, row_start_pos);
373                        let (eb, ep) = position_to_byte_coords(buf, row_end_pos);
374                        if eb <= sb {
375                            continue;
376                        }
377                        out.push(crate::types::ContentEdit {
378                            start_byte: sb,
379                            old_end_byte: eb,
380                            new_end_byte: sb,
381                            start_position: sp,
382                            old_end_position: ep,
383                            new_end_position: sp,
384                        });
385                    }
386                }
387            }
388        }
389        B::Replace { start, end, with } => {
390            let (start, end) = if start <= end {
391                (*start, *end)
392            } else {
393                (*end, *start)
394            };
395            let (start_byte, start_pos) = position_to_byte_coords(buf, start);
396            let (old_end_byte, old_end_pos) = position_to_byte_coords(buf, end);
397            let (new_end_byte, new_end_pos) = advance_by_text(with, start_byte, start_pos);
398            out.push(crate::types::ContentEdit {
399                start_byte,
400                old_end_byte,
401                new_end_byte,
402                start_position: start_pos,
403                old_end_position: old_end_pos,
404                new_end_position: new_end_pos,
405            });
406        }
407        B::JoinLines {
408            row,
409            count,
410            with_space,
411        } => {
412            // Joining `count` rows after `row` collapses the bytes
413            // between EOL of `row` and EOL of `row + count` into either
414            // an empty string (gJ) or a single space per join (J — but
415            // only when both sides are non-empty; we approximate with
416            // a single space for simplicity).
417            let row = (*row).min(buf.row_count().saturating_sub(1));
418            let last_join_row = (row + count).min(buf.row_count().saturating_sub(1));
419            let buf_rope = buf.rope();
420            let line = hjkl_buffer::rope_line_str(&buf_rope, row);
421            let row_eol_byte = buffer_byte_of_row(buf, row) + line.len();
422            let row_eol_col = line.len() as u32;
423            let next_row_after = last_join_row + 1;
424            let old_end_byte = if next_row_after < buf.row_count() {
425                buffer_byte_of_row(buf, next_row_after).saturating_sub(1)
426            } else {
427                let last_row = buf.row_count().saturating_sub(1);
428                buffer_byte_of_row(buf, buf.row_count())
429                    + hjkl_buffer::rope_line_bytes(&buf_rope, last_row)
430            };
431            let last_line = hjkl_buffer::rope_line_str(&buf_rope, last_join_row);
432            let old_end_pos = (last_join_row as u32, last_line.len() as u32);
433            let replacement_len = if *with_space { 1 } else { 0 };
434            let new_end_byte = row_eol_byte + replacement_len;
435            let new_end_pos = (row as u32, row_eol_col + replacement_len as u32);
436            out.push(crate::types::ContentEdit {
437                start_byte: row_eol_byte,
438                old_end_byte,
439                new_end_byte,
440                start_position: (row as u32, row_eol_col),
441                old_end_position: old_end_pos,
442                new_end_position: new_end_pos,
443            });
444        }
445        B::SplitLines {
446            row,
447            cols,
448            inserted_space,
449        } => {
450            // Splits insert "\n" (or "\n " inverse) at each col on `row`.
451            // The buffer applies all splits left-to-right via the
452            // do_split_lines path; we emit one ContentEdit per col,
453            // each treated as an insert at that col on `row`. Note: the
454            // buffer state during emission is *pre-edit*, so all cols
455            // index into the same pre-edit row.
456            let row = (*row).min(buf.row_count().saturating_sub(1));
457            let split_rope = buf.rope();
458            let line = hjkl_buffer::rope_line_str(&split_rope, row);
459            let row_byte = buffer_byte_of_row(buf, row);
460            let insert = if *inserted_space { "\n " } else { "\n" };
461            for &c in cols {
462                let pos = Position::new(row, c);
463                let col_byte = pos.byte_offset(&line);
464                let start_byte = row_byte + col_byte;
465                let start_pos = (row as u32, col_byte as u32);
466                let (new_end_byte, new_end_pos) = advance_by_text(insert, start_byte, start_pos);
467                out.push(crate::types::ContentEdit {
468                    start_byte,
469                    old_end_byte: start_byte,
470                    new_end_byte,
471                    start_position: start_pos,
472                    old_end_position: start_pos,
473                    new_end_position: new_end_pos,
474                });
475            }
476        }
477        B::InsertBlock { at, chunks } => {
478            // One ContentEdit per chunk; each lands at `(at.row + i,
479            // at.col)` in the pre-edit buffer.
480            for (i, chunk) in chunks.iter().enumerate() {
481                let pos = Position::new(at.row + i, at.col);
482                let (start_byte, start_pos) = position_to_byte_coords(buf, pos);
483                let (new_end_byte, new_end_pos) = advance_by_text(chunk, start_byte, start_pos);
484                out.push(crate::types::ContentEdit {
485                    start_byte,
486                    old_end_byte: start_byte,
487                    new_end_byte,
488                    start_position: start_pos,
489                    old_end_position: start_pos,
490                    new_end_position: new_end_pos,
491                });
492            }
493        }
494        B::DeleteBlockChunks { at, widths } => {
495            for (i, w) in widths.iter().enumerate() {
496                let row = at.row + i;
497                let start_pos = Position::new(row, at.col);
498                let end_pos = Position::new(row, at.col + *w);
499                let (sb, sp) = position_to_byte_coords(buf, start_pos);
500                let (eb, ep) = position_to_byte_coords(buf, end_pos);
501                if eb <= sb {
502                    continue;
503                }
504                out.push(crate::types::ContentEdit {
505                    start_byte: sb,
506                    old_end_byte: eb,
507                    new_end_byte: sb,
508                    start_position: sp,
509                    old_end_position: ep,
510                    new_end_position: sp,
511                });
512            }
513        }
514    }
515
516    out
517}
518
519/// Where the cursor should land in the viewport after a `z`-family
520/// scroll (`zz` / `zt` / `zb`).
521#[derive(Debug, Clone, Copy, PartialEq, Eq)]
522pub(super) enum CursorScrollTarget {
523    Center,
524    Top,
525    Bottom,
526}
527
528// ── Trait-surface cast helpers ────────────────────────────────────
529//
530// 0.0.42 (Patch C-δ.7): the helpers introduced in 0.0.41 were
531// promoted to [`crate::buf_helpers`] so `vim.rs` free fns can route
532// their reaches through the same primitives. Re-import via
533// `use` so the editor body keeps its terse call shape.
534
535use crate::buf_helpers::{
536    apply_buffer_edit, buf_cursor_pos, buf_cursor_rc, buf_cursor_row, buf_line, buf_line_chars,
537    buf_row_count, buf_set_cursor_rc,
538};
539
540/// Return value from the engine's `try_goto_mark_*` methods. Tells the
541/// caller (app layer) whether a cross-buffer switch is required.
542///
543/// - `SameBuffer` — cursor moved (or mark was unset → no-op) within the
544///   same buffer; no buffer switch needed.
545/// - `CrossBuffer` — the mark lives in a different buffer. The app must
546///   switch to the slot whose `buffer_id` matches, then position the cursor
547///   at `(row, col)` using `Editor::jump_cursor`.
548/// - `Unset` — mark not set; no action needed.
549#[derive(Debug, Clone, PartialEq, Eq)]
550pub enum MarkJump {
551    SameBuffer,
552    CrossBuffer {
553        buffer_id: u64,
554        row: usize,
555        col: usize,
556    },
557    Unset,
558}
559
560pub struct Editor<
561    B: crate::types::Buffer = hjkl_buffer::Buffer,
562    H: crate::types::Host = crate::types::DefaultHost,
563> {
564    pub keybinding_mode: KeybindingMode,
565    /// Set when the user yanks/cuts; caller drains this to write to OS clipboard.
566    pub last_yank: Option<String>,
567    /// All vim-specific state (mode, pending operator, count, dot-repeat, ...).
568    /// Internal — exposed via Editor accessor methods
569    /// ([`Editor::buffer_mark`], [`Editor::last_jump_back`],
570    /// [`Editor::last_edit_pos`], [`Editor::take_lsp_intent`], …).
571    pub(crate) vim: VimState,
572    /// Undo history: each entry is `(joined_document, cursor)` before the
573    /// edit. Stored as `Arc<String>` so it shares the
574    /// Undo history: snapshots taken via `Buffer::rope()` — `ropey::Rope::clone`
575    /// is O(1) (Arc-clone of the B-tree root). Previously stored
576    /// `Arc<String>` from `content_joined()`, which on the rope storage
577    /// builds the entire document `String` via `rope.to_string()` — that
578    /// turned every `i` / `o` keystroke into a ~3 MB allocation on a
579    /// 1.86 M-line file.
580    pub(crate) undo_stack: Vec<UndoEntry>,
581    /// Redo history: entries pushed when undoing.
582    pub(super) redo_stack: Vec<UndoEntry>,
583    /// Set whenever the buffer content changes; cleared by `take_dirty`.
584    pub(super) content_dirty: bool,
585    /// Cached snapshot of `lines().join("\n") + "\n"` wrapped in an Arc
586    /// so repeated `content_arc()` calls within the same un-mutated
587    /// window are free (ref-count bump instead of a full-buffer join).
588    /// Invalidated by every [`mark_content_dirty`] call.
589    pub(super) cached_content: Option<std::sync::Arc<String>>,
590    /// Last rendered viewport height (text rows only, no chrome). Written
591    /// by the draw path via [`set_viewport_height`] so the scroll helpers
592    /// can clamp the cursor to stay visible without plumbing the height
593    /// through every call.
594    pub(super) viewport_height: AtomicU16,
595    /// Pending LSP intent set by a normal-mode chord (e.g. `gd` for
596    /// goto-definition). The host app drains this each step and fires
597    /// the matching request against its own LSP client.
598    pub(super) pending_lsp: Option<LspIntent>,
599    /// Pending [`crate::types::FoldOp`]s raised by `z…` keystrokes,
600    /// the `:fold*` Ex commands, or the edit pipeline's
601    /// "edits-inside-a-fold open it" invalidation. Drained by hosts
602    /// via [`Editor::take_fold_ops`]; the engine also applies each op
603    /// locally through [`crate::buffer_impl::BufferFoldProviderMut`]
604    /// so the in-tree buffer fold storage stays in sync without host
605    /// cooperation. Introduced in 0.0.38 (Patch C-δ.4).
606    pub(super) pending_fold_ops: Vec<crate::types::FoldOp>,
607    /// Buffer storage.
608    ///
609    /// 0.1.0 (Patch C-δ): generic over `B: Buffer` per SPEC §"Editor
610    /// surface". Default `B = hjkl_buffer::Buffer`. The vim FSM body
611    /// and `Editor::mutate_edit` are concrete on `hjkl_buffer::Buffer`
612    /// for 0.1.0 — see `crate::buf_helpers::apply_buffer_edit`.
613    pub(super) buffer: B,
614    /// Engine-native style intern table. Opaque `Span::style` ids index
615    /// into this table; the render path resolves ids back to
616    /// [`crate::types::Style`]. Ratatui hosts convert at the boundary via
617    /// `hjkl_engine_tui::style_to_ratatui`. Always present — no cfg-mutex.
618    pub(super) style_table: Vec<crate::types::Style>,
619    /// Vim-style register bank — `"`, `"0`–`"9`, `"a`–`"z`. Sources
620    /// every `p` / `P` via the active selector (default unnamed).
621    /// Internal — read via [`Editor::registers`]; mutated by yank /
622    /// delete / paste FSM paths and by [`Editor::seed_yank`].
623    pub(crate) registers: crate::registers::Registers,
624    /// Per-row syntax styling in engine-native form. Always present —
625    /// populated by [`Editor::install_syntax_spans`]. Ratatui hosts use
626    /// `hjkl_engine_tui::EditorRatatuiExt::install_ratatui_syntax_spans`.
627    pub styled_spans: Vec<Vec<(usize, usize, crate::types::Style)>>,
628    /// Per-editor settings tweakable via `:set`. Exposed by reference
629    /// so handlers (indent, search) read the live value rather than a
630    /// snapshot taken at startup. Read via [`Editor::settings`];
631    /// mutate via [`Editor::settings_mut`].
632    pub(crate) settings: Settings,
633    /// Unified named-marks map. Lowercase letters (`'a`–`'z`) are
634    /// per-Editor / "buffer-scope-equivalent" — set by `m{a-z}`, read
635    /// by `'{a-z}` / `` `{a-z} ``. Uppercase letters (`'A`–`'Z`) are
636    /// "file marks" that survive [`Editor::set_content`] calls so
637    /// they persist across tab swaps within the same Editor.
638    ///
639    /// 0.0.36: consolidated from three former storages:
640    /// - `hjkl_buffer::Buffer::marks` (deleted; was unused dead code).
641    /// - `vim::VimState::marks` (lowercase) (deleted).
642    /// - `Editor::file_marks` (uppercase) (replaced by this map).
643    ///
644    /// `BTreeMap` so iteration is deterministic for snapshot tests
645    /// and the `:marks` ex command. Mark-shift on edits is handled
646    /// by [`Editor::shift_marks_after_edit`].
647    pub(crate) marks: std::collections::BTreeMap<char, (usize, usize)>,
648    /// Global (uppercase) marks that carry a `buffer_id` so they can jump
649    /// across buffers. Keyed by `'A'`–`'Z'`; values are
650    /// `(buffer_id, row, col)`. Set by `m{A-Z}`, resolved by
651    /// `try_goto_mark_line` / `try_goto_mark_char`.
652    pub(crate) global_marks: std::collections::BTreeMap<char, (u64, usize, usize)>,
653    /// The `buffer_id` this editor instance is currently attached to.
654    /// Updated by the host app on every `switch_to` / slot creation so
655    /// global-mark writes record the correct id without requiring the app
656    /// to pass the id on every keystroke.
657    pub(crate) current_buffer_id: u64,
658    /// Block ranges (`(start_row, end_row)` inclusive) the host has
659    /// extracted from a syntax tree. `:foldsyntax` reads these to
660    /// populate folds. The host refreshes them on every re-parse via
661    /// [`Editor::set_syntax_fold_ranges`]; ex commands read them via
662    /// [`Editor::syntax_fold_ranges`].
663    pub(crate) syntax_fold_ranges: Vec<(usize, usize)>,
664    /// Pending edit log drained by [`Editor::take_changes`]. Each entry
665    /// is a SPEC [`crate::types::Edit`] mapped from the underlying
666    /// `hjkl_buffer::Edit` operation. Compound ops (JoinLines,
667    /// SplitLines, InsertBlock, DeleteBlockChunks) emit a single
668    /// best-effort EditOp covering the touched range; hosts wanting
669    /// per-cell deltas should diff their own snapshot of `lines()`.
670    /// Sealed at 0.1.0 trait extraction.
671    /// Drained by [`Editor::take_changes`].
672    pub(crate) change_log: Vec<crate::types::Edit>,
673    /// Vim's "sticky column" (curswant). `None` before the first
674    /// motion — the next vertical motion bootstraps from the live
675    /// cursor column. Horizontal motions refresh this to the new
676    /// column; vertical motions read it back so bouncing through a
677    /// shorter row doesn't drag the cursor to col 0. Hoisted out of
678    /// `hjkl_buffer::Buffer` (and `VimState`) in 0.0.28 — Editor is
679    /// the single owner now. Buffer motion methods that need it
680    /// take a `&mut Option<usize>` parameter.
681    pub(crate) sticky_col: Option<usize>,
682    /// Host adapter for clipboard, cursor-shape, time, viewport, and
683    /// search-prompt / cancellation side-channels.
684    ///
685    /// 0.1.0 (Patch C-δ): generic over `H: Host` per SPEC §"Editor
686    /// surface". Default `H = DefaultHost`. The pre-0.1.0 `EngineHost`
687    /// dyn-shim is gone — every method now dispatches through `H`'s
688    /// `Host` trait surface directly.
689    pub(crate) host: H,
690    /// Last public mode the cursor-shape emitter saw. Drives
691    /// [`Editor::emit_cursor_shape_if_changed`] so `Host::emit_cursor_shape`
692    /// fires exactly once per mode transition without sprinkling the
693    /// call across every `vim.mode = ...` site.
694    pub(crate) last_emitted_mode: crate::VimMode,
695    /// Search FSM state (pattern + per-row match cache + wrapscan).
696    /// 0.0.35: relocated out of `hjkl_buffer::Buffer` per
697    /// `DESIGN_33_METHOD_CLASSIFICATION.md` step 1.
698    /// 0.0.37: the buffer-side bridge (`Buffer::search_pattern`) is
699    /// gone; `BufferView` now takes the active regex as a `&Regex`
700    /// parameter, sourced from `Editor::search_state().pattern`.
701    pub(crate) search_state: crate::search::SearchState,
702    /// Per-row syntax span overlay. Source of truth for the host's
703    /// renderer ([`hjkl_buffer::BufferView::spans`]). Populated by
704    /// [`Editor::install_syntax_spans`] (ratatui hosts use
705    /// `hjkl_engine_tui::EditorRatatuiExt::install_ratatui_syntax_spans`)
706    /// and, in due course, by `Host::syntax_highlights` once the engine
707    /// drives that path directly.
708    ///
709    /// 0.0.37: lifted out of `hjkl_buffer::Buffer` per step 3 of
710    /// `DESIGN_33_METHOD_CLASSIFICATION.md`. The buffer-side cache +
711    /// `Buffer::set_spans` / `Buffer::spans` accessors are gone.
712    pub(crate) buffer_spans: Vec<Vec<hjkl_buffer::Span>>,
713    /// Pending `ContentEdit` records emitted by `mutate_edit`. Drained by
714    /// hosts via [`Editor::take_content_edits`] for fan-in to a syntax
715    /// tree (or any other content-change observer that needs byte-level
716    /// position deltas). Edges are byte-indexed and `(row, col_byte)`.
717    pub(crate) pending_content_edits: Vec<crate::types::ContentEdit>,
718    /// Pending "reset" flag set when the entire buffer is replaced
719    /// (e.g. `set_content` / `restore`). Supersedes any queued
720    /// `pending_content_edits` on the same frame: hosts call
721    /// [`Editor::take_content_reset`] before draining edits.
722    pub(crate) pending_content_reset: bool,
723    /// Row range touched by the most recent `auto_indent_rows` call.
724    /// `(top_row, bot_row)` inclusive. Set by the engine after every
725    /// auto-indent operation; drained (and cleared) by the host via
726    /// [`Editor::take_last_indent_range`] so it can display a brief
727    /// visual flash over the reindented rows.
728    pub(crate) last_indent_range: Option<(usize, usize)>,
729}
730
731/// Vim-style options surfaced by `:set`. New fields land here as
732/// individual ex commands gain `:set` plumbing.
733#[derive(Debug, Clone)]
734pub struct Settings {
735    /// Spaces per shift step for `>>` / `<<` / `Ctrl-T` / `Ctrl-D`.
736    pub shiftwidth: usize,
737    /// Visual width of a `\t` character. Stored for future render
738    /// hookup; not yet consumed by the buffer renderer.
739    pub tabstop: usize,
740    /// When true, `/` / `?` patterns and `:s/.../.../` ignore case
741    /// without an explicit `i` flag.
742    pub ignore_case: bool,
743    /// When true *and* `ignore_case` is true, an uppercase letter in
744    /// the pattern flips that search back to case-sensitive. Matches
745    /// vim's `:set smartcase`. Default `false`.
746    pub smartcase: bool,
747    /// Wrap searches past buffer ends. Matches vim's `:set wrapscan`.
748    /// Default `true`.
749    pub wrapscan: bool,
750    /// Wrap column for `gq{motion}` text reflow. Vim's default is 79.
751    pub textwidth: usize,
752    /// When `true`, the Tab key in insert mode inserts `tabstop` spaces
753    /// instead of a literal `\t`. Matches vim's `:set expandtab`.
754    /// Default `false`.
755    pub expandtab: bool,
756    /// Soft tab stop in spaces. When `> 0`, Tab inserts spaces to the
757    /// next softtabstop boundary (when `expandtab`), and Backspace at the
758    /// end of a softtabstop-aligned space run deletes the entire run as
759    /// if it were one tab. `0` disables. Matches vim's `:set softtabstop`.
760    pub softtabstop: usize,
761    /// Soft-wrap mode the renderer + scroll math + `gj` / `gk` use.
762    /// Default is [`hjkl_buffer::Wrap::None`] — long lines extend
763    /// past the right edge and `top_col` clips the left side.
764    /// `:set wrap` flips to char-break wrap; `:set linebreak` flips
765    /// to word-break wrap; `:set nowrap` resets.
766    pub wrap: hjkl_buffer::Wrap,
767    /// When true, the engine drops every edit before it touches the
768    /// buffer — undo, dirty flag, and change log all stay clean.
769    /// Matches vim's `:set readonly` / `:set ro`. Default `false`.
770    pub readonly: bool,
771    /// When `true`, pressing Enter in insert mode copies the leading
772    /// whitespace of the current line onto the new line. Matches vim's
773    /// `:set autoindent`. Default `true` (vim parity).
774    pub autoindent: bool,
775    /// When `true`, bumps indent by one `shiftwidth` after a line ending
776    /// in `{` / `(` / `[`, and strips one indent unit when the user types
777    /// `}` / `)` / `]` on a whitespace-only line. See `compute_enter_indent`
778    /// in `vim.rs` for the tree-sitter plug-in seam. Default `true`.
779    pub smartindent: bool,
780    /// Cap on undo-stack length. Older entries are pruned past this
781    /// bound. `0` means unlimited. Matches vim's `:set undolevels`.
782    /// Default `1000`.
783    pub undo_levels: u32,
784    /// When `true`, cursor motions inside insert mode break the
785    /// current undo group (so a single `u` only reverses the run of
786    /// keystrokes that preceded the motion). Default `true`.
787    /// Currently a no-op — engine doesn't yet break the undo group
788    /// on insert-mode motions; field is wired through `:set
789    /// undobreak` for forward compatibility.
790    pub undo_break_on_motion: bool,
791    /// Vim-flavoured "what counts as a word" character class.
792    /// Comma-separated tokens: `@` = `is_alphabetic()`, `_` = literal
793    /// `_`, `48-57` = decimal char range, bare integer = single char
794    /// code, single ASCII punctuation = literal. Default
795    /// `"@,48-57,_,192-255"` matches vim.
796    pub iskeyword: String,
797    /// Multi-key sequence timeout (e.g. `gg`, `dd`). When the user
798    /// pauses longer than this between keys, any pending prefix is
799    /// abandoned and the next key starts a fresh sequence. Matches
800    /// vim's `:set timeoutlen` / `:set tm` (millis). Default 1000ms.
801    pub timeout_len: core::time::Duration,
802    /// When true, render absolute line numbers in the gutter. Matches
803    /// vim's `:set number` / `:set nu`. Default `true`.
804    pub number: bool,
805    /// When true, render line numbers as offsets from the cursor row.
806    /// Combined with `number`, the cursor row shows its absolute number
807    /// while other rows show the relative offset (vim's `nu+rnu` hybrid).
808    /// Matches vim's `:set relativenumber` / `:set rnu`. Default `false`.
809    pub relativenumber: bool,
810    /// Minimum gutter width in cells for the line-number column.
811    /// Width grows past this to fit the largest displayed number.
812    /// Matches vim's `:set numberwidth` / `:set nuw`. Default `4`.
813    /// Range 1..=20.
814    pub numberwidth: usize,
815    /// Highlight the row where the cursor sits. Matches vim's `:set cursorline`.
816    /// Default `false`.
817    pub cursorline: bool,
818    /// Highlight the column where the cursor sits. Matches vim's `:set cursorcolumn`.
819    /// Default `false`.
820    pub cursorcolumn: bool,
821    /// Sign-column display mode. Matches vim's `:set signcolumn`.
822    /// Default [`crate::types::SignColumnMode::Auto`].
823    pub signcolumn: crate::types::SignColumnMode,
824    /// Number of cells reserved for a fold-marker gutter.
825    /// Matches vim's `:set foldcolumn`. Default `0`.
826    pub foldcolumn: u32,
827    /// Comma-separated 1-based column indices for vertical rulers.
828    /// Matches vim's `:set colorcolumn`. Default `""`.
829    pub colorcolumn: String,
830    /// Format options flags (subset of vim's `formatoptions`).
831    /// `r` — auto-continue line comments on `<Enter>` in insert mode.
832    /// `o` — auto-continue line comments on `o` / `O` in normal mode.
833    /// Default: both on (`"ro"`).
834    pub formatoptions: String,
835    /// Active filetype (language name) for the current buffer.
836    /// Used by comment-continuation and future language-aware features.
837    /// Matches vim's `:set filetype` / `:set ft`. Default `""` (plain text).
838    pub filetype: String,
839    /// Override comment-string for the current buffer.
840    ///
841    /// When non-empty, used by `toggle_comment_range` instead of the
842    /// per-filetype default from `hjkl_lang::comment::commentstring_for_lang`.
843    /// Follows vim's `:set commentstring=…` — use `%s` as the text placeholder
844    /// (e.g. `"// %s"`) for compatibility; the toggle strips/inserts only the
845    /// prefix/suffix portion (before/after `%s`).  An empty string means "use
846    /// the filetype default".  Default `""`.
847    pub commentstring: String,
848    /// When `true`, typing an opening bracket or quote automatically inserts
849    /// the matching close character and parks the cursor between them.
850    /// Matches vim's `set autopairs` (Neovim) / nvim-autopairs behaviour.
851    /// Default `true`.
852    pub autopair: bool,
853    /// When `true`, typing `>` to close an HTML/XML opening tag automatically
854    /// inserts `</tagname>` after the cursor. Only fires for filetypes in the
855    /// HTML/XML family (`html`, `xml`, `svg`, `jsx`, `tsx`, `vue`, `svelte`).
856    /// Matches common editor "autoclose tag" behaviour. Default: `true` for
857    /// those filetypes (the caller gates on filetype), `true` stored here so
858    /// `:set noautoclose-tag` can disable it globally.
859    pub autoclose_tag: bool,
860    /// Minimum context rows kept visible above/below the cursor when scrolling.
861    /// Capped at (height - 1) / 2 for tiny viewports. `0` = no margin.
862    /// Matches vim's `:set scrolloff` / `:set so`. Default `5`.
863    pub scrolloff: usize,
864    /// Minimum context columns kept visible left/right of the cursor (no-wrap
865    /// mode only). `0` = no margin (vim default). Matches `:set sidescrolloff`.
866    /// Default `0`.
867    pub sidescrolloff: usize,
868    /// Auto-reload a clean buffer when its file changes on disk. Matches vim's
869    /// `:set autoread`. Default `true`. Consumed by the host's `:checktime`.
870    pub autoreload: bool,
871    /// Enable vim-sneak style two-char digraph jump via `s` (forward) and
872    /// `S` (backward). When `true` (default), `s`/`S` no longer behave as
873    /// vim's built-in substitute-char / substitute-line; `;`/`,` smart-fall-
874    /// back to sneak-repeat when the last horizontal motion was a sneak.
875    /// Set `:set nomotion_sneak` to revert `s`/`S` to stock vim behavior.
876    /// Default `true` — **BREAKING** for users relying on `s` = substitute-char.
877    pub motion_sneak: bool,
878    /// Render invisible characters (tabs, trailing spaces, EOL markers).
879    /// Matches vim's `:set list` / `:set nolist`. Default `false`.
880    pub list: bool,
881    /// Characters used to represent invisibles when `list` is on.
882    /// Matches vim's `:set listchars` / `:set lcs`.
883    pub listchars: crate::types::ListChars,
884    /// Render thin vertical indent guides at every `shiftwidth`-aligned
885    /// column. hjkl-specific. Default `true`.
886    pub indent_guides: bool,
887    /// Character used to draw indent guides. Default `'│'`.
888    pub indent_guide_char: char,
889    /// Enable inline color-literal preview. hjkl-specific. Default `true`.
890    pub colorizer: bool,
891    /// Filetype allowlist for the colorizer. Default CSS/template languages.
892    pub colorizer_filetypes: Vec<String>,
893    /// Run hjkl-mangler formatter before each `:w` save. Default `false`.
894    pub format_on_save: bool,
895    /// Strip trailing whitespace before each `:w` save. Default `false`.
896    pub trim_trailing_whitespace: bool,
897    /// Enable helix-style rainbow bracket coloring. hjkl-specific. Default `true`.
898    pub rainbow_brackets: bool,
899    /// Milliseconds of inactivity before swap-file write. Default `4000`.
900    /// Matches Vim's `updatetime`; alias `ut`.
901    pub updatetime: u32,
902    /// Highlight matching bracket pair under the cursor. hjkl-specific. Default `true`.
903    /// `:set nomatchparen` / `:set mps` to toggle. Only the char-scan path
904    /// (C-style brackets) is active; tag-pair matching is pending #240.
905    pub matchparen: bool,
906}
907
908impl Default for Settings {
909    fn default() -> Self {
910        Self {
911            shiftwidth: 4,
912            tabstop: 4,
913            softtabstop: 4,
914            ignore_case: true,
915            smartcase: true,
916            wrapscan: true,
917            textwidth: 79,
918            expandtab: true,
919            wrap: hjkl_buffer::Wrap::None,
920            readonly: false,
921            autoindent: true,
922            smartindent: true,
923            undo_levels: 1000,
924            undo_break_on_motion: true,
925            iskeyword: "@,48-57,_,192-255".to_string(),
926            timeout_len: core::time::Duration::from_millis(1000),
927            number: true,
928            relativenumber: false,
929            numberwidth: 4,
930            cursorline: false,
931            cursorcolumn: false,
932            signcolumn: crate::types::SignColumnMode::Auto,
933            foldcolumn: 0,
934            colorcolumn: String::new(),
935            formatoptions: "ro".to_string(),
936            filetype: String::new(),
937            commentstring: String::new(),
938            autopair: true,
939            autoclose_tag: true,
940            scrolloff: 5,
941            sidescrolloff: 0,
942            autoreload: true,
943            motion_sneak: true,
944            list: false,
945            listchars: crate::types::ListChars::default(),
946            indent_guides: true,
947            indent_guide_char: '│',
948            colorizer: true,
949            colorizer_filetypes: vec![
950                "css".to_string(),
951                "scss".to_string(),
952                "sass".to_string(),
953                "less".to_string(),
954                "html".to_string(),
955                "vue".to_string(),
956                "svelte".to_string(),
957                "tailwindcss".to_string(),
958                "toml".to_string(),
959                "lua".to_string(),
960                "vim".to_string(),
961            ],
962            format_on_save: false,
963            trim_trailing_whitespace: false,
964            rainbow_brackets: true,
965            updatetime: 4000,
966            matchparen: true,
967        }
968    }
969}
970
971/// Translate a SPEC [`crate::types::Options`] into the engine's
972/// internal [`Settings`] representation. Field-by-field map; the
973/// shapes are isomorphic except for type widths
974/// (`u32` vs `usize`, [`crate::types::WrapMode`] vs
975/// [`hjkl_buffer::Wrap`]). 0.1.0 (Patch C-δ) collapses both into one
976/// type once the `Editor<B, H>::new(buffer, host, options)` constructor
977/// is the canonical entry point.
978fn settings_from_options(o: &crate::types::Options) -> Settings {
979    Settings {
980        shiftwidth: o.shiftwidth as usize,
981        tabstop: o.tabstop as usize,
982        softtabstop: o.softtabstop as usize,
983        ignore_case: o.ignorecase,
984        smartcase: o.smartcase,
985        wrapscan: o.wrapscan,
986        textwidth: o.textwidth as usize,
987        expandtab: o.expandtab,
988        wrap: match o.wrap {
989            crate::types::WrapMode::None => hjkl_buffer::Wrap::None,
990            crate::types::WrapMode::Char => hjkl_buffer::Wrap::Char,
991            crate::types::WrapMode::Word => hjkl_buffer::Wrap::Word,
992        },
993        readonly: o.readonly,
994        autoindent: o.autoindent,
995        smartindent: o.smartindent,
996        undo_levels: o.undo_levels,
997        undo_break_on_motion: o.undo_break_on_motion,
998        iskeyword: o.iskeyword.clone(),
999        timeout_len: o.timeout_len,
1000        number: o.number,
1001        relativenumber: o.relativenumber,
1002        numberwidth: o.numberwidth,
1003        cursorline: o.cursorline,
1004        cursorcolumn: o.cursorcolumn,
1005        signcolumn: o.signcolumn,
1006        foldcolumn: o.foldcolumn,
1007        colorcolumn: o.colorcolumn.clone(),
1008        formatoptions: o.formatoptions.clone(),
1009        filetype: o.filetype.clone(),
1010        commentstring: String::new(),
1011        autopair: true,
1012        autoclose_tag: true,
1013        scrolloff: o.scrolloff,
1014        sidescrolloff: o.sidescrolloff,
1015        autoreload: o.autoreload,
1016        motion_sneak: o.motion_sneak,
1017        list: o.list,
1018        listchars: o.listchars.clone(),
1019        indent_guides: o.indent_guides,
1020        indent_guide_char: o.indent_guide_char,
1021        colorizer: o.colorizer,
1022        colorizer_filetypes: o.colorizer_filetypes.clone(),
1023        format_on_save: o.format_on_save,
1024        trim_trailing_whitespace: o.trim_trailing_whitespace,
1025        rainbow_brackets: o.rainbow_brackets,
1026        updatetime: o.updatetime,
1027        matchparen: o.matchparen,
1028    }
1029}
1030
1031/// Host-observable LSP requests triggered by editor bindings. The
1032/// hjkl-engine crate doesn't talk to an LSP itself — it just raises an
1033/// intent that the TUI layer picks up and routes to `sqls`.
1034#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1035pub enum LspIntent {
1036    /// `gd` — textDocument/definition at the cursor.
1037    GotoDefinition,
1038}
1039
1040impl<H: crate::types::Host> Editor<hjkl_buffer::Buffer, H> {
1041    /// Build an [`Editor`] from a buffer, host adapter, and SPEC options.
1042    ///
1043    /// 0.1.0 (Patch C-δ): canonical, frozen constructor per SPEC §"Editor
1044    /// surface". Replaces the pre-0.1.0 `Editor::new(KeybindingMode)` /
1045    /// `with_host` / `with_options` triad — there is no shim.
1046    ///
1047    /// Consumers that don't need a custom host pass
1048    /// [`crate::types::DefaultHost::new()`]; consumers that don't need
1049    /// custom options pass [`crate::types::Options::default()`].
1050    pub fn new(buffer: hjkl_buffer::Buffer, host: H, options: crate::types::Options) -> Self {
1051        let settings = settings_from_options(&options);
1052        Self {
1053            keybinding_mode: KeybindingMode::Vim,
1054            last_yank: None,
1055            vim: VimState::default(),
1056            undo_stack: Vec::new(),
1057            redo_stack: Vec::new(),
1058            content_dirty: false,
1059            cached_content: None,
1060            viewport_height: AtomicU16::new(0),
1061            pending_lsp: None,
1062            pending_fold_ops: Vec::new(),
1063            buffer,
1064            style_table: Vec::new(),
1065            registers: crate::registers::Registers::default(),
1066            styled_spans: Vec::new(),
1067            settings,
1068            marks: std::collections::BTreeMap::new(),
1069            global_marks: std::collections::BTreeMap::new(),
1070            current_buffer_id: 0,
1071            syntax_fold_ranges: Vec::new(),
1072            change_log: Vec::new(),
1073            sticky_col: None,
1074            host,
1075            last_emitted_mode: crate::VimMode::Normal,
1076            search_state: crate::search::SearchState::new(),
1077            buffer_spans: Vec::new(),
1078            pending_content_edits: Vec::new(),
1079            pending_content_reset: false,
1080            last_indent_range: None,
1081        }
1082    }
1083}
1084
1085impl<B: crate::types::Buffer, H: crate::types::Host> Editor<B, H> {
1086    /// Borrow the buffer (typed `&B`). Host renders through this via
1087    /// `hjkl_buffer::BufferView` when `B = hjkl_buffer::Buffer`.
1088    pub fn buffer(&self) -> &B {
1089        &self.buffer
1090    }
1091
1092    /// Mutably borrow the buffer (typed `&mut B`).
1093    pub fn buffer_mut(&mut self) -> &mut B {
1094        &mut self.buffer
1095    }
1096
1097    /// Borrow the host adapter directly (typed `&H`).
1098    pub fn host(&self) -> &H {
1099        &self.host
1100    }
1101
1102    /// Mutably borrow the host adapter (typed `&mut H`).
1103    pub fn host_mut(&mut self) -> &mut H {
1104        &mut self.host
1105    }
1106}
1107
1108impl<H: crate::types::Host> Editor<hjkl_buffer::Buffer, H> {
1109    /// Update the active `iskeyword` spec for word motions
1110    /// (`w`/`b`/`e`/`ge` and engine-side `*`/`#` pickup). 0.0.28
1111    /// hoisted iskeyword storage out of `Buffer` — `Editor` is the
1112    /// single owner now. Equivalent to assigning
1113    /// `settings_mut().iskeyword` directly; the dedicated setter is
1114    /// retained for source-compatibility with 0.0.27 callers.
1115    pub fn set_iskeyword(&mut self, spec: impl Into<String>) {
1116        self.settings.iskeyword = spec.into();
1117    }
1118
1119    /// Emit `Host::emit_cursor_shape` if the public mode has changed
1120    /// since the last emit. Engine calls this at the end of every input
1121    /// step so mode transitions surface to the host without sprinkling
1122    /// the call across every `vim.mode = ...` site.
1123    pub fn emit_cursor_shape_if_changed(&mut self) {
1124        let mode = self.vim_mode();
1125        if mode == self.last_emitted_mode {
1126            return;
1127        }
1128        let shape = match mode {
1129            crate::VimMode::Insert => crate::types::CursorShape::Bar,
1130            _ => crate::types::CursorShape::Block,
1131        };
1132        self.host.emit_cursor_shape(shape);
1133        self.last_emitted_mode = mode;
1134    }
1135
1136    /// Record a yank/cut payload. Writes both the legacy
1137    /// [`Editor::last_yank`] field (drained directly by 0.0.28-era
1138    /// hosts) and the new [`crate::types::Host::write_clipboard`]
1139    /// side-channel (Patch B). Consumers should migrate to a `Host`
1140    /// impl whose `write_clipboard` queues the platform-clipboard
1141    /// write; the `last_yank` mirror will be removed at 0.1.0.
1142    pub(crate) fn record_yank_to_host(&mut self, text: String) {
1143        self.host.write_clipboard(text.clone());
1144        self.last_yank = Some(text);
1145    }
1146
1147    /// Vim's sticky column (curswant). `None` before the first motion;
1148    /// hosts shouldn't normally need to read this directly — it's
1149    /// surfaced for migration off `Buffer::sticky_col` and for
1150    /// snapshot tests.
1151    pub fn sticky_col(&self) -> Option<usize> {
1152        self.sticky_col
1153    }
1154
1155    /// Replace the sticky column. Hosts should rarely touch this —
1156    /// motion code maintains it through the standard horizontal /
1157    /// vertical motion paths.
1158    pub fn set_sticky_col(&mut self, col: Option<usize>) {
1159        self.sticky_col = col;
1160    }
1161
1162    /// Host hook: replace the cached syntax-derived block ranges that
1163    /// `:foldsyntax` consumes. the host calls this on every re-parse;
1164    /// the cost is just a `Vec` swap.
1165    /// Look up a named mark by character. Returns `(row, col)` if
1166    /// set; `None` otherwise. Both lowercase (`'a`–`'z`) and
1167    /// uppercase (`'A`–`'Z`) marks live in the same unified
1168    /// [`Editor::marks`] map as of 0.0.36.
1169    pub fn mark(&self, c: char) -> Option<(usize, usize)> {
1170        self.marks.get(&c).copied()
1171    }
1172
1173    /// Set the named mark `c` to `(row, col)`. Used by the FSM's
1174    /// `m{a-zA-Z}` keystroke and by [`Editor::restore_snapshot`].
1175    pub fn set_mark(&mut self, c: char, pos: (usize, usize)) {
1176        self.marks.insert(c, pos);
1177    }
1178
1179    /// Remove the named mark `c` (no-op if unset).
1180    pub fn clear_mark(&mut self, c: char) {
1181        self.marks.remove(&c);
1182    }
1183
1184    /// Look up an uppercase global mark by letter. Returns
1185    /// `(buffer_id, row, col)` if set; `None` otherwise.
1186    pub fn global_mark(&self, c: char) -> Option<(u64, usize, usize)> {
1187        self.global_marks.get(&c).copied()
1188    }
1189
1190    /// Set an uppercase global mark `c` to `(buffer_id, row, col)`.
1191    pub fn set_global_mark(&mut self, c: char, buffer_id: u64, pos: (usize, usize)) {
1192        self.global_marks.insert(c, (buffer_id, pos.0, pos.1));
1193    }
1194
1195    /// Return the `buffer_id` this editor is currently attached to.
1196    pub fn current_buffer_id(&self) -> u64 {
1197        self.current_buffer_id
1198    }
1199
1200    /// Update the `buffer_id` this editor is attached to. Called by the
1201    /// app on every `switch_to` so global-mark sets record the correct id.
1202    pub fn set_current_buffer_id(&mut self, id: u64) {
1203        self.current_buffer_id = id;
1204    }
1205
1206    /// Iterate all global marks (`'A'`–`'Z'`), yielding
1207    /// `(mark_char, buffer_id, row, col)`.
1208    pub fn global_marks_iter(&self) -> impl Iterator<Item = (char, u64, usize, usize)> + '_ {
1209        self.global_marks
1210            .iter()
1211            .map(|(c, &(bid, r, col))| (*c, bid, r, col))
1212    }
1213
1214    /// Look up a buffer-local lowercase mark (`'a`–`'z`). Kept as a
1215    /// thin wrapper over [`Editor::mark`] for source compatibility
1216    /// with pre-0.0.36 callers; new code should call
1217    /// [`Editor::mark`] directly.
1218    #[deprecated(
1219        since = "0.0.36",
1220        note = "use Editor::mark — lowercase + uppercase marks now live in a single map"
1221    )]
1222    pub fn buffer_mark(&self, c: char) -> Option<(usize, usize)> {
1223        self.mark(c)
1224    }
1225
1226    /// Discard the most recent undo entry. Used by ex commands that
1227    /// pre-emptively pushed an undo state (`:s`, `:r`) but ended up
1228    /// matching nothing — popping prevents a no-op undo step from
1229    /// polluting the user's history.
1230    ///
1231    /// Returns `true` if an entry was discarded.
1232    pub fn pop_last_undo(&mut self) -> bool {
1233        self.undo_stack.pop().is_some()
1234    }
1235
1236    /// Read all named marks set this session — both lowercase
1237    /// (`'a`–`'z`) and uppercase (`'A`–`'Z`). Iteration is
1238    /// deterministic (BTreeMap-ordered) so snapshot / `:marks`
1239    /// output is stable.
1240    pub fn marks(&self) -> impl Iterator<Item = (char, (usize, usize))> + '_ {
1241        self.marks.iter().map(|(c, p)| (*c, *p))
1242    }
1243
1244    /// Read all buffer-local lowercase marks. Kept for source
1245    /// compatibility with pre-0.0.36 callers (e.g. `:marks` ex
1246    /// command); new code should use [`Editor::marks`] which
1247    /// iterates the unified map.
1248    #[deprecated(
1249        since = "0.0.36",
1250        note = "use Editor::marks — lowercase + uppercase marks now live in a single map"
1251    )]
1252    pub fn buffer_marks(&self) -> impl Iterator<Item = (char, (usize, usize))> + '_ {
1253        self.marks
1254            .iter()
1255            .filter(|(c, _)| c.is_ascii_lowercase())
1256            .map(|(c, p)| (*c, *p))
1257    }
1258
1259    /// Position the cursor was at when the user last jumped via
1260    /// `<C-o>` / `g;` / similar. `None` before any jump.
1261    pub fn last_jump_back(&self) -> Option<(usize, usize)> {
1262        self.vim.jump_back.last().copied()
1263    }
1264
1265    /// Position of the last edit (where `.` would replay). `None` if
1266    /// no edit has happened yet in this session.
1267    pub fn last_edit_pos(&self) -> Option<(usize, usize)> {
1268        self.vim.last_edit_pos
1269    }
1270
1271    /// Read-only view of the file-marks table — uppercase / "file"
1272    /// marks (`'A`–`'Z`) the host has set this session. Returns an
1273    /// iterator of `(mark_char, (row, col))` pairs.
1274    ///
1275    /// Mutate via the FSM (`m{A-Z}` keystroke) or via
1276    /// [`Editor::restore_snapshot`].
1277    ///
1278    /// 0.0.36: file marks now live in the unified [`Editor::marks`]
1279    /// map; this accessor is kept for source compatibility and
1280    /// filters the unified map to uppercase entries.
1281    pub fn file_marks(&self) -> impl Iterator<Item = (char, (usize, usize))> + '_ {
1282        self.marks
1283            .iter()
1284            .filter(|(c, _)| c.is_ascii_uppercase())
1285            .map(|(c, p)| (*c, *p))
1286    }
1287
1288    /// Read-only view of the cached syntax-derived block ranges that
1289    /// `:foldsyntax` consumes. Returns the slice the host last
1290    /// installed via [`Editor::set_syntax_fold_ranges`]; empty when
1291    /// no syntax integration is active.
1292    pub fn syntax_fold_ranges(&self) -> &[(usize, usize)] {
1293        &self.syntax_fold_ranges
1294    }
1295
1296    pub fn set_syntax_fold_ranges(&mut self, ranges: Vec<(usize, usize)>) {
1297        self.syntax_fold_ranges = ranges;
1298    }
1299
1300    /// Live settings (read-only). `:set` mutates these via
1301    /// [`Editor::settings_mut`].
1302    pub fn settings(&self) -> &Settings {
1303        &self.settings
1304    }
1305
1306    /// Live settings (mutable). `:set` flows through here to mutate
1307    /// shiftwidth / tabstop / textwidth / ignore_case / wrap. Hosts
1308    /// configuring at startup typically construct a [`Settings`]
1309    /// snapshot and overwrite via `*editor.settings_mut() = …`.
1310    pub fn settings_mut(&mut self) -> &mut Settings {
1311        &mut self.settings
1312    }
1313
1314    /// Set the active filetype (language name) for the current buffer.
1315    /// Used by comment-continuation and future language-aware features.
1316    /// Equivalent to `:set filetype=<lang>`. Pass `""` to clear.
1317    pub fn set_filetype(&mut self, lang: &str) {
1318        self.settings.filetype = lang.to_string();
1319    }
1320
1321    /// Returns `true` when `:set readonly` is active. Convenience
1322    /// accessor for hosts that cannot import the internal [`Settings`]
1323    /// type. Phase 5 binary uses this to gate `:w` writes.
1324    pub fn is_readonly(&self) -> bool {
1325        self.settings.readonly
1326    }
1327
1328    /// Borrow the engine search state. Hosts inspecting the
1329    /// committed `/` / `?` pattern (e.g. for status-line display) or
1330    /// feeding the active regex into `BufferView::search_pattern`
1331    /// read it from here.
1332    pub fn search_state(&self) -> &crate::search::SearchState {
1333        &self.search_state
1334    }
1335
1336    /// Mutable engine search state. Hosts driving search
1337    /// programmatically (test fixtures, scripted demos) write the
1338    /// pattern through here.
1339    pub fn search_state_mut(&mut self) -> &mut crate::search::SearchState {
1340        &mut self.search_state
1341    }
1342
1343    /// Install `pattern` as the active search regex on the engine
1344    /// state and clear the cached row matches. Pass `None` to clear.
1345    /// 0.0.37: dropped the buffer-side mirror that 0.0.35 introduced
1346    /// — `BufferView` now takes the regex through its `search_pattern`
1347    /// field per step 3 of `DESIGN_33_METHOD_CLASSIFICATION.md`.
1348    pub fn set_search_pattern(&mut self, pattern: Option<regex::Regex>) {
1349        self.search_state.set_pattern(pattern);
1350    }
1351
1352    /// Drive `n` (or the `/` commit equivalent) — advance the cursor
1353    /// to the next match of `search_state.pattern` from the cursor's
1354    /// current position. Returns `true` when a match was found.
1355    /// `skip_current = true` excludes a match the cursor sits on.
1356    pub fn search_advance_forward(&mut self, skip_current: bool) -> bool {
1357        crate::search::search_forward(&mut self.buffer, &mut self.search_state, skip_current)
1358    }
1359
1360    /// Drive `N` — symmetric counterpart of [`Editor::search_advance_forward`].
1361    pub fn search_advance_backward(&mut self, skip_current: bool) -> bool {
1362        crate::search::search_backward(&mut self.buffer, &mut self.search_state, skip_current)
1363    }
1364
1365    /// Snapshot of the unnamed register (the default `p` / `P` source).
1366    pub fn yank(&self) -> &str {
1367        &self.registers.unnamed.text
1368    }
1369
1370    /// Borrow the full register bank — `"`, `"0`–`"9`, `"a`–`"z`.
1371    pub fn registers(&self) -> &crate::registers::Registers {
1372        &self.registers
1373    }
1374
1375    /// Mutably borrow the full register bank. Hosts that share registers
1376    /// across multiple editors (e.g. multi-buffer `yy` / `p`) overwrite
1377    /// the slots here on buffer switch.
1378    pub fn registers_mut(&mut self) -> &mut crate::registers::Registers {
1379        &mut self.registers
1380    }
1381
1382    /// Host hook: load the OS clipboard's contents into the `"+` / `"*`
1383    /// register slot. the host calls this before letting vim consume a
1384    /// paste so `"*p` / `"+p` reflect the live clipboard rather than a
1385    /// stale snapshot from the last yank.
1386    pub fn sync_clipboard_register(&mut self, text: String, linewise: bool) {
1387        self.registers.set_clipboard(text, linewise);
1388    }
1389
1390    /// Return the user's pending register selection (set via `"<reg>` chord
1391    /// before an operator). `None` if no register was selected — caller should
1392    /// use the unnamed register `"`.
1393    ///
1394    /// Read-only — does not consume / clear the pending selection. The
1395    /// register is cleared by the engine after the next operator fires.
1396    ///
1397    /// Promoted in 0.6.X for Phase 4e to let the App's visual-op dispatch arm
1398    /// honor `"a` + visual op chord sequences.
1399    pub fn pending_register(&self) -> Option<char> {
1400        self.vim.pending_register
1401    }
1402
1403    /// True when the user's pending register selector is `+` or `*`.
1404    /// the host peeks this so it can refresh `sync_clipboard_register`
1405    /// only when a clipboard read is actually about to happen.
1406    pub fn pending_register_is_clipboard(&self) -> bool {
1407        matches!(self.vim.pending_register, Some('+') | Some('*'))
1408    }
1409
1410    /// Register currently being recorded into via `q{reg}`. `None` when
1411    /// no recording is active. Hosts use this to surface a "recording @r"
1412    /// indicator in the status line.
1413    pub fn recording_register(&self) -> Option<char> {
1414        self.vim.recording_macro
1415    }
1416
1417    /// Pending repeat count the user has typed but not yet resolved
1418    /// (e.g. pressing `5` before `d`). `None` when nothing is pending.
1419    /// Hosts surface this in a "showcmd" area.
1420    pub fn pending_count(&self) -> Option<u32> {
1421        self.vim.pending_count_val()
1422    }
1423
1424    /// The operator character for any in-flight operator that is waiting
1425    /// for a motion (e.g. `d` after the user types `d` but before a
1426    /// motion). Returns `None` when no operator is pending.
1427    pub fn pending_op(&self) -> Option<char> {
1428        self.vim.pending_op_char()
1429    }
1430
1431    /// `true` when the engine is in any pending chord state — waiting for
1432    /// the next key to complete a command (e.g. `r<char>` replace,
1433    /// `f<char>` find, `m<a>` set-mark, `'<a>` goto-mark, operator-pending
1434    /// after `d` / `c` / `y`, `g`-prefix continuation, `z`-prefix continuation,
1435    /// register selection `"<reg>`, macro recording target, etc).
1436    ///
1437    /// Hosts use this to bypass their own chord dispatch (keymap tries, etc.)
1438    /// and forward keys directly to the engine so in-flight commands can
1439    /// complete without the host eating their continuation keys.
1440    pub fn is_chord_pending(&self) -> bool {
1441        self.vim.is_chord_pending()
1442    }
1443
1444    /// `true` when `insert_ctrl_r_arm()` has been called and the dispatcher
1445    /// is waiting for the next typed character to name the register to paste.
1446    /// The dispatcher should call `insert_paste_register(c)` instead of
1447    /// `insert_char(c)` for the next printable key, then the flag auto-clears.
1448    ///
1449    /// Phase 6.5: exposed so the app-level `dispatch_insert_key` can branch
1450    /// without having to drive the full FSM.
1451    pub fn is_insert_register_pending(&self) -> bool {
1452        self.vim.insert_pending_register
1453    }
1454
1455    /// Clear the `Ctrl-R` register-paste pending flag. Call this immediately
1456    /// before `insert_paste_register(c)` in app-level dispatchers so that the
1457    /// flag does not persist into the next key. Call before
1458    /// `insert_paste_register_bridge` (which `hjkl_vim::insert` does).
1459    ///
1460    /// Phase 6.5: used by `dispatch_insert_key` in the app crate.
1461    pub fn clear_insert_register_pending(&mut self) {
1462        self.vim.insert_pending_register = false;
1463    }
1464
1465    /// Read-only view of the jump-back list (positions pushed on "big"
1466    /// motions). Newest entry is at the back — `Ctrl-o` pops from there.
1467    #[allow(clippy::type_complexity)]
1468    pub fn jump_list(&self) -> (&[(usize, usize)], &[(usize, usize)]) {
1469        (&self.vim.jump_back, &self.vim.jump_fwd)
1470    }
1471
1472    /// Read-only view of the change list (positions of recent edits) plus
1473    /// the current walk cursor. Newest entry is at the back.
1474    pub fn change_list(&self) -> (&[(usize, usize)], Option<usize>) {
1475        (&self.vim.change_list, self.vim.change_list_cursor)
1476    }
1477
1478    /// Replace the unnamed register without touching any other slot.
1479    /// For host-driven imports (e.g. system clipboard); operator
1480    /// code uses [`record_yank`] / [`record_delete`].
1481    pub fn set_yank(&mut self, text: impl Into<String>) {
1482        let text = text.into();
1483        let linewise = self.vim.yank_linewise;
1484        self.registers.unnamed = crate::registers::Slot { text, linewise };
1485    }
1486
1487    /// Record a yank into `"` and `"0`, plus the named target if the
1488    /// user prefixed `"reg`. Updates `vim.yank_linewise` for the
1489    /// paste path.
1490    pub(crate) fn record_yank(&mut self, text: String, linewise: bool) {
1491        self.vim.yank_linewise = linewise;
1492        let target = self.vim.pending_register.take();
1493        self.registers.record_yank(text, linewise, target);
1494    }
1495
1496    /// Direct write to a named register slot — bypasses the unnamed
1497    /// `"` and `"0` updates that `record_yank` does. Used by the
1498    /// macro recorder so finishing a `q{reg}` recording doesn't
1499    /// pollute the user's last yank.
1500    pub fn set_named_register_text(&mut self, reg: char, text: String) {
1501        if let Some(slot) = match reg {
1502            'a'..='z' => Some(&mut self.registers.named[(reg as u8 - b'a') as usize]),
1503            'A'..='Z' => {
1504                Some(&mut self.registers.named[(reg.to_ascii_lowercase() as u8 - b'a') as usize])
1505            }
1506            _ => None,
1507        } {
1508            slot.text = text;
1509            slot.linewise = false;
1510        }
1511    }
1512
1513    /// Record a delete / change into `"` and the `"1`–`"9` ring.
1514    /// Honours the active named-register prefix.
1515    pub(crate) fn record_delete(&mut self, text: String, linewise: bool) {
1516        self.vim.yank_linewise = linewise;
1517        let target = self.vim.pending_register.take();
1518        self.registers.record_delete(text, linewise, target);
1519    }
1520
1521    /// Install styled syntax spans using the engine-native
1522    /// [`crate::types::Style`]. Always available — engine is ratatui-free.
1523    /// Ratatui hosts use
1524    /// `hjkl_engine_tui::EditorRatatuiExt::install_ratatui_syntax_spans`
1525    /// which converts at the boundary and delegates here.
1526    ///
1527    /// Renamed from `install_engine_syntax_spans` in 0.0.32 — at the
1528    /// 0.1.0 freeze the unprefixed name is the universally-available
1529    /// engine-native variant.
1530    pub fn install_syntax_spans(&mut self, spans: Vec<Vec<(usize, usize, crate::types::Style)>>) {
1531        // Note: do NOT pre-collect `line_byte_lens` here. `buf_line` clones
1532        // the row string under a content-mutex lock; pre-collecting for
1533        // every row turns a 10k-row file's install into 10k mutex-locked
1534        // String clones (visible as j/k cursor lag). The typical install
1535        // has spans on at most a few hundred rows (the parsed viewport
1536        // window); lazy lookup keeps the cost proportional to populated
1537        // rows, not file size.
1538        let mut by_row: Vec<Vec<hjkl_buffer::Span>> = Vec::with_capacity(spans.len());
1539        let mut engine_spans: Vec<Vec<(usize, usize, crate::types::Style)>> =
1540            Vec::with_capacity(spans.len());
1541        for (row, row_spans) in spans.iter().enumerate() {
1542            if row_spans.is_empty() {
1543                by_row.push(Vec::new());
1544                engine_spans.push(Vec::new());
1545                continue;
1546            }
1547            let line_len = buf_line(&self.buffer, row).map(|s| s.len()).unwrap_or(0);
1548            let mut translated = Vec::with_capacity(row_spans.len());
1549            let mut translated_e = Vec::with_capacity(row_spans.len());
1550            for (start, end, style) in row_spans {
1551                let end_clamped = (*end).min(line_len);
1552                if end_clamped <= *start {
1553                    continue;
1554                }
1555                let id = self.intern_style(*style);
1556                translated.push(hjkl_buffer::Span::new(*start, end_clamped, id));
1557                translated_e.push((*start, end_clamped, *style));
1558            }
1559            by_row.push(translated);
1560            engine_spans.push(translated_e);
1561        }
1562        self.buffer_spans = by_row;
1563        self.styled_spans = engine_spans;
1564    }
1565
1566    /// Patch only `rows` of the installed `buffer_spans` / `styled_spans`,
1567    /// leaving rows outside that range untouched. `spans` is indexed by
1568    /// row offset within `rows` — `spans[0]` is for `rows.start`,
1569    /// `spans[1]` for `rows.start + 1`, etc.
1570    ///
1571    /// Use this instead of [`Self::install_syntax_spans`] when a sync
1572    /// `query_viewport` produced spans for the visible region only.
1573    /// Walking the full `line_count` and re-installing every row on
1574    /// every j/k that nudges the viewport dominated the per-keystroke
1575    /// cost on large files; patching just the changed range keeps the
1576    /// cost proportional to viewport size, not file size.
1577    ///
1578    /// Ensures `buffer_spans` / `styled_spans` are sized to the buffer's
1579    /// current `line_count` (resizes if a row-count edit shifted them).
1580    pub fn patch_syntax_spans_range(
1581        &mut self,
1582        rows: std::ops::Range<usize>,
1583        spans: &[Vec<(usize, usize, crate::types::Style)>],
1584    ) {
1585        let line_count = buf_row_count(&self.buffer);
1586        if self.buffer_spans.len() != line_count {
1587            self.buffer_spans.resize_with(line_count, Vec::new);
1588        }
1589        if self.styled_spans.len() != line_count {
1590            self.styled_spans.resize_with(line_count, Vec::new);
1591        }
1592        for (i, row_spans) in spans.iter().enumerate() {
1593            let row = rows.start + i;
1594            if row >= line_count {
1595                break;
1596            }
1597            if row_spans.is_empty() {
1598                self.buffer_spans[row] = Vec::new();
1599                self.styled_spans[row] = Vec::new();
1600                continue;
1601            }
1602            let line_len = buf_line(&self.buffer, row).map(|s| s.len()).unwrap_or(0);
1603            let mut translated = Vec::with_capacity(row_spans.len());
1604            let mut translated_e = Vec::with_capacity(row_spans.len());
1605            for (start, end, style) in row_spans {
1606                let end_clamped = (*end).min(line_len);
1607                if end_clamped <= *start {
1608                    continue;
1609                }
1610                let id = self.intern_style(*style);
1611                translated.push(hjkl_buffer::Span::new(*start, end_clamped, id));
1612                translated_e.push((*start, end_clamped, *style));
1613            }
1614            self.buffer_spans[row] = translated;
1615            self.styled_spans[row] = translated_e;
1616        }
1617    }
1618
1619    /// Translate the cached `buffer_spans` / `styled_spans` row indices
1620    /// in-place to track a batch of [`crate::types::ContentEdit`]s without
1621    /// blanking the cache.
1622    ///
1623    /// Why: spans are installed by the async syntax worker, which can lag
1624    /// the buffer by one or more frames after an edit. If the edit changes
1625    /// the row count and we keep the old span rows in place, the renderer
1626    /// paints last-frame's spans at the wrong line — visibly garbled colours.
1627    /// The historical fix was to blank `buffer_spans` whenever a row-count
1628    /// change came through, but that produces a white flash on every Enter
1629    /// or backspace-at-BOL.
1630    ///
1631    /// What this does instead: for each edit, insert empty span rows where
1632    /// the edit grew the buffer and drain rows where it shrank, so the
1633    /// surviving rows still index the right line. Spans on the edited row
1634    /// itself stay (they'll show stale colours for that one row until the
1635    /// worker delivers a fresh parse, which is invisible compared to the
1636    /// blank flash).
1637    ///
1638    /// Edits are applied in order — each edit's `(row, col)` positions are
1639    /// taken to be relative to the post-state of the prior edits in the
1640    /// batch (matching the order the engine emitted them).
1641    pub fn shift_syntax_spans_for_edits(&mut self, edits: &[crate::types::ContentEdit]) {
1642        for edit in edits {
1643            let oer = edit.old_end_position.0 as usize;
1644            let ner = edit.new_end_position.0 as usize;
1645            if ner == oer {
1646                continue;
1647            }
1648            let start_row = edit.start_position.0 as usize;
1649            let start_col = edit.start_position.1 as usize;
1650            // Insert/drain index depends on whether the edit starts at
1651            // the BEGINNING of `start_row` or somewhere INSIDE it.
1652            //   col == 0 → edit is at the very start of `start_row`; new
1653            //              rows go BEFORE row `start_row`, so the affected
1654            //              indices begin AT `start_row`.
1655            //   col > 0 → edit is inside `start_row`; new rows go AFTER
1656            //              `start_row`, so affected indices begin at
1657            //              `start_row + 1`.
1658            //
1659            // Pre-fix this always used `oer + 1` (the col-> 0 branch),
1660            // which left row `start_row`'s spans at its old index while
1661            // the file's row `start_row` was now the freshly-pasted
1662            // content — visible as wrong-row colour mappings after
1663            // `ggP` / `P` / any insert at column 0.
1664            let affected_idx = if start_col == 0 {
1665                start_row
1666            } else {
1667                start_row + 1
1668            };
1669            if ner > oer {
1670                let n = ner - oer;
1671                // O(len + n) via splice; the prior per-row `insert(idx, ...)`
1672                // loop was O(n × (len - idx)), which on a 60k-row paste at
1673                // the BOL became ~1.8 G memmove ops (87 % of paste CPU per
1674                // samply). Splice memmove-shifts once, then fills.
1675                let idx = affected_idx.min(self.buffer_spans.len());
1676                self.buffer_spans
1677                    .splice(idx..idx, std::iter::repeat_with(Vec::new).take(n));
1678                let idx_s = affected_idx.min(self.styled_spans.len());
1679                self.styled_spans
1680                    .splice(idx_s..idx_s, std::iter::repeat_with(Vec::new).take(n));
1681            } else {
1682                let n = oer - ner;
1683                let len_b = self.buffer_spans.len();
1684                let start_b = affected_idx.min(len_b);
1685                let end_b = (start_b + n).min(len_b);
1686                if end_b > start_b {
1687                    self.buffer_spans.drain(start_b..end_b);
1688                }
1689                let len_s = self.styled_spans.len();
1690                let start_s = affected_idx.min(len_s);
1691                let end_s = (start_s + n).min(len_s);
1692                if end_s > start_s {
1693                    self.styled_spans.drain(start_s..end_s);
1694                }
1695            }
1696        }
1697    }
1698
1699    /// Read-only view of the style table in engine-native form —
1700    /// id `i` → `style_table[i]`. Always available, no cfg gate.
1701    ///
1702    /// Ratatui hosts that need a `ratatui::style::Style` slice should
1703    /// use `hjkl_engine_tui::EditorRatatuiExt::ratatui_style_table` or
1704    /// convert individual entries via `hjkl_engine_tui::style_to_ratatui`.
1705    pub fn style_table(&self) -> &[crate::types::Style] {
1706        &self.style_table
1707    }
1708
1709    /// Per-row syntax span overlay, one `Vec<Span>` per buffer row.
1710    /// Hosts feed this slice into [`hjkl_buffer::BufferView::spans`]
1711    /// per draw frame.
1712    ///
1713    /// 0.0.37: replaces `editor.buffer().spans()` per step 3 of
1714    /// `DESIGN_33_METHOD_CLASSIFICATION.md`. The buffer no longer
1715    /// caches spans; they live on the engine and route through the
1716    /// `Host::syntax_highlights` pipeline.
1717    pub fn buffer_spans(&self) -> &[Vec<hjkl_buffer::Span>] {
1718        &self.buffer_spans
1719    }
1720
1721    /// Intern a SPEC [`crate::types::Style`] and return its opaque id.
1722    /// Engine-native — the unified `style_table` is always engine-native.
1723    /// Linear-scan dedup — the table grows only as new tree-sitter token
1724    /// kinds appear, so it stays tiny. Ratatui callers use
1725    /// `hjkl_engine_tui::EditorRatatuiExt::intern_ratatui_style` which
1726    /// converts at the boundary and delegates here.
1727    ///
1728    /// Renamed from `intern_engine_style` in 0.0.32 — at 0.1.0 freeze
1729    /// the unprefixed name is the universally-available engine-native
1730    /// variant.
1731    pub fn intern_style(&mut self, style: crate::types::Style) -> u32 {
1732        if let Some(idx) = self.style_table.iter().position(|s| *s == style) {
1733            return idx as u32;
1734        }
1735        self.style_table.push(style);
1736        (self.style_table.len() - 1) as u32
1737    }
1738
1739    /// Look up an interned style by id and return it as a SPEC
1740    /// [`crate::types::Style`]. Returns `None` for ids past the end
1741    /// of the table.
1742    pub fn engine_style_at(&self, id: u32) -> Option<crate::types::Style> {
1743        self.style_table.get(id as usize).copied()
1744    }
1745
1746    /// Historical reverse-sync hook from when the textarea mirrored
1747    /// the buffer. Now that Buffer is the cursor authority this is a
1748    /// no-op; call sites can remain in place during the migration.
1749    pub fn push_buffer_cursor_to_textarea(&mut self) {}
1750
1751    /// Force the host viewport's top row without touching the
1752    /// cursor. Used by tests that simulate a scroll without the
1753    /// SCROLLOFF cursor adjustment that `scroll_down` / `scroll_up`
1754    /// apply.
1755    ///
1756    /// 0.0.34 (Patch C-δ.1): writes through `Host::viewport_mut`
1757    /// instead of the (now-deleted) `Buffer::viewport_mut`.
1758    pub fn set_viewport_top(&mut self, row: usize) {
1759        let last = buf_row_count(&self.buffer).saturating_sub(1);
1760        let target = row.min(last);
1761        self.host.viewport_mut().top_row = target;
1762    }
1763
1764    /// Set the cursor to `(row, col)`, clamped to the buffer's
1765    /// content. Hosts use this for goto-line, jump-to-mark, and
1766    /// programmatic cursor placement.
1767    ///
1768    /// Resets `sticky_col` (curswant) to `col` — every explicit jump
1769    /// (goto-line, jump-to-mark, search hit, click, `]d`) follows vim
1770    /// semantics. Only `j`/`k`/`+`/`-` READ `sticky_col`; everything
1771    /// else resets it to the column where the cursor actually landed.
1772    pub fn jump_cursor(&mut self, row: usize, col: usize) {
1773        buf_set_cursor_rc(&mut self.buffer, row, col);
1774        self.sticky_col = Some(col);
1775    }
1776
1777    /// Set the cursor to `(row, col)` without modifying `sticky_col`.
1778    ///
1779    /// Use this for host-side state restores (viewport sync, snapshot
1780    /// replay) where the cursor was already at this position semantically
1781    /// and the host's sticky tracking should remain authoritative.
1782    ///
1783    /// For user-facing jumps (goto-line, search hit, picker `<CR>`, `]d`,
1784    /// click), use [`Editor::jump_cursor`] which DOES reset `sticky_col`
1785    /// per vim curswant semantics.
1786    pub fn set_cursor_quiet(&mut self, row: usize, col: usize) {
1787        buf_set_cursor_rc(&mut self.buffer, row, col);
1788    }
1789
1790    /// `(row, col)` cursor read sourced from the migration buffer.
1791    /// Equivalent to `self.textarea.cursor()` when the two are in
1792    /// sync — which is the steady state during Phase 7f because
1793    /// every step opens with `sync_buffer_content_from_textarea` and
1794    /// every ported motion pushes the result back. Prefer this over
1795    /// `self.textarea.cursor()` so call sites keep working unchanged
1796    /// once the textarea field is ripped.
1797    pub fn cursor(&self) -> (usize, usize) {
1798        buf_cursor_rc(&self.buffer)
1799    }
1800
1801    /// Drain any pending LSP intent raised by the last key. Returns
1802    /// `None` when no intent is armed.
1803    pub fn take_lsp_intent(&mut self) -> Option<LspIntent> {
1804        self.pending_lsp.take()
1805    }
1806
1807    /// Drain every [`crate::types::FoldOp`] raised since the last
1808    /// call. Hosts that mirror the engine's fold storage (or that
1809    /// project folds onto a separate fold tree, LSP folding ranges,
1810    /// …) drain this each step and dispatch as their own
1811    /// [`crate::types::Host::Intent`] requires.
1812    ///
1813    /// The engine has already applied every op locally against the
1814    /// in-tree [`hjkl_buffer::Buffer`] fold storage via
1815    /// [`crate::buffer_impl::BufferFoldProviderMut`], so hosts that
1816    /// don't track folds independently can ignore the queue
1817    /// (or simply never call this drain).
1818    ///
1819    /// Introduced in 0.0.38 (Patch C-δ.4).
1820    pub fn take_fold_ops(&mut self) -> Vec<crate::types::FoldOp> {
1821        std::mem::take(&mut self.pending_fold_ops)
1822    }
1823
1824    /// Dispatch a [`crate::types::FoldOp`] through the canonical fold
1825    /// surface: queue it for host observation (drained by
1826    /// [`Editor::take_fold_ops`]) and apply it locally against the
1827    /// in-tree buffer fold storage via
1828    /// [`crate::buffer_impl::BufferFoldProviderMut`]. Engine call sites
1829    /// (vim FSM `z…` chords, `:fold*` Ex commands, edit-pipeline
1830    /// invalidation) route every fold mutation through this method.
1831    ///
1832    /// Introduced in 0.0.38 (Patch C-δ.4).
1833    pub fn apply_fold_op(&mut self, op: crate::types::FoldOp) {
1834        use crate::types::FoldProvider;
1835        self.pending_fold_ops.push(op);
1836        let mut provider = crate::buffer_impl::BufferFoldProviderMut::new(&mut self.buffer);
1837        provider.apply(op);
1838    }
1839
1840    /// Refresh the host viewport's height from the cached
1841    /// `viewport_height_value()`. Called from the per-step
1842    /// boilerplate; was the textarea → buffer mirror before Phase 7f
1843    /// put Buffer in charge. 0.0.28 hoisted sticky_col out of
1844    /// `Buffer`. 0.0.34 (Patch C-δ.1) routes the height write through
1845    /// `Host::viewport_mut`.
1846    pub fn sync_buffer_from_textarea(&mut self) {
1847        let height = self.viewport_height_value();
1848        self.host.viewport_mut().height = height;
1849    }
1850
1851    /// Was the full textarea → buffer content sync. Buffer is the
1852    /// content authority now; this remains as a no-op so the per-step
1853    /// call sites don't have to be ripped in the same patch.
1854    pub(crate) fn sync_buffer_content_from_textarea(&mut self) {
1855        self.sync_buffer_from_textarea();
1856    }
1857
1858    /// Push a `(row, col)` onto the back-jumplist so `Ctrl-o` returns
1859    /// to it later. Used by host-driven jumps (e.g. `gd`) that move
1860    /// the cursor without going through the vim engine's motion
1861    /// machinery, where push_jump fires automatically.
1862    pub fn record_jump(&mut self, pos: (usize, usize)) {
1863        const JUMPLIST_MAX: usize = 100;
1864        self.vim.jump_back.push(pos);
1865        if self.vim.jump_back.len() > JUMPLIST_MAX {
1866            self.vim.jump_back.remove(0);
1867        }
1868        self.vim.jump_fwd.clear();
1869    }
1870
1871    /// Host apps call this each draw with the current text area height so
1872    /// scroll helpers can clamp the cursor without recomputing layout.
1873    pub fn set_viewport_height(&self, height: u16) {
1874        self.viewport_height.store(height, Ordering::Relaxed);
1875    }
1876
1877    /// Last height published by `set_viewport_height` (in rows).
1878    pub fn viewport_height_value(&self) -> u16 {
1879        self.viewport_height.load(Ordering::Relaxed)
1880    }
1881
1882    /// Apply `edit` against the buffer and return the inverse so the
1883    /// host can push it onto an undo stack. Side effects: dirty
1884    /// flag, change-list ring, mark / jump-list shifts, change_log
1885    /// append, fold invalidation around the touched rows.
1886    ///
1887    /// The primary edit funnel — both FSM operators and ex commands
1888    /// route mutations through here so the side effects fire
1889    /// uniformly.
1890    pub fn mutate_edit(&mut self, edit: hjkl_buffer::Edit) -> hjkl_buffer::Edit {
1891        // `:set readonly` short-circuits every mutation funnel: no
1892        // buffer change, no dirty flag, no undo entry, no change-log
1893        // emission. We swallow the requested `edit` and hand back a
1894        // self-inverse no-op (`InsertStr` of an empty string at the
1895        // current cursor) so callers that push the return value onto
1896        // an undo stack still get a structurally valid round trip.
1897        if self.settings.readonly {
1898            let _ = edit;
1899            return hjkl_buffer::Edit::InsertStr {
1900                at: buf_cursor_pos(&self.buffer),
1901                text: String::new(),
1902            };
1903        }
1904        let pre_row = buf_cursor_row(&self.buffer);
1905        let pre_rows = buf_row_count(&self.buffer);
1906        // Capture the pre-edit cursor for the dot mark (`'.` / `` `. ``).
1907        // Vim's `:h '.` says "the position where the last change was made",
1908        // meaning the change-start, not the post-insert cursor. We snap it
1909        // here before `apply_buffer_edit` moves the cursor.
1910        let (pre_edit_row, pre_edit_col) = buf_cursor_rc(&self.buffer);
1911        // Map the underlying buffer edit to a SPEC EditOp for
1912        // change-log emission before consuming it. Coarse — see
1913        // change_log field doc on the struct.
1914        self.change_log.extend(edit_to_editops(&edit));
1915        // Compute ContentEdit fan-out from the pre-edit buffer state.
1916        // Done before `apply_buffer_edit` consumes `edit` so we can
1917        // inspect the operation's fields and the buffer's pre-edit row
1918        // bytes (needed for byte_of_row / col_byte conversion). Edits
1919        // are pushed onto `pending_content_edits` for host drain.
1920        let content_edits = content_edits_from_buffer_edit(&self.buffer, &edit);
1921        self.pending_content_edits.extend(content_edits);
1922        // 0.0.42 (Patch C-δ.7): the `apply_edit` reach is centralized
1923        // in [`crate::buf_helpers::apply_buffer_edit`] (option (c) of
1924        // the 0.0.42 plan — see that fn's doc comment). The free fn
1925        // takes `&mut hjkl_buffer::Buffer` so the editor body itself
1926        // no longer carries a `self.buffer.<inherent>` hop.
1927        let inverse = apply_buffer_edit(&mut self.buffer, edit);
1928        let (pos_row, pos_col) = buf_cursor_rc(&self.buffer);
1929        // Drop any folds the edit's range overlapped — vim opens the
1930        // surrounding fold automatically when you edit inside it. The
1931        // approximation here invalidates folds covering either the
1932        // pre-edit cursor row or the post-edit cursor row, which
1933        // catches the common single-line / multi-line edit shapes.
1934        let lo = pre_row.min(pos_row);
1935        let hi = pre_row.max(pos_row);
1936        self.apply_fold_op(crate::types::FoldOp::Invalidate {
1937            start_row: lo,
1938            end_row: hi,
1939        });
1940        // Dot mark records the PRE-edit position (change start), matching
1941        // vim's `:h '.` semantics. Previously this stored the post-edit
1942        // cursor, which diverged from nvim on `iX<Esc>j`.
1943        self.vim.last_edit_pos = Some((pre_edit_row, pre_edit_col));
1944        // Append to the change-list ring (skip when the cursor sits on
1945        // the same cell as the last entry — back-to-back keystrokes on
1946        // one column shouldn't pollute the ring). A new edit while
1947        // walking the ring trims the forward half, vim style.
1948        let entry = (pos_row, pos_col);
1949        if self.vim.change_list.last() != Some(&entry) {
1950            if let Some(idx) = self.vim.change_list_cursor.take() {
1951                self.vim.change_list.truncate(idx + 1);
1952            }
1953            self.vim.change_list.push(entry);
1954            let len = self.vim.change_list.len();
1955            if len > crate::vim::CHANGE_LIST_MAX {
1956                self.vim
1957                    .change_list
1958                    .drain(0..len - crate::vim::CHANGE_LIST_MAX);
1959            }
1960        }
1961        self.vim.change_list_cursor = None;
1962        // Shift / drop marks + jump-list entries to track the row
1963        // delta the edit produced. Without this, every line-changing
1964        // edit silently invalidates `'a`-style positions.
1965        let post_rows = buf_row_count(&self.buffer);
1966        let delta = post_rows as isize - pre_rows as isize;
1967        if delta != 0 {
1968            self.shift_marks_after_edit(pre_row, delta);
1969        }
1970        self.push_buffer_content_to_textarea();
1971        self.mark_content_dirty();
1972        inverse
1973    }
1974
1975    /// Migrate user marks + jumplist entries when an edit at row
1976    /// `edit_start` changes the buffer's row count by `delta` (positive
1977    /// for inserts, negative for deletes). Marks tied to a deleted row
1978    /// are dropped; marks past the affected band shift by `delta`.
1979    fn shift_marks_after_edit(&mut self, edit_start: usize, delta: isize) {
1980        if delta == 0 {
1981            return;
1982        }
1983        // Deleted-row band (only meaningful for delta < 0). Inclusive
1984        // start, exclusive end.
1985        let drop_end = if delta < 0 {
1986            edit_start.saturating_add((-delta) as usize)
1987        } else {
1988            edit_start
1989        };
1990        let shift_threshold = drop_end.max(edit_start.saturating_add(1));
1991
1992        // 0.0.36: lowercase + uppercase marks share the unified
1993        // `marks` map; one pass migrates both.
1994        let mut to_drop: Vec<char> = Vec::new();
1995        for (c, (row, _col)) in self.marks.iter_mut() {
1996            if (edit_start..drop_end).contains(row) {
1997                to_drop.push(*c);
1998            } else if *row >= shift_threshold {
1999                *row = ((*row as isize) + delta).max(0) as usize;
2000            }
2001        }
2002        for c in to_drop {
2003            self.marks.remove(&c);
2004        }
2005
2006        // Shift global marks that belong to the current buffer.
2007        let cur_bid = self.current_buffer_id;
2008        let mut global_to_drop: Vec<char> = Vec::new();
2009        for (c, (bid, row, _col)) in self.global_marks.iter_mut() {
2010            if *bid != cur_bid {
2011                continue;
2012            }
2013            if (edit_start..drop_end).contains(row) {
2014                global_to_drop.push(*c);
2015            } else if *row >= shift_threshold {
2016                *row = ((*row as isize) + delta).max(0) as usize;
2017            }
2018        }
2019        for c in global_to_drop {
2020            self.global_marks.remove(&c);
2021        }
2022
2023        let shift_jumps = |entries: &mut Vec<(usize, usize)>| {
2024            entries.retain(|(row, _)| !(edit_start..drop_end).contains(row));
2025            for (row, _) in entries.iter_mut() {
2026                if *row >= shift_threshold {
2027                    *row = ((*row as isize) + delta).max(0) as usize;
2028                }
2029            }
2030        };
2031        shift_jumps(&mut self.vim.jump_back);
2032        shift_jumps(&mut self.vim.jump_fwd);
2033    }
2034
2035    /// Reverse-sync helper paired with [`Editor::mutate_edit`]: rebuild
2036    /// the textarea from the buffer's lines + cursor, preserving yank
2037    /// text. Heavy (allocates a fresh `TextArea`) but correct; the
2038    /// textarea field disappears at the end of Phase 7f anyway.
2039    /// No-op since Buffer is the content authority. Retained as a
2040    /// shim so call sites in `mutate_edit` and friends don't have to
2041    /// be ripped in lockstep with the field removal.
2042    pub(crate) fn push_buffer_content_to_textarea(&mut self) {}
2043
2044    /// Single choke-point for "the buffer just changed". Sets the
2045    /// dirty flag and drops the cached `content_arc` snapshot so
2046    /// subsequent reads rebuild from the live textarea. Callers
2047    /// mutating `textarea` directly (e.g. the TUI's bracketed-paste
2048    /// path) must invoke this to keep the cache honest.
2049    pub fn mark_content_dirty(&mut self) {
2050        self.content_dirty = true;
2051        self.cached_content = None;
2052    }
2053
2054    /// Returns true if content changed since the last call, then clears the flag.
2055    pub fn take_dirty(&mut self) -> bool {
2056        let dirty = self.content_dirty;
2057        self.content_dirty = false;
2058        dirty
2059    }
2060
2061    /// Drain the queue of [`crate::types::ContentEdit`]s emitted since
2062    /// the last call. Each entry corresponds to a single buffer
2063    /// mutation funnelled through [`Editor::mutate_edit`]; block edits
2064    /// fan out to one entry per row touched.
2065    ///
2066    /// Hosts call this each frame (after [`Editor::take_content_reset`])
2067    /// to fan edits into a tree-sitter parser via `Tree::edit`.
2068    pub fn take_content_edits(&mut self) -> Vec<crate::types::ContentEdit> {
2069        std::mem::take(&mut self.pending_content_edits)
2070    }
2071
2072    /// Returns `true` if a bulk buffer replacement happened since the
2073    /// last call (e.g. `set_content` / `restore` / undo restore), then
2074    /// clears the flag. When this returns `true`, hosts should drop
2075    /// any retained syntax tree before consuming
2076    /// [`Editor::take_content_edits`].
2077    pub fn take_content_reset(&mut self) -> bool {
2078        let r = self.pending_content_reset;
2079        self.pending_content_reset = false;
2080        r
2081    }
2082
2083    /// Pull-model coarse change observation. If content changed since
2084    /// the last call, returns `Some(Arc<String>)` with the new content
2085    /// and clears the dirty flag; otherwise returns `None`.
2086    ///
2087    /// Hosts that need fine-grained edit deltas (e.g., DOM patching at
2088    /// the character level) should diff against their own previous
2089    /// snapshot. The SPEC `take_changes() -> Vec<EditOp>` API lands
2090    /// once every edit path inside the engine is instrumented; this
2091    /// coarse form covers the pull-model use case in the meantime.
2092    pub fn take_content_change(&mut self) -> Option<std::sync::Arc<String>> {
2093        if !self.content_dirty {
2094            return None;
2095        }
2096        let arc = self.content_arc();
2097        self.content_dirty = false;
2098        Some(arc)
2099    }
2100
2101    /// Width in cells of the line-number gutter for the current buffer
2102    /// and settings. Matches what [`Editor::cursor_screen_pos`] reserves
2103    /// in front of the text column. Returns `0` when both `number` and
2104    /// `relativenumber` are off.
2105    pub fn lnum_width(&self) -> u16 {
2106        if self.settings.number || self.settings.relativenumber {
2107            let needed = buf_row_count(&self.buffer).to_string().len() + 1;
2108            needed.max(self.settings.numberwidth) as u16
2109        } else {
2110            0
2111        }
2112    }
2113
2114    /// Returns the cursor's row within the visible textarea (0-based), updating
2115    /// the stored viewport top so subsequent calls remain accurate.
2116    pub fn cursor_screen_row(&mut self, height: u16) -> u16 {
2117        let cursor = buf_cursor_row(&self.buffer);
2118        let top = self.host.viewport().top_row;
2119        cursor.saturating_sub(top).min(height as usize - 1) as u16
2120    }
2121
2122    /// Returns the cursor's screen position `(x, y)` for the textarea
2123    /// described by `(area_x, area_y, area_width, area_height)`.
2124    /// Accounts for line-number gutter, viewport scroll, and any extra
2125    /// gutter width to the left of the number column (sign column, fold
2126    /// column). Returns `None` if the cursor is outside the visible
2127    /// viewport. Always available (engine-native; no ratatui dependency).
2128    ///
2129    /// `extra_gutter_width` is added to the number-column width before
2130    /// computing the cursor x position. Callers (e.g. `apps/hjkl/src/render.rs`)
2131    /// pass `sign_w + fold_w` here so the cursor lands on the correct cell
2132    /// when a dedicated sign or fold column is present.
2133    ///
2134    /// Renamed from `cursor_screen_pos_xywh` in 0.0.32.
2135    pub fn cursor_screen_pos(
2136        &self,
2137        area_x: u16,
2138        area_y: u16,
2139        area_width: u16,
2140        area_height: u16,
2141        extra_gutter_width: u16,
2142    ) -> Option<(u16, u16)> {
2143        let (pos_row, pos_col) = buf_cursor_rc(&self.buffer);
2144        let v = self.host.viewport();
2145        if pos_row < v.top_row || pos_col < v.top_col {
2146            return None;
2147        }
2148        let lnum_width = self.lnum_width();
2149        // Full offset from the left edge of the window to the first text cell.
2150        let gutter_total = lnum_width + extra_gutter_width;
2151        let dy = (pos_row - v.top_row) as u16;
2152        // Convert char column to visual column so cursor lands on the
2153        // correct cell when the line contains tabs (which the renderer
2154        // expands to TAB_WIDTH stops). Tab width must match the renderer.
2155        let cursor_rope = self.buffer.rope();
2156        let pos_row_safe = pos_row.min(cursor_rope.len_lines().saturating_sub(1));
2157        let line = hjkl_buffer::rope_line_str(&cursor_rope, pos_row_safe);
2158        let tab_width = if v.tab_width == 0 {
2159            4
2160        } else {
2161            v.tab_width as usize
2162        };
2163        let visual_pos = visual_col_for_char(&line, pos_col, tab_width);
2164        let visual_top = visual_col_for_char(&line, v.top_col, tab_width);
2165        let dx = (visual_pos - visual_top) as u16;
2166        if dy >= area_height || dx + gutter_total >= area_width {
2167            return None;
2168        }
2169        Some((area_x + gutter_total + dx, area_y + dy))
2170    }
2171
2172    /// Returns the current vim mode. Phase 6.3: reads from the stable
2173    /// `current_mode` field (kept in sync by both the FSM step loop and
2174    /// the Phase 6.3 primitive bridges) rather than deriving from the
2175    /// FSM-internal `mode` field via `public_mode()`.
2176    pub fn vim_mode(&self) -> VimMode {
2177        self.vim.current_mode
2178    }
2179
2180    /// Bounds of the active visual-block rectangle as
2181    /// `(top_row, bot_row, left_col, right_col)` — all inclusive.
2182    /// `None` when we're not in VisualBlock mode.
2183    /// Read-only view of the live `/` or `?` prompt. `None` outside
2184    /// search-prompt mode.
2185    pub fn search_prompt(&self) -> Option<&crate::vim::SearchPrompt> {
2186        self.vim.search_prompt.as_ref()
2187    }
2188
2189    /// Most recent committed search pattern (persists across `n` / `N`
2190    /// and across prompt exits). `None` before the first search.
2191    pub fn last_search(&self) -> Option<&str> {
2192        self.vim.last_search.as_deref()
2193    }
2194
2195    /// Whether the last committed search was a forward `/` (`true`) or
2196    /// a backward `?` (`false`). `n` and `N` consult this to honour the
2197    /// direction the user committed.
2198    pub fn last_search_forward(&self) -> bool {
2199        self.vim.last_search_forward
2200    }
2201
2202    /// Set the most recent committed search text + direction. Used by
2203    /// host-driven prompts (e.g. apps/hjkl's `/` `?` prompt that lives
2204    /// outside the engine's vim FSM) so `n` / `N` repeat the host's
2205    /// most recent commit with the right direction. Pass `None` /
2206    /// `true` to clear.
2207    pub fn set_last_search(&mut self, text: Option<String>, forward: bool) {
2208        self.vim.last_search = text;
2209        self.vim.last_search_forward = forward;
2210    }
2211
2212    /// The most recent successful `:s` command. `None` before the first substitute.
2213    /// Used by `:&` / `:&&` to repeat it.
2214    pub fn last_substitute(&self) -> Option<&crate::substitute::SubstituteCmd> {
2215        self.vim.last_substitute.as_ref()
2216    }
2217
2218    /// Store the last successful substitute so `:&` / `:&&` can repeat it.
2219    pub fn set_last_substitute(&mut self, cmd: crate::substitute::SubstituteCmd) {
2220        self.vim.last_substitute = Some(cmd);
2221    }
2222
2223    /// Start/end `(row, col)` of the active char-wise Visual selection
2224    /// (inclusive on both ends, positionally ordered). `None` when not
2225    /// in Visual mode.
2226    pub fn char_highlight(&self) -> Option<((usize, usize), (usize, usize))> {
2227        if self.vim_mode() != VimMode::Visual {
2228            return None;
2229        }
2230        let anchor = self.vim.visual_anchor;
2231        let cursor = self.cursor();
2232        let (start, end) = if anchor <= cursor {
2233            (anchor, cursor)
2234        } else {
2235            (cursor, anchor)
2236        };
2237        Some((start, end))
2238    }
2239
2240    /// Top/bottom rows of the active VisualLine selection (inclusive).
2241    /// `None` when we're not in VisualLine mode.
2242    pub fn line_highlight(&self) -> Option<(usize, usize)> {
2243        if self.vim_mode() != VimMode::VisualLine {
2244            return None;
2245        }
2246        let anchor = self.vim.visual_line_anchor;
2247        let cursor = buf_cursor_row(&self.buffer);
2248        Some((anchor.min(cursor), anchor.max(cursor)))
2249    }
2250
2251    pub fn block_highlight(&self) -> Option<(usize, usize, usize, usize)> {
2252        if self.vim_mode() != VimMode::VisualBlock {
2253            return None;
2254        }
2255        let (ar, ac) = self.vim.block_anchor;
2256        let cr = buf_cursor_row(&self.buffer);
2257        let cc = self.vim.block_vcol;
2258        let top = ar.min(cr);
2259        let bot = ar.max(cr);
2260        let left = ac.min(cc);
2261        let right = ac.max(cc);
2262        Some((top, bot, left, right))
2263    }
2264
2265    /// Active selection in `hjkl_buffer::Selection` shape. `None` when
2266    /// not in a Visual mode. Phase 7d-i wiring — the host hands this
2267    /// straight to `BufferView` once render flips off textarea
2268    /// (Phase 7d-ii drops the `paint_*_overlay` calls on the same
2269    /// switch).
2270    pub fn buffer_selection(&self) -> Option<hjkl_buffer::Selection> {
2271        use hjkl_buffer::{Position, Selection};
2272        match self.vim_mode() {
2273            VimMode::Visual => {
2274                let (ar, ac) = self.vim.visual_anchor;
2275                let head = buf_cursor_pos(&self.buffer);
2276                Some(Selection::Char {
2277                    anchor: Position::new(ar, ac),
2278                    head,
2279                })
2280            }
2281            VimMode::VisualLine => {
2282                let anchor_row = self.vim.visual_line_anchor;
2283                let head_row = buf_cursor_row(&self.buffer);
2284                Some(Selection::Line {
2285                    anchor_row,
2286                    head_row,
2287                })
2288            }
2289            VimMode::VisualBlock => {
2290                let (ar, ac) = self.vim.block_anchor;
2291                let cr = buf_cursor_row(&self.buffer);
2292                let cc = self.vim.block_vcol;
2293                Some(Selection::Block {
2294                    anchor: Position::new(ar, ac),
2295                    head: Position::new(cr, cc),
2296                })
2297            }
2298            _ => None,
2299        }
2300    }
2301
2302    /// Force back to normal mode (used when dismissing completions etc.)
2303    pub fn force_normal(&mut self) {
2304        self.vim.force_normal();
2305    }
2306
2307    pub fn content(&self) -> String {
2308        let n = buf_row_count(&self.buffer);
2309        let mut s = String::new();
2310        for r in 0..n {
2311            if r > 0 {
2312                s.push('\n');
2313            }
2314            s.push_str(&crate::types::Query::line(&self.buffer, r as u32));
2315        }
2316        s.push('\n');
2317        s
2318    }
2319
2320    /// Same logical output as [`content`], but returns a cached
2321    /// `Arc<String>` so back-to-back reads within an un-mutated window
2322    /// are ref-count bumps instead of multi-MB joins. The cache is
2323    /// invalidated by every [`mark_content_dirty`] call.
2324    pub fn content_arc(&mut self) -> std::sync::Arc<String> {
2325        if let Some(arc) = &self.cached_content {
2326            return std::sync::Arc::clone(arc);
2327        }
2328        let arc = std::sync::Arc::new(self.content());
2329        self.cached_content = Some(std::sync::Arc::clone(&arc));
2330        arc
2331    }
2332
2333    pub fn set_content(&mut self, text: &str) {
2334        let mut lines: Vec<String> = text.lines().map(|l| l.to_string()).collect();
2335        while lines.last().map(|l| l.is_empty()).unwrap_or(false) {
2336            lines.pop();
2337        }
2338        if lines.is_empty() {
2339            lines.push(String::new());
2340        }
2341        let _ = lines;
2342        crate::types::BufferEdit::replace_all(&mut self.buffer, text);
2343        self.undo_stack.clear();
2344        self.redo_stack.clear();
2345        // Whole-buffer replace supersedes any queued ContentEdits.
2346        self.pending_content_edits.clear();
2347        self.pending_content_reset = true;
2348        self.mark_content_dirty();
2349    }
2350
2351    /// Whole-buffer replace that **preserves the undo history**.
2352    ///
2353    /// Equivalent to [`Editor::set_content`] but pushes the current buffer
2354    /// state onto the undo stack first, so a subsequent `u` walks back to
2355    /// the pre-replacement content. Use this for any operation the user
2356    /// expects to undo as a single step — e.g. external formatter output
2357    /// (`hjkl-mangler`) installed via the async [`crate::app::FormatWorker`].
2358    ///
2359    /// Like `push_undo`, this clears the redo stack (vim semantics: any
2360    /// new edit invalidates redo).
2361    pub fn set_content_undoable(&mut self, text: &str) {
2362        self.push_undo();
2363        let mut lines: Vec<String> = text.lines().map(|l| l.to_string()).collect();
2364        while lines.last().map(|l| l.is_empty()).unwrap_or(false) {
2365            lines.pop();
2366        }
2367        if lines.is_empty() {
2368            lines.push(String::new());
2369        }
2370        let _ = lines;
2371        crate::types::BufferEdit::replace_all(&mut self.buffer, text);
2372        // Whole-buffer replace supersedes any queued ContentEdits.
2373        self.pending_content_edits.clear();
2374        self.pending_content_reset = true;
2375        self.mark_content_dirty();
2376    }
2377
2378    /// Drain the pending change log produced by buffer mutations.
2379    ///
2380    /// Returns a `Vec<EditOp>` covering edits applied since the last
2381    /// call. Empty when no edits ran. Pull-model, complementary to
2382    /// [`Editor::take_content_change`] which gives back the new full
2383    /// content.
2384    ///
2385    /// Mapping coverage:
2386    /// - InsertChar / InsertStr → exact `EditOp` with empty range +
2387    ///   replacement.
2388    /// - DeleteRange (`Char` kind) → exact range + empty replacement.
2389    /// - Replace → exact range + new replacement.
2390    /// - DeleteRange (`Line`/`Block`), JoinLines, SplitLines,
2391    ///   InsertBlock, DeleteBlockChunks → best-effort placeholder
2392    ///   covering the touched range. Hosts wanting per-cell deltas
2393    ///   should diff their own `lines()` snapshot.
2394    pub fn take_changes(&mut self) -> Vec<crate::types::Edit> {
2395        std::mem::take(&mut self.change_log)
2396    }
2397
2398    /// Read the engine's current settings as a SPEC
2399    /// [`crate::types::Options`].
2400    ///
2401    /// Bridges between the legacy [`Settings`] (which carries fewer
2402    /// fields than SPEC) and the planned 0.1.0 trait surface. Fields
2403    /// not present in `Settings` fall back to vim defaults (e.g.,
2404    /// `expandtab=false`, `wrapscan=true`, `timeout_len=1000ms`).
2405    /// Once trait extraction lands, this becomes the canonical config
2406    /// reader and `Settings` retires.
2407    pub fn current_options(&self) -> crate::types::Options {
2408        crate::types::Options {
2409            shiftwidth: self.settings.shiftwidth as u32,
2410            tabstop: self.settings.tabstop as u32,
2411            softtabstop: self.settings.softtabstop as u32,
2412            textwidth: self.settings.textwidth as u32,
2413            expandtab: self.settings.expandtab,
2414            ignorecase: self.settings.ignore_case,
2415            smartcase: self.settings.smartcase,
2416            wrapscan: self.settings.wrapscan,
2417            wrap: match self.settings.wrap {
2418                hjkl_buffer::Wrap::None => crate::types::WrapMode::None,
2419                hjkl_buffer::Wrap::Char => crate::types::WrapMode::Char,
2420                hjkl_buffer::Wrap::Word => crate::types::WrapMode::Word,
2421            },
2422            readonly: self.settings.readonly,
2423            autoindent: self.settings.autoindent,
2424            smartindent: self.settings.smartindent,
2425            undo_levels: self.settings.undo_levels,
2426            undo_break_on_motion: self.settings.undo_break_on_motion,
2427            iskeyword: self.settings.iskeyword.clone(),
2428            timeout_len: self.settings.timeout_len,
2429            ..crate::types::Options::default()
2430        }
2431    }
2432
2433    /// Apply a SPEC [`crate::types::Options`] to the engine's settings.
2434    /// Only the fields backed by today's [`Settings`] take effect;
2435    /// remaining options become live once trait extraction wires them
2436    /// through.
2437    pub fn apply_options(&mut self, opts: &crate::types::Options) {
2438        self.settings.shiftwidth = opts.shiftwidth as usize;
2439        self.settings.tabstop = opts.tabstop as usize;
2440        self.settings.softtabstop = opts.softtabstop as usize;
2441        self.settings.textwidth = opts.textwidth as usize;
2442        self.settings.expandtab = opts.expandtab;
2443        self.settings.ignore_case = opts.ignorecase;
2444        self.settings.smartcase = opts.smartcase;
2445        self.settings.wrapscan = opts.wrapscan;
2446        self.settings.wrap = match opts.wrap {
2447            crate::types::WrapMode::None => hjkl_buffer::Wrap::None,
2448            crate::types::WrapMode::Char => hjkl_buffer::Wrap::Char,
2449            crate::types::WrapMode::Word => hjkl_buffer::Wrap::Word,
2450        };
2451        self.settings.readonly = opts.readonly;
2452        self.settings.autoindent = opts.autoindent;
2453        self.settings.smartindent = opts.smartindent;
2454        self.settings.undo_levels = opts.undo_levels;
2455        self.settings.undo_break_on_motion = opts.undo_break_on_motion;
2456        self.set_iskeyword(opts.iskeyword.clone());
2457        self.settings.timeout_len = opts.timeout_len;
2458        self.settings.number = opts.number;
2459        self.settings.relativenumber = opts.relativenumber;
2460        self.settings.numberwidth = opts.numberwidth;
2461        self.settings.cursorline = opts.cursorline;
2462        self.settings.cursorcolumn = opts.cursorcolumn;
2463        self.settings.signcolumn = opts.signcolumn;
2464        self.settings.foldcolumn = opts.foldcolumn;
2465        self.settings.colorcolumn = opts.colorcolumn.clone();
2466        self.settings.scrolloff = opts.scrolloff;
2467        self.settings.sidescrolloff = opts.sidescrolloff;
2468        self.settings.autoreload = opts.autoreload;
2469        self.settings.list = opts.list;
2470        self.settings.listchars = opts.listchars.clone();
2471        self.settings.colorizer = opts.colorizer;
2472        self.settings.colorizer_filetypes = opts.colorizer_filetypes.clone();
2473        self.settings.format_on_save = opts.format_on_save;
2474        self.settings.trim_trailing_whitespace = opts.trim_trailing_whitespace;
2475        self.settings.rainbow_brackets = opts.rainbow_brackets;
2476        self.settings.matchparen = opts.matchparen;
2477    }
2478
2479    /// Active visual selection as a SPEC [`crate::types::Highlight`]
2480    /// with [`crate::types::HighlightKind::Selection`].
2481    ///
2482    /// Returns `None` when the editor isn't in a Visual mode.
2483    /// Visual-line and visual-block selections collapse to the
2484    /// bounding char range of the selection — the SPEC `Selection`
2485    /// kind doesn't carry sub-line info today; hosts that need full
2486    /// line / block geometry continue to read [`buffer_selection`]
2487    /// (the legacy [`hjkl_buffer::Selection`] shape).
2488    pub fn selection_highlight(&self) -> Option<crate::types::Highlight> {
2489        use crate::types::{Highlight, HighlightKind, Pos};
2490        let sel = self.buffer_selection()?;
2491        let (start, end) = match sel {
2492            hjkl_buffer::Selection::Char { anchor, head } => {
2493                let a = (anchor.row, anchor.col);
2494                let h = (head.row, head.col);
2495                if a <= h { (a, h) } else { (h, a) }
2496            }
2497            hjkl_buffer::Selection::Line {
2498                anchor_row,
2499                head_row,
2500            } => {
2501                let (top, bot) = if anchor_row <= head_row {
2502                    (anchor_row, head_row)
2503                } else {
2504                    (head_row, anchor_row)
2505                };
2506                let last_col = buf_line(&self.buffer, bot).map(|l| l.len()).unwrap_or(0);
2507                ((top, 0), (bot, last_col))
2508            }
2509            hjkl_buffer::Selection::Block { anchor, head } => {
2510                let (top, bot) = if anchor.row <= head.row {
2511                    (anchor.row, head.row)
2512                } else {
2513                    (head.row, anchor.row)
2514                };
2515                let (left, right) = if anchor.col <= head.col {
2516                    (anchor.col, head.col)
2517                } else {
2518                    (head.col, anchor.col)
2519                };
2520                ((top, left), (bot, right))
2521            }
2522        };
2523        Some(Highlight {
2524            range: Pos {
2525                line: start.0 as u32,
2526                col: start.1 as u32,
2527            }..Pos {
2528                line: end.0 as u32,
2529                col: end.1 as u32,
2530            },
2531            kind: HighlightKind::Selection,
2532        })
2533    }
2534
2535    /// SPEC-typed highlights for `line`.
2536    ///
2537    /// Two emission modes:
2538    ///
2539    /// - **IncSearch**: the user is typing a `/` or `?` prompt and
2540    ///   `Editor::search_prompt` is `Some`. Live-preview matches of
2541    ///   the in-flight pattern surface as
2542    ///   [`crate::types::HighlightKind::IncSearch`].
2543    /// - **SearchMatch**: the prompt has been committed (or absent)
2544    ///   and the buffer's armed pattern is non-empty. Matches surface
2545    ///   as [`crate::types::HighlightKind::SearchMatch`].
2546    ///
2547    /// Selection / MatchParen / Syntax(id) variants land once the
2548    /// trait extraction routes the FSM's selection set + the host's
2549    /// syntax pipeline through the [`crate::types::Host`] trait.
2550    ///
2551    /// Returns an empty vec when there is nothing to highlight or
2552    /// `line` is out of bounds.
2553    pub fn highlights_for_line(&mut self, line: u32) -> Vec<crate::types::Highlight> {
2554        use crate::types::{Highlight, HighlightKind, Pos};
2555        let row = line as usize;
2556        if row >= buf_row_count(&self.buffer) {
2557            return Vec::new();
2558        }
2559
2560        // Live preview while the prompt is open beats the committed
2561        // pattern.
2562        if let Some(prompt) = self.search_prompt() {
2563            if prompt.text.is_empty() {
2564                return Vec::new();
2565            }
2566            use crate::search::{CaseMode, resolve_case_mode};
2567            let base =
2568                CaseMode::from_options(self.settings().ignore_case, self.settings().smartcase);
2569            let (stripped, mode) = resolve_case_mode(&prompt.text, base);
2570            let src = if mode == CaseMode::Insensitive {
2571                format!("(?i){stripped}")
2572            } else {
2573                stripped
2574            };
2575            let Ok(re) = regex::Regex::new(&src) else {
2576                return Vec::new();
2577            };
2578            let Some(haystack) = buf_line(&self.buffer, row) else {
2579                return Vec::new();
2580            };
2581            return re
2582                .find_iter(&haystack)
2583                .map(|m| Highlight {
2584                    range: Pos {
2585                        line,
2586                        col: m.start() as u32,
2587                    }..Pos {
2588                        line,
2589                        col: m.end() as u32,
2590                    },
2591                    kind: HighlightKind::IncSearch,
2592                })
2593                .collect();
2594        }
2595
2596        if self.search_state.pattern.is_none() {
2597            return Vec::new();
2598        }
2599        let dgen = crate::types::Query::dirty_gen(&self.buffer);
2600        crate::search::search_matches(&self.buffer, &mut self.search_state, dgen, row)
2601            .into_iter()
2602            .map(|(start, end)| Highlight {
2603                range: Pos {
2604                    line,
2605                    col: start as u32,
2606                }..Pos {
2607                    line,
2608                    col: end as u32,
2609                },
2610                kind: HighlightKind::SearchMatch,
2611            })
2612            .collect()
2613    }
2614
2615    /// Build the engine's [`crate::types::RenderFrame`] for the
2616    /// current state. Hosts call this once per redraw and diff
2617    /// across frames.
2618    ///
2619    /// Coarse today — covers mode + cursor + cursor shape + viewport
2620    /// top + line count. SPEC-target fields (selections, highlights,
2621    /// command line, search prompt, status line) land once trait
2622    /// extraction routes them through `SelectionSet` and the
2623    /// `Highlight` pipeline.
2624    pub fn render_frame(&self) -> crate::types::RenderFrame {
2625        use crate::types::{CursorShape, RenderFrame, SnapshotMode};
2626        let (cursor_row, cursor_col) = self.cursor();
2627        let (mode, shape) = match self.vim_mode() {
2628            crate::VimMode::Normal => (SnapshotMode::Normal, CursorShape::Block),
2629            crate::VimMode::Insert => (SnapshotMode::Insert, CursorShape::Bar),
2630            crate::VimMode::Visual => (SnapshotMode::Visual, CursorShape::Block),
2631            crate::VimMode::VisualLine => (SnapshotMode::VisualLine, CursorShape::Block),
2632            crate::VimMode::VisualBlock => (SnapshotMode::VisualBlock, CursorShape::Block),
2633        };
2634        RenderFrame {
2635            mode,
2636            cursor_row: cursor_row as u32,
2637            cursor_col: cursor_col as u32,
2638            cursor_shape: shape,
2639            viewport_top: self.host.viewport().top_row as u32,
2640            line_count: crate::types::Query::line_count(&self.buffer),
2641        }
2642    }
2643
2644    /// Capture the editor's coarse state into a serde-friendly
2645    /// [`crate::types::EditorSnapshot`].
2646    ///
2647    /// Today's snapshot covers mode, cursor, lines, viewport top.
2648    /// Registers, marks, jump list, undo tree, and full options arrive
2649    /// once phase 5 trait extraction lands the generic
2650    /// `Editor<B: Buffer, H: Host>` constructor — this method's surface
2651    /// stays stable; only the snapshot's internal fields grow.
2652    ///
2653    /// Distinct from the internal `snapshot` used by undo (which
2654    /// returns `(Vec<String>, (usize, usize))`); host-facing
2655    /// persistence goes through this one.
2656    pub fn take_snapshot(&self) -> crate::types::EditorSnapshot {
2657        use crate::types::{EditorSnapshot, SnapshotMode};
2658        let mode = match self.vim_mode() {
2659            crate::VimMode::Normal => SnapshotMode::Normal,
2660            crate::VimMode::Insert => SnapshotMode::Insert,
2661            crate::VimMode::Visual => SnapshotMode::Visual,
2662            crate::VimMode::VisualLine => SnapshotMode::VisualLine,
2663            crate::VimMode::VisualBlock => SnapshotMode::VisualBlock,
2664        };
2665        let cursor = self.cursor();
2666        let cursor = (cursor.0 as u32, cursor.1 as u32);
2667        let rope = crate::types::Query::rope(&self.buffer);
2668        let lines: Vec<String> = (0..rope.len_lines())
2669            .map(|r| {
2670                let s = rope.line(r).to_string();
2671                if s.ends_with('\n') {
2672                    s[..s.len() - 1].to_string()
2673                } else {
2674                    s
2675                }
2676            })
2677            .collect();
2678        let viewport_top = self.host.viewport().top_row as u32;
2679        let marks = self
2680            .marks
2681            .iter()
2682            .map(|(c, (r, col))| (*c, (*r as u32, *col as u32)))
2683            .collect();
2684        let global_marks = self
2685            .global_marks
2686            .iter()
2687            .map(|(c, &(bid, r, col))| (*c, (bid, r as u32, col as u32)))
2688            .collect();
2689        EditorSnapshot {
2690            version: EditorSnapshot::VERSION,
2691            mode,
2692            cursor,
2693            lines,
2694            viewport_top,
2695            registers: self.registers.clone(),
2696            marks,
2697            global_marks,
2698        }
2699    }
2700
2701    /// Restore editor state from an [`EditorSnapshot`]. Returns
2702    /// [`crate::EngineError::SnapshotVersion`] if the snapshot's
2703    /// `version` doesn't match [`EditorSnapshot::VERSION`].
2704    ///
2705    /// Mode is best-effort: `SnapshotMode` only round-trips the
2706    /// status-line summary, not the full FSM state. Visual / Insert
2707    /// mode entry happens through synthetic key dispatch when needed.
2708    pub fn restore_snapshot(
2709        &mut self,
2710        snap: crate::types::EditorSnapshot,
2711    ) -> Result<(), crate::EngineError> {
2712        use crate::types::EditorSnapshot;
2713        if snap.version != EditorSnapshot::VERSION {
2714            return Err(crate::EngineError::SnapshotVersion(
2715                snap.version,
2716                EditorSnapshot::VERSION,
2717            ));
2718        }
2719        let text = snap.lines.join("\n");
2720        self.set_content(&text);
2721        self.jump_cursor(snap.cursor.0 as usize, snap.cursor.1 as usize);
2722        self.host.viewport_mut().top_row = snap.viewport_top as usize;
2723        self.registers = snap.registers;
2724        self.marks = snap
2725            .marks
2726            .into_iter()
2727            .map(|(c, (r, col))| (c, (r as usize, col as usize)))
2728            .collect();
2729        self.global_marks = snap
2730            .global_marks
2731            .into_iter()
2732            .map(|(c, (bid, r, col))| (c, (bid, r as usize, col as usize)))
2733            .collect();
2734        Ok(())
2735    }
2736
2737    /// Install `text` as the pending yank buffer so the next `p`/`P` pastes
2738    /// it. Linewise is inferred from a trailing newline, matching how `yy`/`dd`
2739    /// shape their payload.
2740    pub fn seed_yank(&mut self, text: String) {
2741        let linewise = text.ends_with('\n');
2742        self.vim.yank_linewise = linewise;
2743        self.registers.unnamed = crate::registers::Slot { text, linewise };
2744    }
2745
2746    /// Scroll the viewport down by `rows`. The cursor stays on its
2747    /// absolute line (vim convention) unless the scroll would take it
2748    /// off-screen — in that case it's clamped to the first row still
2749    /// visible.
2750    pub fn scroll_down(&mut self, rows: i16) {
2751        self.scroll_viewport(rows);
2752    }
2753
2754    /// Scroll the viewport up by `rows`. Cursor stays unless it would
2755    /// fall off the bottom of the new viewport, then clamp to the
2756    /// bottom-most visible row.
2757    pub fn scroll_up(&mut self, rows: i16) {
2758        self.scroll_viewport(-rows);
2759    }
2760
2761    /// Scroll the viewport right by `cols` columns. Only the horizontal
2762    /// offset (`top_col`) moves — the cursor is NOT adjusted (matches
2763    /// vim's `zl` behaviour for horizontal scroll without wrap).
2764    pub fn scroll_right(&mut self, cols: i16) {
2765        let vp = self.host.viewport_mut();
2766        let cols_i = cols as isize;
2767        let new_top = (vp.top_col as isize + cols_i).max(0) as usize;
2768        vp.top_col = new_top;
2769    }
2770
2771    /// Scroll the viewport left by `cols` columns. Delegates to
2772    /// `scroll_right` with a negated argument so the floor-at-zero
2773    /// clamp is shared.
2774    pub fn scroll_left(&mut self, cols: i16) {
2775        self.scroll_right(-cols);
2776    }
2777
2778    /// Scroll the viewport so the cursor stays at least `scrolloff`
2779    /// rows from each edge. Replaces the bare
2780    /// `Buffer::ensure_cursor_visible` call at end-of-step so motions
2781    /// don't park the cursor on the very last visible row.
2782    pub fn ensure_cursor_in_scrolloff(&mut self) {
2783        let height = self.viewport_height.load(Ordering::Relaxed) as usize;
2784        if height == 0 {
2785            // 0.0.42 (Patch C-δ.7): viewport math lifted onto engine
2786            // free fns over `B: Query [+ Cursor]` + `&dyn FoldProvider`.
2787            // Disjoint-field borrow split: `self.buffer` (immutable via
2788            // `folds` snapshot + cursor) and `self.host` (mutable
2789            // viewport ref) live on distinct struct fields, so one
2790            // statement satisfies the borrow checker.
2791            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2792            crate::viewport_math::ensure_cursor_visible(
2793                &self.buffer,
2794                &folds,
2795                self.host.viewport_mut(),
2796            );
2797            return;
2798        }
2799        // Cap margin at (height - 1) / 2 so the upper + lower bands
2800        // can't overlap on tiny windows (margin=5 + height=10 would
2801        // otherwise produce contradictory clamp ranges).
2802        let margin = self.settings.scrolloff.min(height.saturating_sub(1) / 2);
2803        // Soft-wrap path: scrolloff math runs in *screen rows*, not
2804        // doc rows, since a wrapped doc row spans many visual lines.
2805        if !matches!(self.host.viewport().wrap, hjkl_buffer::Wrap::None) {
2806            self.ensure_scrolloff_wrap(height, margin);
2807            return;
2808        }
2809        let cursor_row = buf_cursor_row(&self.buffer);
2810        let last_row = buf_row_count(&self.buffer).saturating_sub(1);
2811        let v = self.host.viewport_mut();
2812        // Top edge: cursor_row should sit at >= top_row + margin.
2813        if cursor_row < v.top_row + margin {
2814            v.top_row = cursor_row.saturating_sub(margin);
2815        }
2816        // Bottom edge: cursor_row should sit at <= top_row + height - 1 - margin.
2817        let max_bottom = height.saturating_sub(1).saturating_sub(margin);
2818        if cursor_row > v.top_row + max_bottom {
2819            v.top_row = cursor_row.saturating_sub(max_bottom);
2820        }
2821        // Clamp top_row so we never scroll past the buffer's bottom.
2822        let max_top = last_row.saturating_sub(height.saturating_sub(1));
2823        if v.top_row > max_top {
2824            v.top_row = max_top;
2825        }
2826        // Defer to Buffer for column-side scroll (no scrolloff for
2827        // horizontal scrolling — vim default `sidescrolloff = 0`).
2828        let cursor = buf_cursor_pos(&self.buffer);
2829        self.host.viewport_mut().ensure_visible(cursor);
2830    }
2831
2832    /// Soft-wrap-aware scrolloff. Walks `top_row` one visible doc row
2833    /// at a time so the cursor's *screen* row stays inside
2834    /// `[margin, height - 1 - margin]`, then clamps `top_row` so the
2835    /// buffer's bottom never leaves blank rows below it.
2836    fn ensure_scrolloff_wrap(&mut self, height: usize, margin: usize) {
2837        let cursor_row = buf_cursor_row(&self.buffer);
2838        // Step 1 — cursor above viewport: snap top to cursor row,
2839        // then we'll fix up the margin below.
2840        if cursor_row < self.host.viewport().top_row {
2841            let v = self.host.viewport_mut();
2842            v.top_row = cursor_row;
2843            v.top_col = 0;
2844        }
2845        // Step 2 — push top forward until cursor's screen row is
2846        // within the bottom margin (`csr <= height - 1 - margin`).
2847        // 0.0.33 (Patch C-γ): fold-iteration goes through the
2848        // [`crate::types::FoldProvider`] surface via
2849        // [`crate::buffer_impl::BufferFoldProvider`]. 0.0.34 (Patch
2850        // C-δ.1): `cursor_screen_row` / `max_top_for_height` now take
2851        // a `&Viewport` parameter; the host owns the viewport, so the
2852        // disjoint `(self.host, self.buffer)` borrows split cleanly.
2853        let max_csr = height.saturating_sub(1).saturating_sub(margin);
2854        loop {
2855            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2856            let csr =
2857                crate::viewport_math::cursor_screen_row(&self.buffer, &folds, self.host.viewport())
2858                    .unwrap_or(0);
2859            if csr <= max_csr {
2860                break;
2861            }
2862            let top = self.host.viewport().top_row;
2863            let row_count = buf_row_count(&self.buffer);
2864            let next = {
2865                let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2866                <crate::buffer_impl::BufferFoldProvider<'_> as crate::types::FoldProvider>::next_visible_row(&folds, top, row_count)
2867            };
2868            let Some(next) = next else {
2869                break;
2870            };
2871            // Don't walk past the cursor's row.
2872            if next > cursor_row {
2873                self.host.viewport_mut().top_row = cursor_row;
2874                break;
2875            }
2876            self.host.viewport_mut().top_row = next;
2877        }
2878        // Step 3 — pull top backward until cursor's screen row is
2879        // past the top margin (`csr >= margin`).
2880        loop {
2881            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2882            let csr =
2883                crate::viewport_math::cursor_screen_row(&self.buffer, &folds, self.host.viewport())
2884                    .unwrap_or(0);
2885            if csr >= margin {
2886                break;
2887            }
2888            let top = self.host.viewport().top_row;
2889            let prev = {
2890                let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2891                <crate::buffer_impl::BufferFoldProvider<'_> as crate::types::FoldProvider>::prev_visible_row(&folds, top)
2892            };
2893            let Some(prev) = prev else {
2894                break;
2895            };
2896            self.host.viewport_mut().top_row = prev;
2897        }
2898        // Step 4 — clamp top so the buffer's bottom doesn't leave
2899        // blank rows below it. `max_top_for_height` walks segments
2900        // backward from the last row until it accumulates `height`
2901        // screen rows.
2902        let max_top = {
2903            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
2904            crate::viewport_math::max_top_for_height(
2905                &self.buffer,
2906                &folds,
2907                self.host.viewport(),
2908                height,
2909            )
2910        };
2911        if self.host.viewport().top_row > max_top {
2912            self.host.viewport_mut().top_row = max_top;
2913        }
2914        self.host.viewport_mut().top_col = 0;
2915    }
2916
2917    fn scroll_viewport(&mut self, delta: i16) {
2918        if delta == 0 {
2919            return;
2920        }
2921        // Bump the host viewport's top within bounds.
2922        let total_rows = buf_row_count(&self.buffer) as isize;
2923        let height = self.viewport_height.load(Ordering::Relaxed) as usize;
2924        let cur_top = self.host.viewport().top_row as isize;
2925        let new_top = (cur_top + delta as isize)
2926            .max(0)
2927            .min((total_rows - 1).max(0)) as usize;
2928        self.host.viewport_mut().top_row = new_top;
2929        // Mirror to textarea so its viewport reads (still consumed by
2930        // a couple of helpers) stay accurate.
2931        let _ = cur_top;
2932        if height == 0 {
2933            return;
2934        }
2935        // Apply scrolloff: keep the cursor at least scrolloff rows
2936        // from the visible viewport edges.
2937        let (cursor_row, cursor_col) = buf_cursor_rc(&self.buffer);
2938        let margin = self.settings.scrolloff.min(height / 2);
2939        let min_row = new_top + margin;
2940        let max_row = new_top + height.saturating_sub(1).saturating_sub(margin);
2941        let target_row = cursor_row.clamp(min_row, max_row.max(min_row));
2942        if target_row != cursor_row {
2943            let line_len = buf_line(&self.buffer, target_row)
2944                .map(|l| l.chars().count())
2945                .unwrap_or(0);
2946            let target_col = cursor_col.min(line_len.saturating_sub(1));
2947            buf_set_cursor_rc(&mut self.buffer, target_row, target_col);
2948        }
2949    }
2950
2951    pub fn goto_line(&mut self, line: usize) {
2952        let row = line.saturating_sub(1);
2953        let max = buf_row_count(&self.buffer).saturating_sub(1);
2954        let target = row.min(max);
2955        buf_set_cursor_rc(&mut self.buffer, target, 0);
2956        // Vim: `:N` / `+N` jump scrolls the viewport too — without this
2957        // the cursor lands off-screen and the user has to scroll
2958        // manually to see it.
2959        self.ensure_cursor_in_scrolloff();
2960    }
2961
2962    /// Scroll so the cursor row lands at the given viewport position:
2963    /// `Center` → middle row, `Top` → first row, `Bottom` → last row.
2964    /// Cursor stays on its absolute line; only the viewport moves.
2965    pub(super) fn scroll_cursor_to(&mut self, pos: CursorScrollTarget) {
2966        let height = self.viewport_height.load(Ordering::Relaxed) as usize;
2967        if height == 0 {
2968            return;
2969        }
2970        let cur_row = buf_cursor_row(&self.buffer);
2971        let cur_top = self.host.viewport().top_row;
2972        // Scrolloff awareness: `zt` lands the cursor at the top edge
2973        // of the viable area (top + margin), `zb` at the bottom edge
2974        // (top + height - 1 - margin). Match the cap used by
2975        // `ensure_cursor_in_scrolloff` so contradictory bounds are
2976        // impossible on tiny viewports.
2977        let margin = self.settings.scrolloff.min(height.saturating_sub(1) / 2);
2978        let new_top = match pos {
2979            CursorScrollTarget::Center => cur_row.saturating_sub(height / 2),
2980            CursorScrollTarget::Top => cur_row.saturating_sub(margin),
2981            CursorScrollTarget::Bottom => {
2982                cur_row.saturating_sub(height.saturating_sub(1).saturating_sub(margin))
2983            }
2984        };
2985        if new_top == cur_top {
2986            return;
2987        }
2988        self.host.viewport_mut().top_row = new_top;
2989    }
2990
2991    /// Jump the cursor to the given 1-based line/column, clamped to the document.
2992    pub fn jump_to(&mut self, line: usize, col: usize) {
2993        let r = line.saturating_sub(1);
2994        let max_row = buf_row_count(&self.buffer).saturating_sub(1);
2995        let r = r.min(max_row);
2996        let line_len = buf_line(&self.buffer, r)
2997            .map(|l| l.chars().count())
2998            .unwrap_or(0);
2999        let c = col.saturating_sub(1).min(line_len);
3000        buf_set_cursor_rc(&mut self.buffer, r, c);
3001    }
3002
3003    // ── Host-agnostic doc-coord mouse primitives (Phase 1 of issue #114) ─────
3004    //
3005    // These primitives operate on document (row, col) coordinates that the HOST
3006    // computes from its own layout knowledge (cell geometry for the TUI host,
3007    // pixel geometry for the future GUI host). The engine has no u16 terminal
3008    // assumption here — it just moves the cursor in doc-space.
3009
3010    /// Set the cursor to the given doc-space `(row, col)`, clamped to the
3011    /// document bounds. Hosts use this for programmatic cursor placement and
3012    /// as the building block for the mouse-click path.
3013    ///
3014    /// `col` may equal `line.chars().count()` (Insert-mode "one past end"
3015    /// position); values beyond that are clamped to `char_count`.
3016    pub fn set_cursor_doc(&mut self, row: usize, col: usize) {
3017        let max_row = buf_row_count(&self.buffer).saturating_sub(1);
3018        let r = row.min(max_row);
3019        let line_len = buf_line(&self.buffer, r)
3020            .map(|l| l.chars().count())
3021            .unwrap_or(0);
3022        let c = col.min(line_len);
3023        buf_set_cursor_rc(&mut self.buffer, r, c);
3024    }
3025
3026    /// Handle a left-button click at doc-space `(row, col)`.
3027    ///
3028    /// Exits Visual mode if active, breaks the insert-mode undo group (Vim
3029    /// parity for `undo_break_on_motion`), then moves the cursor. The host
3030    /// performs cell→doc or pixel→doc translation before calling this.
3031    ///
3032    /// Mode-aware EOL clamp (neovim parity): in Normal / Visual modes the
3033    /// cursor lives on chars and never on the implicit `\n` — `col` is
3034    /// capped at `line.chars().count().saturating_sub(1)`. Insert mode
3035    /// allows the one-past-EOL insert position (`col == chars().count()`).
3036    ///
3037    /// Resets `sticky_col` to the clicked column so the next `j`/`k`
3038    /// motion uses the clicked column as the intended visual column
3039    /// (otherwise the cursor would snap back to the keyboard-tracked
3040    /// column on the first vertical motion after a click).
3041    pub fn mouse_click_doc(&mut self, row: usize, col: usize) {
3042        if self.vim.is_visual() {
3043            self.vim.force_normal();
3044        }
3045        // Mouse-position click counts as a motion — break the active
3046        // insert-mode undo group when the toggle is on (vim parity).
3047        crate::vim::break_undo_group_in_insert(self);
3048
3049        let max_row = buf_row_count(&self.buffer).saturating_sub(1);
3050        let r = row.min(max_row);
3051        let line_len = buf_line(&self.buffer, r)
3052            .map(|l| l.chars().count())
3053            .unwrap_or(0);
3054        let cap = if self.vim.current_mode == crate::VimMode::Insert {
3055            line_len
3056        } else {
3057            line_len.saturating_sub(1)
3058        };
3059        let c = col.min(cap);
3060        buf_set_cursor_rc(&mut self.buffer, r, c);
3061        self.sticky_col = Some(c);
3062    }
3063
3064    /// Begin a mouse-drag selection: anchor at the current cursor and enter
3065    /// Visual-char mode. Idempotent if already in Visual-char mode.
3066    pub fn mouse_begin_drag(&mut self) {
3067        if !self.vim.is_visual_char() {
3068            vim::enter_visual_char_bridge(self);
3069        }
3070    }
3071
3072    /// Extend an in-progress mouse drag to doc-space `(row, col)`.
3073    ///
3074    /// Moves the live cursor; the Visual anchor stays where
3075    /// [`Editor::mouse_begin_drag`] set it. Call after the host has
3076    /// translated the drag position to doc coordinates.
3077    pub fn mouse_extend_drag_doc(&mut self, row: usize, col: usize) {
3078        self.set_cursor_doc(row, col);
3079    }
3080
3081    pub fn insert_str(&mut self, text: &str) {
3082        let pos = crate::types::Cursor::cursor(&self.buffer);
3083        crate::types::BufferEdit::insert_at(&mut self.buffer, pos, text);
3084        self.push_buffer_content_to_textarea();
3085        self.mark_content_dirty();
3086    }
3087
3088    pub fn accept_completion(&mut self, completion: &str) {
3089        use crate::types::{BufferEdit, Cursor as CursorTrait, Pos};
3090        let cursor_pos = CursorTrait::cursor(&self.buffer);
3091        let cursor_row = cursor_pos.line as usize;
3092        let cursor_col = cursor_pos.col as usize;
3093        let line = buf_line(&self.buffer, cursor_row).unwrap_or_default();
3094        let chars: Vec<char> = line.chars().collect();
3095        let prefix_len = chars[..cursor_col.min(chars.len())]
3096            .iter()
3097            .rev()
3098            .take_while(|c| c.is_alphanumeric() || **c == '_')
3099            .count();
3100        if prefix_len > 0 {
3101            let start = Pos {
3102                line: cursor_row as u32,
3103                col: (cursor_col - prefix_len) as u32,
3104            };
3105            BufferEdit::delete_range(&mut self.buffer, start..cursor_pos);
3106        }
3107        let cursor = CursorTrait::cursor(&self.buffer);
3108        BufferEdit::insert_at(&mut self.buffer, cursor, completion);
3109        self.push_buffer_content_to_textarea();
3110        self.mark_content_dirty();
3111    }
3112
3113    /// Capture the buffer state for undo / redo.  Uses
3114    /// [`Query::content_joined`], which the `Buffer` impl caches as an
3115    /// `Arc<String>` against `dirty_gen` — so when LSP / git / syntax
3116    /// already joined this generation, the snapshot is an `Arc::clone`
3117    /// (one ptr bump). Previously this cloned every line into a
3118    /// `Vec<String>` (162 k allocations on a 162 k-row buffer) and the
3119    /// matching `restore` re-joined them — samply showed it at ~9 % of
3120    /// CPU on a big-paste session.
3121    pub(super) fn snapshot(&self) -> (ropey::Rope, (usize, usize)) {
3122        use crate::types::Query;
3123        let rc = buf_cursor_rc(&self.buffer);
3124        (Query::rope(&self.buffer), rc)
3125    }
3126
3127    /// Walk one step back through the undo history. Equivalent to the
3128    /// user pressing `u` in normal mode. Drains the most recent undo
3129    /// entry and pushes it onto the redo stack.
3130    pub fn undo(&mut self) {
3131        crate::vim::do_undo(self);
3132    }
3133
3134    /// Walk one step forward through the redo history. Equivalent to
3135    /// `<C-r>` in normal mode.
3136    pub fn redo(&mut self) {
3137        crate::vim::do_redo(self);
3138    }
3139
3140    /// Undo `n` steps. Returns the number of steps actually applied
3141    /// (bounded by undo stack size).
3142    pub fn earlier_by_steps(&mut self, n: usize) -> usize {
3143        let mut count = 0;
3144        for _ in 0..n {
3145            if self.undo_stack.is_empty() {
3146                break;
3147            }
3148            crate::vim::do_undo(self);
3149            count += 1;
3150        }
3151        count
3152    }
3153
3154    /// Redo `n` steps. Returns the number of steps actually applied
3155    /// (bounded by redo stack size).
3156    pub fn later_by_steps(&mut self, n: usize) -> usize {
3157        let mut count = 0;
3158        for _ in 0..n {
3159            if self.redo_stack.is_empty() {
3160                break;
3161            }
3162            crate::vim::do_redo(self);
3163            count += 1;
3164        }
3165        count
3166    }
3167
3168    /// Undo back until the next-to-pop entry's timestamp is at or before
3169    /// `target`. Entries whose timestamp is strictly greater than `target`
3170    /// are popped (undone). Returns the number of steps applied.
3171    ///
3172    /// Vim `:earlier Ns` semantics: `target = SystemTime::now() - N seconds`.
3173    pub fn earlier_by_time(&mut self, target: SystemTime) -> usize {
3174        let mut count = 0;
3175        loop {
3176            match self.undo_stack.last() {
3177                None => break,
3178                Some(entry) => {
3179                    if entry.timestamp <= target {
3180                        break;
3181                    }
3182                }
3183            }
3184            crate::vim::do_undo(self);
3185            count += 1;
3186        }
3187        count
3188    }
3189
3190    /// Redo forward while the next-to-pop redo entry's timestamp is at
3191    /// or before `target`. Returns the number of steps applied.
3192    ///
3193    /// Vim `:later Ns` semantics: `target = current_state_time + N seconds`.
3194    pub fn later_by_time(&mut self, target: SystemTime) -> usize {
3195        let mut count = 0;
3196        loop {
3197            match self.redo_stack.last() {
3198                None => break,
3199                Some(entry) => {
3200                    if entry.timestamp > target {
3201                        break;
3202                    }
3203                }
3204            }
3205            crate::vim::do_redo(self);
3206            count += 1;
3207        }
3208        count
3209    }
3210
3211    /// Snapshot current buffer state onto the undo stack and clear
3212    /// the redo stack. Bounded by `settings.undo_levels` — older
3213    /// entries pruned. Call before any group of buffer mutations the
3214    /// user might want to undo as a single step.
3215    pub fn push_undo(&mut self) {
3216        self.push_undo_at(SystemTime::now());
3217    }
3218
3219    /// Like [`push_undo`] but uses a caller-supplied timestamp. Used by
3220    /// tests that need deterministic time values without `sleep`.
3221    #[doc(hidden)]
3222    pub fn push_undo_at(&mut self, timestamp: SystemTime) {
3223        let (rope, cursor) = self.snapshot();
3224        self.undo_stack.push(UndoEntry {
3225            rope,
3226            cursor,
3227            timestamp,
3228        });
3229        self.cap_undo();
3230        self.redo_stack.clear();
3231    }
3232
3233    /// Trim the undo stack down to `settings.undo_levels`, dropping
3234    /// the oldest entries. `undo_levels == 0` is treated as
3235    /// "unlimited" (vim's 0-means-no-undo semantics intentionally
3236    /// skipped — guarding with `> 0` is one line shorter than gating
3237    /// the cap path with an explicit zero-check above the call site).
3238    pub(crate) fn cap_undo(&mut self) {
3239        let cap = self.settings.undo_levels as usize;
3240        if cap > 0 && self.undo_stack.len() > cap {
3241            let diff = self.undo_stack.len() - cap;
3242            self.undo_stack.drain(..diff);
3243        }
3244    }
3245
3246    /// Test-only accessor for the undo stack length.
3247    #[doc(hidden)]
3248    pub fn undo_stack_len(&self) -> usize {
3249        self.undo_stack.len()
3250    }
3251
3252    /// Replace the buffer with `lines` joined by `\n` and set the
3253    /// cursor to `cursor`. Used by undo / `:e!` / snapshot restore
3254    /// paths. Marks the editor dirty.
3255    ///
3256    /// Emits a single whole-buffer `ContentEdit` describing the
3257    /// transition so the syntax layer can apply it as an `InputEdit`
3258    /// on the retained tree and run an INCREMENTAL parse — tree-sitter
3259    /// reuses unchanged subtrees and `Tree::changed_ranges` reports
3260    /// just the bytes that differ, which lets the install path walk
3261    /// only the changed rows instead of the full viewport. Big undos
3262    /// that revert a large paste now refresh in ~1ms per affected
3263    /// row instead of a ~30ms full-viewport sync walk.
3264    pub fn restore(&mut self, lines: Vec<String>, cursor: (usize, usize)) {
3265        let text = lines.join("\n");
3266        self.restore_text(&text, cursor);
3267    }
3268
3269    /// Restore the buffer from a `ropey::Rope` snapshot. Used by undo /
3270    /// redo: snapshots are stored as `Rope` (O(1) Arc-clone via
3271    /// `Buffer::rope()`), so this avoids the full-document `to_string`
3272    /// materialization that the old `Arc<String>` snapshot path forced
3273    /// on every undo group boundary.
3274    ///
3275    /// Internally materializes the rope to a `String` for `restore_text`
3276    /// — paying the cost on the restore side instead of the snapshot
3277    /// side trades one ~3 MB build per undo for none-per-snapshot. Undo
3278    /// is user-initiated and rare; snapshots fire on every `i` / `o`.
3279    pub fn restore_rope(&mut self, rope: ropey::Rope, cursor: (usize, usize)) {
3280        let text = rope.to_string();
3281        self.restore_text(&text, cursor);
3282    }
3283
3284    fn restore_text(&mut self, text: &str, cursor: (usize, usize)) {
3285        // Diff the old rope (O(1) Arc-clone) against the incoming text
3286        // to emit a minimal ContentEdit — without it the syntax layer's
3287        // tree.edit() marks the whole document changed and tree-sitter
3288        // cold-parses on every undo.
3289        let old_rope = self.buffer.rope();
3290        let edit = minimal_content_edit_rope(&old_rope, text);
3291
3292        crate::types::BufferEdit::replace_all(&mut self.buffer, text);
3293        buf_set_cursor_rc(&mut self.buffer, cursor.0, cursor.1);
3294
3295        // Bulk replace supersedes any prior queued edits.
3296        self.pending_content_edits.clear();
3297        self.pending_content_edits.push(edit);
3298        self.mark_content_dirty();
3299    }
3300
3301    /// Returns true if the key was consumed by the editor.
3302    /// Replace the char under the cursor with `ch`, `count` times. Matches
3303    /// vim `r<x>` semantics: cursor ends on the last replaced char, undo
3304    /// snapshot taken once at start. Promoted to public surface in 0.5.5
3305    /// so hjkl-vim's pending-state reducer can dispatch `Replace` without
3306    /// re-entering the FSM.
3307    pub fn replace_char_at(&mut self, ch: char, count: usize) {
3308        vim::replace_char(self, ch, count);
3309    }
3310
3311    /// Apply vim's `f<x>` / `F<x>` / `t<x>` / `T<x>` motion. Moves the cursor
3312    /// to the `count`-th occurrence of `ch` on the current line, respecting
3313    /// `forward` (direction) and `till` (stop one char before target).
3314    /// Records `last_find` so `;` / `,` repeat work.
3315    ///
3316    /// No-op if the target char isn't on the current line within range.
3317    /// Cursor / scroll / sticky-col semantics match `f<x>` via `execute_motion`.
3318    pub fn find_char(&mut self, ch: char, forward: bool, till: bool, count: usize) {
3319        vim::apply_find_char(self, ch, forward, till, count.max(1));
3320    }
3321
3322    /// Apply the g-chord effect for `g<ch>` with a pre-captured `count`.
3323    /// Mirrors the full `handle_after_g` dispatch table — `gg`, `gj`, `gk`,
3324    /// `gv`, `gU` / `gu` / `g~` (→ operator-pending), `gi`, `g*`, `g#`, etc.
3325    ///
3326    /// Promoted to public surface in 0.5.10 so hjkl-vim's
3327    /// `PendingState::AfterG` reducer can dispatch `AfterGChord` without
3328    /// re-entering the engine FSM.
3329    pub fn after_g(&mut self, ch: char, count: usize) {
3330        vim::apply_after_g(self, ch, count);
3331    }
3332
3333    /// Apply the z-chord effect for `z<ch>` with a pre-captured `count`.
3334    /// Mirrors the full `handle_after_z` dispatch table — `zz` / `zt` / `zb`
3335    /// (scroll-cursor), `zo` / `zc` / `za` / `zR` / `zM` / `zE` / `zd`
3336    /// (fold ops), and `zf` (fold-add over visual selection or → op-pending).
3337    ///
3338    /// Promoted to public surface in 0.5.11 so hjkl-vim's
3339    /// `PendingState::AfterZ` reducer can dispatch `AfterZChord` without
3340    /// re-entering the engine FSM.
3341    pub fn after_z(&mut self, ch: char, count: usize) {
3342        vim::apply_after_z(self, ch, count);
3343    }
3344
3345    /// Apply an operator over a single-key motion. `op` is the engine `Operator`
3346    /// and `motion_key` is the raw character (e.g. `'w'`, `'$'`, `'G'`). The
3347    /// engine resolves the char to a [`vim::Motion`] via `parse_motion`, applies
3348    /// the vim quirks (`cw` → `ce`, `cW` → `cE`, `FindRepeat` → stored find),
3349    /// then calls `apply_op_with_motion`. `total_count` is already the product of
3350    /// the prefix count and any inner count accumulated by the reducer.
3351    ///
3352    /// No-op when `motion_key` does not map to a known motion (engine silently
3353    /// cancels the operator, matching vim's behaviour on unknown motions).
3354    ///
3355    /// Promoted to the public surface in 0.5.12 so the hjkl-vim
3356    /// `PendingState::AfterOp` reducer can dispatch `ApplyOpMotion` without
3357    /// re-entering the engine FSM.
3358    pub fn apply_op_motion(
3359        &mut self,
3360        op: crate::vim::Operator,
3361        motion_key: char,
3362        total_count: usize,
3363    ) {
3364        vim::apply_op_motion_key(self, op, motion_key, total_count);
3365    }
3366
3367    /// Apply a doubled-letter line op (`dd` / `yy` / `cc` / `>>` / `<<`).
3368    /// `total_count` is the product of prefix count and inner count.
3369    ///
3370    /// Promoted to the public surface in 0.5.12 so the hjkl-vim
3371    /// `PendingState::AfterOp` reducer can dispatch `ApplyOpDouble` without
3372    /// re-entering the engine FSM.
3373    pub fn apply_op_double(&mut self, op: crate::vim::Operator, total_count: usize) {
3374        vim::apply_op_double(self, op, total_count);
3375    }
3376
3377    /// Apply an operator over a find motion (`df<x>` / `dF<x>` / `dt<x>` /
3378    /// `dT<x>`). Builds `Motion::Find { ch, forward, till }`, applies it via
3379    /// `apply_op_with_motion`, records `last_find` for `;` / `,` repeat, and
3380    /// updates `last_change` when `op` is Change (for dot-repeat).
3381    ///
3382    /// `total_count` is the product of prefix count and any inner count
3383    /// accumulated by the reducer — already folded at transition time.
3384    ///
3385    /// Promoted to the public surface in 0.5.14 so the hjkl-vim
3386    /// `PendingState::OpFind` reducer can dispatch `ApplyOpFind` without
3387    /// re-entering the engine FSM. `handle_op_find_target` (used by the
3388    /// chord-init op path) delegates here to avoid logic duplication.
3389    pub fn apply_op_find(
3390        &mut self,
3391        op: crate::vim::Operator,
3392        ch: char,
3393        forward: bool,
3394        till: bool,
3395        total_count: usize,
3396    ) {
3397        vim::apply_op_find_motion(self, op, ch, forward, till, total_count);
3398    }
3399
3400    /// Apply an operator over a text-object range (`diw` / `daw` / `di"` etc.).
3401    /// Maps `ch` to a `TextObject` per the standard vim table, calls
3402    /// `apply_op_with_text_object`, and records `last_change` when `op` is
3403    /// Change (dot-repeat). Unknown `ch` values are silently ignored (no-op),
3404    /// matching the engine FSM's behaviour on unrecognised text-object chars.
3405    ///
3406    /// `total_count` is accepted for API symmetry with `apply_op_motion` /
3407    /// `apply_op_find` but is currently unused — text objects don't repeat in
3408    /// vim's current grammar. Kept for future-proofing.
3409    ///
3410    /// Promoted to the public surface in 0.5.15 so the hjkl-vim
3411    /// `PendingState::OpTextObj` reducer can dispatch `ApplyOpTextObj` without
3412    /// re-entering the engine FSM. `handle_text_object` (chord-init op path)
3413    /// delegates to the shared `apply_op_text_obj_inner` helper to avoid logic
3414    /// duplication.
3415    pub fn apply_op_text_obj(
3416        &mut self,
3417        op: crate::vim::Operator,
3418        ch: char,
3419        inner: bool,
3420        total_count: usize,
3421    ) {
3422        vim::apply_op_text_obj_inner(self, op, ch, inner, total_count);
3423    }
3424
3425    /// Apply an operator over a g-chord motion or case-op linewise form
3426    /// (`dgg` / `dge` / `dgE` / `dgj` / `dgk` / `gUgU` etc.).
3427    ///
3428    /// - If `op` is Uppercase/Lowercase/ToggleCase and `ch` matches the op's
3429    ///   letter (`U`/`u`/`~`), executes the line op (linewise form).
3430    /// - Otherwise maps `ch` to a motion:
3431    ///   - `'g'` → `Motion::FileTop` (gg)
3432    ///   - `'e'` → `Motion::WordEndBack` (ge)
3433    ///   - `'E'` → `Motion::BigWordEndBack` (gE)
3434    ///   - `'j'` → `Motion::ScreenDown` (gj)
3435    ///   - `'k'` → `Motion::ScreenUp` (gk)
3436    ///   - unknown → no-op (silently ignored, matching engine FSM behaviour)
3437    /// - Updates `last_change` for dot-repeat when `op` is a change operator.
3438    ///
3439    /// `total_count` is the already-folded product of prefix and inner counts.
3440    ///
3441    /// Promoted to the public surface in 0.5.16 so the hjkl-vim
3442    /// `PendingState::OpG` reducer can dispatch `ApplyOpG` without
3443    /// re-entering the engine FSM. `handle_op_after_g` (chord-init op path)
3444    /// delegates to the shared `apply_op_g_inner` helper to avoid logic
3445    /// duplication.
3446    pub fn apply_op_g(&mut self, op: crate::vim::Operator, ch: char, total_count: usize) {
3447        vim::apply_op_g_inner(self, op, ch, total_count);
3448    }
3449
3450    // ─── Range-query helpers for partial-format dispatch (#119) ─────────────
3451
3452    /// Dry-run `motion_key` and return `(min_row, max_row)` between the cursor
3453    /// row and the motion's target row. Used by the app layer to compute the
3454    /// [`hjkl_mangler::RangeSpec`] for `=<motion>` before submitting the async
3455    /// format job.
3456    ///
3457    /// Returns `None` when `motion_key` does not map to a known motion (same
3458    /// condition that makes `apply_op_motion` a no-op).
3459    ///
3460    /// The cursor is restored to its original position after the probe —
3461    /// the buffer content is not touched.
3462    pub fn range_for_op_motion(
3463        &mut self,
3464        motion_key: char,
3465        total_count: usize,
3466    ) -> Option<(usize, usize)> {
3467        let start = self.cursor();
3468        // Reuse the same logic as apply_op_motion_key but only read the
3469        // target row — we parse the motion, apply it to move the cursor,
3470        // then immediately restore.
3471        let input = crate::input::Input {
3472            key: crate::input::Key::Char(motion_key),
3473            ctrl: false,
3474            alt: false,
3475            shift: false,
3476        };
3477        let motion = vim::parse_motion(&input)?;
3478        // Resolve FindRepeat and cw/cW quirks just like apply_op_motion_key.
3479        let motion = match motion {
3480            vim::Motion::FindRepeat { reverse } => match self.vim.last_find {
3481                Some((ch, forward, till)) => vim::Motion::Find {
3482                    ch,
3483                    forward: if reverse { !forward } else { forward },
3484                    till,
3485                },
3486                None => return None,
3487            },
3488            m => m,
3489        };
3490        vim::apply_motion_cursor_ctx(self, &motion, total_count, true);
3491        let end = self.cursor();
3492        // Restore cursor.
3493        buf_set_cursor_rc(&mut self.buffer, start.0, start.1);
3494        let (r0, r1) = (start.0.min(end.0), start.0.max(end.0));
3495        Some((r0, r1))
3496    }
3497
3498    /// Dry-run a `g`-prefixed motion and return `(min_row, max_row)`. Used for
3499    /// `=gg` / `=gj` etc. Returns `None` for unknown `ch` values or case-op
3500    /// linewise forms that don't map to a row range.
3501    ///
3502    /// The cursor is restored after the probe.
3503    pub fn range_for_op_g(&mut self, ch: char, total_count: usize) -> Option<(usize, usize)> {
3504        let start = self.cursor();
3505        let motion = match ch {
3506            'g' => vim::Motion::FileTop,
3507            'e' => vim::Motion::WordEndBack,
3508            'E' => vim::Motion::BigWordEndBack,
3509            'j' => vim::Motion::ScreenDown,
3510            'k' => vim::Motion::ScreenUp,
3511            _ => return None,
3512        };
3513        vim::apply_motion_cursor_ctx(self, &motion, total_count, true);
3514        let end = self.cursor();
3515        buf_set_cursor_rc(&mut self.buffer, start.0, start.1);
3516        let (r0, r1) = (start.0.min(end.0), start.0.max(end.0));
3517        Some((r0, r1))
3518    }
3519
3520    /// Dry-run a text-object lookup and return `(min_row, max_row)` for the
3521    /// matched region. Returns `None` when `ch` is not a known text-object
3522    /// kind or the text object could not be resolved (e.g. no enclosing bracket).
3523    ///
3524    /// The buffer is not mutated.
3525    pub fn range_for_op_text_obj(
3526        &self,
3527        ch: char,
3528        inner: bool,
3529        total_count: usize,
3530    ) -> Option<(usize, usize)> {
3531        let obj = match ch {
3532            'w' => vim::TextObject::Word { big: false },
3533            'W' => vim::TextObject::Word { big: true },
3534            '"' | '\'' | '`' => vim::TextObject::Quote(ch),
3535            '(' | ')' | 'b' => vim::TextObject::Bracket('('),
3536            '[' | ']' => vim::TextObject::Bracket('['),
3537            '{' | '}' | 'B' => vim::TextObject::Bracket('{'),
3538            '<' | '>' => vim::TextObject::Bracket('<'),
3539            'p' => vim::TextObject::Paragraph,
3540            't' => vim::TextObject::XmlTag,
3541            's' => vim::TextObject::Sentence,
3542            _ => return None,
3543        };
3544        let (start, end, _kind) = vim::text_object_range(self, obj, inner, total_count.max(1))?;
3545        let (r0, r1) = (start.0.min(end.0), start.0.max(end.0));
3546        Some((r0, r1))
3547    }
3548
3549    // ─── Phase 4a: pub range-mutation primitives (hjkl#70) ──────────────────
3550    //
3551    // These do not consume input — the caller (hjkl-vim's visual-mode operator
3552    // path, chunk 4e) has already resolved the range from the visual selection
3553    // before calling in. Normal-mode op dispatch continues to use
3554    // `apply_op_motion` / `apply_op_double` / `apply_op_find` / `apply_op_text_obj`.
3555
3556    /// Delete the region `[start, end)` and stash the removed text in
3557    /// `register`. `'"'` selects the unnamed register (vim default); `'a'`–`'z'`
3558    /// select named registers.
3559    ///
3560    /// Pure range-mutation primitive — does not consume input. Called by
3561    /// hjkl-vim's visual-mode operator path which has already resolved the range
3562    /// from the visual selection.
3563    ///
3564    /// Promoted to the public surface in 0.6.7 for Phase 4 visual-mode op
3565    /// grammar migration (kryptic-sh/hjkl#70).
3566    pub fn delete_range(
3567        &mut self,
3568        start: (usize, usize),
3569        end: (usize, usize),
3570        kind: crate::vim::RangeKind,
3571        register: char,
3572    ) {
3573        vim::delete_range_bridge(self, start, end, kind, register);
3574    }
3575
3576    /// Yank (copy) the region `[start, end)` into `register` without mutating
3577    /// the buffer. `'"'` selects the unnamed register; `'0'` the yank-only
3578    /// register; `'a'`–`'z'` select named registers.
3579    ///
3580    /// Pure range-mutation primitive — does not consume input. Called by
3581    /// hjkl-vim's visual-mode operator path which has already resolved the range
3582    /// from the visual selection.
3583    ///
3584    /// Promoted to the public surface in 0.6.7 for Phase 4 visual-mode op
3585    /// grammar migration (kryptic-sh/hjkl#70).
3586    pub fn yank_range(
3587        &mut self,
3588        start: (usize, usize),
3589        end: (usize, usize),
3590        kind: crate::vim::RangeKind,
3591        register: char,
3592    ) {
3593        vim::yank_range_bridge(self, start, end, kind, register);
3594    }
3595
3596    /// Delete the region `[start, end)` and transition to Insert mode (vim `c`
3597    /// operator). The deleted text is stashed in `register`. On return the
3598    /// editor is in Insert mode; the caller must not issue further normal-mode
3599    /// ops until the insert session ends.
3600    ///
3601    /// Pure range-mutation primitive — does not consume input. Called by
3602    /// hjkl-vim's visual-mode operator path which has already resolved the range
3603    /// from the visual selection.
3604    ///
3605    /// Promoted to the public surface in 0.6.7 for Phase 4 visual-mode op
3606    /// grammar migration (kryptic-sh/hjkl#70).
3607    pub fn change_range(
3608        &mut self,
3609        start: (usize, usize),
3610        end: (usize, usize),
3611        kind: crate::vim::RangeKind,
3612        register: char,
3613    ) {
3614        vim::change_range_bridge(self, start, end, kind, register);
3615    }
3616
3617    /// Indent (`count > 0`) or outdent (`count < 0`) the row span
3618    /// `[start.0, end.0]`. Column components are ignored — indent is always
3619    /// linewise. `shiftwidth` overrides the editor's configured shiftwidth for
3620    /// this call; pass `0` to use the current editor setting. `count == 0` is a
3621    /// no-op.
3622    ///
3623    /// Pure range-mutation primitive — does not consume input. Called by
3624    /// hjkl-vim's visual-mode operator path which has already resolved the range
3625    /// from the visual selection.
3626    ///
3627    /// Promoted to the public surface in 0.6.7 for Phase 4 visual-mode op
3628    /// grammar migration (kryptic-sh/hjkl#70).
3629    pub fn indent_range(
3630        &mut self,
3631        start: (usize, usize),
3632        end: (usize, usize),
3633        count: i32,
3634        shiftwidth: u32,
3635    ) {
3636        vim::indent_range_bridge(self, start, end, count, shiftwidth);
3637    }
3638
3639    /// Apply a case transformation (`Operator::Uppercase` /
3640    /// `Operator::Lowercase` / `Operator::ToggleCase`) to the region
3641    /// `[start, end)`. Other `Operator` variants are silently ignored (no-op).
3642    /// Yanks registers are left untouched — vim's case operators do not write
3643    /// to registers.
3644    ///
3645    /// Pure range-mutation primitive — does not consume input. Called by
3646    /// hjkl-vim's visual-mode operator path which has already resolved the range
3647    /// from the visual selection.
3648    ///
3649    /// Promoted to the public surface in 0.6.7 for Phase 4 visual-mode op
3650    /// grammar migration (kryptic-sh/hjkl#70).
3651    pub fn case_range(
3652        &mut self,
3653        start: (usize, usize),
3654        end: (usize, usize),
3655        kind: crate::vim::RangeKind,
3656        op: crate::vim::Operator,
3657    ) {
3658        vim::case_range_bridge(self, start, end, kind, op);
3659    }
3660
3661    // ─── Phase 4e: pub block-shape range-mutation primitives (hjkl#70) ──────
3662    //
3663    // Rectangular VisualBlock operations. `top_row`/`bot_row` are inclusive
3664    // line indices; `left_col`/`right_col` are inclusive char-column bounds.
3665    // Ragged-edge handling (short lines not reaching `right_col`) matches the
3666    // engine FSM's `apply_block_operator` path — short lines lose only the
3667    // chars that exist.
3668    //
3669    // `register` is the target register; `'"'` selects the unnamed register.
3670
3671    /// Delete a rectangular VisualBlock selection. `top_row` / `bot_row` are
3672    /// inclusive line bounds; `left_col` / `right_col` are inclusive column
3673    /// bounds at the visual (display) column level. Ragged-edge handling
3674    /// matches engine FSM's VisualBlock op behavior — short lines that don't
3675    /// reach `right_col` lose only the chars that exist.
3676    ///
3677    /// `register` honors the user's pending register selection.
3678    ///
3679    /// Promoted in 0.6.X for Phase 4e block-op grammar migration.
3680    pub fn delete_block(
3681        &mut self,
3682        top_row: usize,
3683        bot_row: usize,
3684        left_col: usize,
3685        right_col: usize,
3686        register: char,
3687    ) {
3688        vim::delete_block_bridge(self, top_row, bot_row, left_col, right_col, register);
3689    }
3690
3691    /// Yank a rectangular VisualBlock selection into `register` without
3692    /// mutating the buffer. `'"'` selects the unnamed register.
3693    ///
3694    /// Promoted in 0.6.X for Phase 4e block-op grammar migration.
3695    pub fn yank_block(
3696        &mut self,
3697        top_row: usize,
3698        bot_row: usize,
3699        left_col: usize,
3700        right_col: usize,
3701        register: char,
3702    ) {
3703        vim::yank_block_bridge(self, top_row, bot_row, left_col, right_col, register);
3704    }
3705
3706    /// Delete a rectangular VisualBlock selection and enter Insert mode (`c`
3707    /// operator). The deleted text is stashed in `register`. Mode is Insert
3708    /// on return; the caller must not issue further normal-mode ops until the
3709    /// insert session ends.
3710    ///
3711    /// Promoted in 0.6.X for Phase 4e block-op grammar migration.
3712    pub fn change_block(
3713        &mut self,
3714        top_row: usize,
3715        bot_row: usize,
3716        left_col: usize,
3717        right_col: usize,
3718        register: char,
3719    ) {
3720        vim::change_block_bridge(self, top_row, bot_row, left_col, right_col, register);
3721    }
3722
3723    /// Indent (`count > 0`) or outdent (`count < 0`) rows `top_row..=bot_row`.
3724    /// Column bounds are ignored — vim's block indent is always linewise.
3725    /// `count == 0` is a no-op.
3726    ///
3727    /// Promoted in 0.6.X for Phase 4e block-op grammar migration.
3728    pub fn indent_block(
3729        &mut self,
3730        top_row: usize,
3731        bot_row: usize,
3732        _left_col: usize,
3733        _right_col: usize,
3734        count: i32,
3735    ) {
3736        vim::indent_block_bridge(self, top_row, bot_row, count);
3737    }
3738
3739    /// Auto-indent (v1 dumb shiftwidth) the row span `[start.0, end.0]`.
3740    /// Column components are ignored — auto-indent is always linewise.
3741    ///
3742    /// The algorithm is a naive bracket-depth counter: it scans the buffer from
3743    /// row 0 to compute the correct depth at `start.0`, then for each line in
3744    /// the target range strips existing leading whitespace and prepends
3745    /// `depth × indent_unit` where `indent_unit` is `"\t"` when `expandtab`
3746    /// is `false`, or `" " × shiftwidth` when `expandtab` is `true`. Lines
3747    /// whose first non-whitespace character is a close bracket (`}`, `)`, `]`)
3748    /// get one fewer indent level. Empty / whitespace-only lines are cleared.
3749    ///
3750    /// After the operation the cursor lands on the first non-whitespace
3751    /// character of `start_row` (vim parity for `==`).
3752    ///
3753    /// **v1 limitation**: the bracket scan does not detect brackets inside
3754    /// string literals or comments. Code such as `let s = "{";` will increment
3755    /// the depth counter even though the brace is not a structural opener.
3756    /// Tree-sitter / LSP indentation is deferred to a follow-up.
3757    pub fn auto_indent_range(&mut self, start: (usize, usize), end: (usize, usize)) {
3758        vim::auto_indent_range_bridge(self, start, end);
3759    }
3760
3761    /// Drain the row range set by the most recent auto-indent operation.
3762    ///
3763    /// Returns `Some((top_row, bot_row))` (inclusive) on the first call after
3764    /// an `=` / `==` / `=G` / Visual-`=` operator, then clears the stored
3765    /// value so a subsequent call returns `None`. The host (e.g. `apps/hjkl`)
3766    /// uses this to arm a brief visual flash over the reindented rows.
3767    pub fn take_last_indent_range(&mut self) -> Option<(usize, usize)> {
3768        self.last_indent_range.take()
3769    }
3770
3771    /// Filter rows `top_row..=bot_row` through an external shell command.
3772    ///
3773    /// Spawns `sh -c "<command>"` (or `cmd /C "<command>"` on Windows), pipes
3774    /// the selected lines (joined by `\n`) to stdin, and waits up to
3775    /// `timeout_secs` seconds (default 10) for the process to finish.
3776    ///
3777    /// On success: the rows are replaced with stdout. No trailing-newline trim.
3778    /// On non-zero exit, spawn failure, or timeout: returns `Err(stderr_or_msg)`
3779    /// without mutating the buffer.
3780    ///
3781    /// `top_row` and `bot_row` are clamped to the buffer's valid row range.
3782    pub fn filter_range(
3783        &mut self,
3784        top_row: usize,
3785        bot_row: usize,
3786        command: &str,
3787        timeout_secs: Option<u64>,
3788    ) -> Result<(), String> {
3789        use std::io::Write;
3790        use std::process::{Command, Stdio};
3791        use std::thread;
3792        use std::time::Instant;
3793
3794        let timeout = std::time::Duration::from_secs(timeout_secs.unwrap_or(10));
3795        let rope = crate::types::Query::rope(self.buffer());
3796        let line_count = rope.len_lines();
3797        let top = top_row.min(line_count.saturating_sub(1));
3798        let bot = bot_row.min(line_count.saturating_sub(1));
3799        let (top, bot) = (top.min(bot), top.max(bot));
3800        let input_text = crate::vim::rope_row_range_str(&rope, top, bot);
3801        // Materialized for the splice-back after the command succeeds.
3802        let lines = crate::vim::rope_to_lines_vec(&rope);
3803
3804        tracing::debug!(
3805            top_row = top,
3806            bot_row = bot,
3807            command = command,
3808            "filter_range: spawning shell command"
3809        );
3810
3811        #[cfg(not(windows))]
3812        let mut child = Command::new("sh")
3813            .args(["-c", command])
3814            .stdin(Stdio::piped())
3815            .stdout(Stdio::piped())
3816            .stderr(Stdio::piped())
3817            .spawn()
3818            .map_err(|e| format!("spawn failed: {e}"))?;
3819
3820        #[cfg(windows)]
3821        let mut child = Command::new("cmd")
3822            .args(["/C", command])
3823            .stdin(Stdio::piped())
3824            .stdout(Stdio::piped())
3825            .stderr(Stdio::piped())
3826            .spawn()
3827            .map_err(|e| format!("spawn failed: {e}"))?;
3828
3829        // Write stdin on a thread to avoid deadlock when output > pipe buffer.
3830        let mut stdin = child.stdin.take().ok_or("no stdin handle")?;
3831        let input_bytes = input_text.into_bytes();
3832        thread::spawn(move || {
3833            let _ = stdin.write_all(&input_bytes);
3834            // stdin drops here, signalling EOF to the child.
3835        });
3836
3837        // Drain stdout/stderr on separate threads so the child's pipes don't
3838        // fill and deadlock the child. Keep `child` here so we can kill it on
3839        // timeout.
3840        let mut stdout_pipe = child.stdout.take().ok_or("no stdout handle")?;
3841        let mut stderr_pipe = child.stderr.take().ok_or("no stderr handle")?;
3842        let stdout_thread = thread::spawn(move || {
3843            let mut buf = Vec::new();
3844            let _ = std::io::Read::read_to_end(&mut stdout_pipe, &mut buf);
3845            buf
3846        });
3847        let stderr_thread = thread::spawn(move || {
3848            let mut buf = Vec::new();
3849            let _ = std::io::Read::read_to_end(&mut stderr_pipe, &mut buf);
3850            buf
3851        });
3852
3853        // Poll try_wait until exit or timeout. On timeout: SIGKILL the child
3854        // (std Child::kill sends SIGKILL on Unix / TerminateProcess on Windows).
3855        // A proper TERM→KILL escalation would need nix/libc; skip for v1.
3856        let start = Instant::now();
3857        let status = loop {
3858            match child.try_wait() {
3859                Ok(Some(status)) => break status,
3860                Ok(None) => {
3861                    if start.elapsed() >= timeout {
3862                        tracing::debug!(command, "filter_range: timeout — killing child");
3863                        let _ = child.kill();
3864                        let _ = child.wait(); // reap so the OS can free resources
3865                        return Err(format!("command timed out after {}s", timeout.as_secs()));
3866                    }
3867                    thread::sleep(std::time::Duration::from_millis(20));
3868                }
3869                Err(e) => return Err(format!("wait failed: {e}")),
3870            }
3871        };
3872
3873        let stdout_bytes = stdout_thread.join().unwrap_or_default();
3874        let stderr_bytes = stderr_thread.join().unwrap_or_default();
3875
3876        if !status.success() {
3877            let stderr = String::from_utf8_lossy(&stderr_bytes).into_owned();
3878            tracing::debug!(
3879                command,
3880                exit_code = ?status.code(),
3881                "filter_range: command exited with non-zero status"
3882            );
3883            return Err(if stderr.is_empty() {
3884                format!("command exited with status {}", status.code().unwrap_or(-1))
3885            } else {
3886                stderr
3887            });
3888        }
3889
3890        let stdout = String::from_utf8_lossy(&stdout_bytes).into_owned();
3891        tracing::debug!(
3892            command,
3893            stdout_bytes = stdout_bytes.len(),
3894            "filter_range: command succeeded, replacing rows"
3895        );
3896
3897        // Replace the row range with the stdout lines.
3898        let mut all_lines = lines;
3899        let new_lines: Vec<String> = stdout.lines().map(|l| l.to_owned()).collect();
3900        // If stdout ended with a newline, stdout.lines() drops the trailing empty
3901        // entry — this preserves vim's "no trailing-newline trim" spec because
3902        // a trailing '\n' from the command means the last replacement line is the
3903        // line BEFORE the newline, not an empty line after it.
3904        let after = all_lines.split_off(bot + 1);
3905        all_lines.truncate(top);
3906        all_lines.extend(new_lines);
3907        all_lines.extend(after);
3908
3909        self.push_undo();
3910        self.restore(all_lines, (top, 0));
3911        // Leave mode as Normal after a successful filter operation (vim parity).
3912        self.force_normal();
3913
3914        Ok(())
3915    }
3916
3917    // ─── Comment toggle (#187) ───────────────────────────────────────────────
3918
3919    /// Toggle line comments on rows `top_row..=bot_row` (0-based, inclusive).
3920    ///
3921    /// **Algorithm** (vim-commentary parity):
3922    ///
3923    /// 1. Determine the comment marker(s) for the active filetype.
3924    ///    Priority: `settings.commentstring` (`:set commentstring=…`) → per-filetype
3925    ///    default from `hjkl_lang::comment::commentstring_for_lang` → no-op.
3926    /// 2. Scan non-blank lines.  If every non-blank line is already commented →
3927    ///    strip the comment marker from each.  Otherwise → add it to all non-blank
3928    ///    lines.
3929    /// 3. Blank / whitespace-only lines are skipped (no marker added or removed).
3930    /// 4. The marker is inserted AFTER the leading whitespace (indent-preserving).
3931    /// 5. The entire operation is a single undo step.
3932    ///
3933    /// For block-comment languages (HTML, CSS) each line is individually wrapped
3934    /// as `start text end` (per-line block style, not one multi-line block).
3935    ///
3936    /// `top_row` and `bot_row` are clamped to the buffer's valid row range.
3937    pub fn toggle_comment_range(&mut self, top_row: usize, bot_row: usize) {
3938        use hjkl_lang::comment::commentstring_for_lang;
3939
3940        let lang = self.settings.filetype.clone();
3941
3942        // Resolve the comment markers.
3943        // If `settings.commentstring` is set (non-empty) parse `start %s end`
3944        // from it; otherwise fall back to the filetype table.
3945        let (start, end) = if !self.settings.commentstring.is_empty() {
3946            let cs = &self.settings.commentstring;
3947            if let Some(idx) = cs.find("%s") {
3948                let s = cs[..idx].trim_end().to_string();
3949                let e_raw = cs[idx + 2..].trim_start();
3950                let e: Option<String> = if e_raw.is_empty() {
3951                    None
3952                } else {
3953                    Some(e_raw.to_string())
3954                };
3955                (s, e)
3956            } else {
3957                // No %s placeholder — treat the whole string as start marker.
3958                (cs.clone(), None)
3959            }
3960        } else {
3961            match commentstring_for_lang(&lang) {
3962                Some((s, e)) => (s.to_string(), e.map(|v| v.to_string())),
3963                None => return, // no known comment syntax → no-op
3964            }
3965        };
3966
3967        let row_count = buf_row_count(&self.buffer);
3968        let top = top_row.min(row_count.saturating_sub(1));
3969        let bot = bot_row.min(row_count.saturating_sub(1));
3970
3971        // Collect all lines in the range.
3972        let lines: Vec<String> = (top..=bot)
3973            .map(|r| buf_line(&self.buffer, r).unwrap_or_default())
3974            .collect();
3975
3976        // Check whether every non-blank line is already commented.
3977        let all_commented = lines.iter().all(|line| {
3978            let trimmed = line.trim_start();
3979            if trimmed.is_empty() {
3980                return true; // blank lines don't count against "all commented"
3981            }
3982            if let Some(ref end_marker) = end {
3983                // Block style: line starts with start and ends with end.
3984                trimmed.starts_with(start.as_str())
3985                    && line.trim_end().ends_with(end_marker.as_str())
3986            } else {
3987                trimmed.starts_with(start.as_str())
3988            }
3989        });
3990
3991        let mut new_lines: Vec<String> = Vec::with_capacity(lines.len());
3992        for line in &lines {
3993            let trimmed = line.trim_start();
3994            if trimmed.is_empty() {
3995                // Blank line — leave as-is.
3996                new_lines.push(line.clone());
3997                continue;
3998            }
3999            let indent_len = line.len() - trimmed.len();
4000            let indent = &line[..indent_len];
4001
4002            if all_commented {
4003                // Uncomment: strip exactly one occurrence of start (+ optional space).
4004                if let Some(after_start) = trimmed.strip_prefix(start.as_str()) {
4005                    // Strip one leading space after the marker if present.
4006                    let after_space = after_start.strip_prefix(' ').unwrap_or(after_start);
4007                    // For block style also strip the trailing end marker.
4008                    let text = if let Some(ref end_marker) = end {
4009                        after_space
4010                            .trim_end()
4011                            .strip_suffix(end_marker.as_str())
4012                            .map(|s| s.trim_end())
4013                            .unwrap_or(after_space)
4014                    } else {
4015                        after_space
4016                    };
4017                    new_lines.push(format!("{indent}{text}"));
4018                } else {
4019                    new_lines.push(line.clone());
4020                }
4021            } else {
4022                // Comment: insert marker after indent.
4023                let commented = if let Some(ref end_marker) = end {
4024                    format!("{indent}{start} {trimmed} {end_marker}")
4025                } else {
4026                    format!("{indent}{start} {trimmed}")
4027                };
4028                new_lines.push(commented);
4029            }
4030        }
4031
4032        // Replace the row range in the buffer — single undo step.
4033        self.push_undo();
4034        let row_count_after = buf_row_count(&self.buffer);
4035        let all_before: Vec<String> = (0..top)
4036            .map(|r| buf_line(&self.buffer, r).unwrap_or_default())
4037            .collect();
4038        let all_after: Vec<String> = ((bot + 1)..row_count_after)
4039            .map(|r| buf_line(&self.buffer, r).unwrap_or_default())
4040            .collect();
4041        let mut all: Vec<String> = all_before;
4042        all.extend(new_lines);
4043        all.extend(all_after);
4044        self.restore(all, (top, 0));
4045    }
4046
4047    // ─── Phase 4b: pub text-object resolution (hjkl#70) ─────────────────────
4048    //
4049    // Pure functions — no cursor mutation, no mode change, no register write.
4050    // Each method delegates to `vim::text_object_*_bridge`, which in turn calls
4051    // the existing `word_text_object` private resolver in vim.rs.
4052    //
4053    // Called by hjkl-vim's `OpTextObj` reducer (chunk 4e) to resolve the range
4054    // before invoking a range-mutation primitive (`delete_range`, etc.).
4055    //
4056    // Return value: `Some((start, end))` where both positions are `(row, col)`
4057    // byte-column pairs and `end` is *exclusive* (one past the last byte to act
4058    // on), matching the convention used by `delete_range` / `yank_range` / etc.
4059    // Returns `None` when the cursor is on an empty line or the resolver cannot
4060    // find a word boundary.
4061
4062    /// Resolve the range of `iw` (inner word) at the current cursor position.
4063    ///
4064    /// An inner word is the contiguous run of keyword characters (or punctuation
4065    /// characters if the cursor is on punctuation) under the cursor, without any
4066    /// surrounding whitespace. Whitespace-only positions return `None`.
4067    ///
4068    /// Pure function — does not move the cursor or change any editor state.
4069    /// Called by hjkl-vim's `OpTextObj` reducer to resolve the range before
4070    /// invoking a range-mutation primitive (`delete_range`, etc.).
4071    ///
4072    /// Promoted to the public surface in 0.6.X for Phase 4b text-object grammar
4073    /// migration (kryptic-sh/hjkl#70).
4074    pub fn text_object_inner_word(&self) -> Option<((usize, usize), (usize, usize))> {
4075        vim::text_object_inner_word_bridge(self)
4076    }
4077
4078    /// Resolve the range of `aw` (around word) at the current cursor position.
4079    ///
4080    /// Like `iw` but extends the range to include trailing whitespace after the
4081    /// word. If no trailing whitespace exists, leading whitespace before the word
4082    /// is absorbed instead (vim `:help text-objects` behaviour).
4083    ///
4084    /// Pure function — does not move the cursor or change any editor state.
4085    ///
4086    /// Promoted to the public surface in 0.6.X for Phase 4b text-object grammar
4087    /// migration (kryptic-sh/hjkl#70).
4088    pub fn text_object_around_word(&self) -> Option<((usize, usize), (usize, usize))> {
4089        vim::text_object_around_word_bridge(self)
4090    }
4091
4092    /// Resolve the range of `iW` (inner WORD) at the current cursor position.
4093    ///
4094    /// A WORD is any contiguous run of non-whitespace characters — punctuation
4095    /// is not treated as a word boundary. Returns the span of the WORD under the
4096    /// cursor, without surrounding whitespace.
4097    ///
4098    /// Pure function — does not move the cursor or change any editor state.
4099    ///
4100    /// Promoted to the public surface in 0.6.X for Phase 4b text-object grammar
4101    /// migration (kryptic-sh/hjkl#70).
4102    pub fn text_object_inner_big_word(&self) -> Option<((usize, usize), (usize, usize))> {
4103        vim::text_object_inner_big_word_bridge(self)
4104    }
4105
4106    /// Resolve the range of `aW` (around WORD) at the current cursor position.
4107    ///
4108    /// Like `iW` but extends the range to include trailing whitespace after the
4109    /// WORD. If no trailing whitespace exists, leading whitespace before the WORD
4110    /// is absorbed instead.
4111    ///
4112    /// Pure function — does not move the cursor or change any editor state.
4113    ///
4114    /// Promoted to the public surface in 0.6.X for Phase 4b text-object grammar
4115    /// migration (kryptic-sh/hjkl#70).
4116    pub fn text_object_around_big_word(&self) -> Option<((usize, usize), (usize, usize))> {
4117        vim::text_object_around_big_word_bridge(self)
4118    }
4119
4120    // ─── Phase 4c: pub text-object resolution — quote + bracket (hjkl#70) ───
4121    //
4122    // Pure functions — no cursor mutation, no mode change, no register write.
4123    // Each method delegates to `vim::text_object_*_bridge`, which in turn calls
4124    // the existing private resolvers (`quote_text_object`, `bracket_text_object`)
4125    // in vim.rs.
4126    //
4127    // Quote methods take the quote char itself (`'"'`, `'\''`, `` '`' ``).
4128    // Bracket methods take the OPEN bracket char (`'('`, `'{'`, `'['`, `'<'`);
4129    // close-bracket variants (`)`, `}`, `]`, `>`) are NOT accepted here — the
4130    // hjkl-vim grammar layer normalises close→open before calling these methods.
4131    //
4132    // Return value: `Some((start, end))` where both positions are `(row, col)`
4133    // byte-column pairs and `end` is *exclusive* (one past the last byte to act
4134    // on), matching the convention used by `delete_range` / `yank_range` / etc.
4135    // `bracket_text_object` internally distinguishes Linewise vs Exclusive
4136    // ranges for multi-line pairs; that tag is stripped here — callers receive
4137    // the same flat shape as all other text-object resolvers.
4138
4139    /// Resolve the range of `i<quote>` (inner quote) at the cursor position.
4140    ///
4141    /// `quote` is one of `'"'`, `'\''`, or `` '`' ``. Returns `None` when the
4142    /// cursor's line contains fewer than two occurrences of `quote`, or when no
4143    /// matching pair can be found around or ahead of the cursor.
4144    ///
4145    /// Inner range excludes the quote characters themselves.
4146    ///
4147    /// Pure function — no cursor mutation.
4148    ///
4149    /// Promoted to the public surface in 0.6.X for Phase 4c text-object grammar
4150    /// migration (kryptic-sh/hjkl#70).
4151    pub fn text_object_inner_quote(&self, quote: char) -> Option<((usize, usize), (usize, usize))> {
4152        vim::text_object_inner_quote_bridge(self, quote)
4153    }
4154
4155    /// Resolve the range of `a<quote>` (around quote) at the cursor position.
4156    ///
4157    /// Like `i<quote>` but includes the quote characters themselves plus
4158    /// surrounding whitespace on one side: trailing whitespace after the closing
4159    /// quote if any exists; otherwise leading whitespace before the opening
4160    /// quote. This matches vim `:help text-objects` behaviour.
4161    ///
4162    /// Pure function — no cursor mutation.
4163    ///
4164    /// Promoted to the public surface in 0.6.X for Phase 4c text-object grammar
4165    /// migration (kryptic-sh/hjkl#70).
4166    pub fn text_object_around_quote(
4167        &self,
4168        quote: char,
4169    ) -> Option<((usize, usize), (usize, usize))> {
4170        vim::text_object_around_quote_bridge(self, quote)
4171    }
4172
4173    /// Resolve the range of `i<bracket>` (inner bracket pair) at the cursor.
4174    ///
4175    /// `open` must be one of `'('`, `'{'`, `'['`, `'<'` — the corresponding
4176    /// close bracket is derived automatically. Close-bracket chars (`)`, `}`,
4177    /// `]`, `>`) are **not** accepted; hjkl-vim normalises close→open before
4178    /// calling this method. Returns `None` when no enclosing pair is found.
4179    ///
4180    /// The cursor may be anywhere inside the pair or on a bracket character
4181    /// itself. When not inside any pair the resolver falls back to a forward
4182    /// scan (targets.vim-style: `ci(` works when the cursor is before `(`).
4183    ///
4184    /// Inner range excludes the bracket characters. Multi-line pairs are
4185    /// supported; the returned range spans the full content between the
4186    /// brackets.
4187    ///
4188    /// Pure function — no cursor mutation.
4189    ///
4190    /// `ib` / `iB` aliases live in the hjkl-vim grammar layer and are not
4191    /// handled here.
4192    ///
4193    /// Promoted to the public surface in 0.6.X for Phase 4c text-object grammar
4194    /// migration (kryptic-sh/hjkl#70).
4195    pub fn text_object_inner_bracket(
4196        &self,
4197        open: char,
4198    ) -> Option<((usize, usize), (usize, usize))> {
4199        vim::text_object_inner_bracket_bridge(self, open)
4200    }
4201
4202    /// Resolve the range of `a<bracket>` (around bracket pair) at the cursor.
4203    ///
4204    /// Like `i<bracket>` but includes the bracket characters themselves.
4205    /// `open` must be one of `'('`, `'{'`, `'['`, `'<'`.
4206    ///
4207    /// Pure function — no cursor mutation.
4208    ///
4209    /// `aB` alias lives in the hjkl-vim grammar layer and is not handled here.
4210    ///
4211    /// Promoted to the public surface in 0.6.X for Phase 4c text-object grammar
4212    /// migration (kryptic-sh/hjkl#70).
4213    pub fn text_object_around_bracket(
4214        &self,
4215        open: char,
4216    ) -> Option<((usize, usize), (usize, usize))> {
4217        vim::text_object_around_bracket_bridge(self, open)
4218    }
4219
4220    // ── Sentence text objects (is / as) ───────────────────────────────────
4221
4222    /// Resolve `is` (inner sentence) at the cursor position.
4223    ///
4224    /// Returns the range of the current sentence, excluding trailing
4225    /// whitespace. Sentence boundaries follow vim's `is` semantics (period /
4226    /// `?` / `!` followed by whitespace or end-of-paragraph).
4227    ///
4228    /// Pure function — no cursor mutation.
4229    ///
4230    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
4231    /// grammar migration (kryptic-sh/hjkl#70).
4232    pub fn text_object_inner_sentence(&self) -> Option<((usize, usize), (usize, usize))> {
4233        vim::text_object_inner_sentence_bridge(self)
4234    }
4235
4236    /// Resolve `as` (around sentence) at the cursor position.
4237    ///
4238    /// Like `is` but includes trailing whitespace after the sentence
4239    /// terminator.
4240    ///
4241    /// Pure function — no cursor mutation.
4242    ///
4243    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
4244    /// grammar migration (kryptic-sh/hjkl#70).
4245    pub fn text_object_around_sentence(&self) -> Option<((usize, usize), (usize, usize))> {
4246        vim::text_object_around_sentence_bridge(self)
4247    }
4248
4249    // ── Paragraph text objects (ip / ap) ──────────────────────────────────
4250
4251    /// Resolve `ip` (inner paragraph) at the cursor position.
4252    ///
4253    /// A paragraph is a block of non-blank lines bounded by blank lines or
4254    /// buffer edges. Returns `None` when the cursor is on a blank line.
4255    ///
4256    /// Pure function — no cursor mutation.
4257    ///
4258    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
4259    /// grammar migration (kryptic-sh/hjkl#70).
4260    pub fn text_object_inner_paragraph(&self) -> Option<((usize, usize), (usize, usize))> {
4261        vim::text_object_inner_paragraph_bridge(self)
4262    }
4263
4264    /// Resolve `ap` (around paragraph) at the cursor position.
4265    ///
4266    /// Like `ip` but includes one trailing blank line when present.
4267    ///
4268    /// Pure function — no cursor mutation.
4269    ///
4270    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
4271    /// grammar migration (kryptic-sh/hjkl#70).
4272    pub fn text_object_around_paragraph(&self) -> Option<((usize, usize), (usize, usize))> {
4273        vim::text_object_around_paragraph_bridge(self)
4274    }
4275
4276    // ── Tag text objects (it / at) ────────────────────────────────────────
4277
4278    /// Resolve `it` (inner tag) at the cursor position.
4279    ///
4280    /// Matches XML/HTML-style `<tag>...</tag>` pairs. Returns the range of
4281    /// inner content between the open and close tags (excluding the tags
4282    /// themselves).
4283    ///
4284    /// Pure function — no cursor mutation.
4285    ///
4286    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
4287    /// grammar migration (kryptic-sh/hjkl#70).
4288    pub fn text_object_inner_tag(&self) -> Option<((usize, usize), (usize, usize))> {
4289        vim::text_object_inner_tag_bridge(self)
4290    }
4291
4292    /// Resolve `at` (around tag) at the cursor position.
4293    ///
4294    /// Like `it` but includes the open and close tag delimiters themselves.
4295    ///
4296    /// Pure function — no cursor mutation.
4297    ///
4298    /// Promoted to the public surface in 0.6.X for Phase 4d text-object
4299    /// grammar migration (kryptic-sh/hjkl#70).
4300    pub fn text_object_around_tag(&self) -> Option<((usize, usize), (usize, usize))> {
4301        vim::text_object_around_tag_bridge(self)
4302    }
4303
4304    /// Execute a named cursor motion `kind` repeated `count` times.
4305    ///
4306    /// Maps the keymap-layer `crate::MotionKind` to the engine's internal
4307    /// motion primitives, bypassing the engine FSM. Identical cursor semantics
4308    /// to the FSM path — sticky column, scroll sync, and big-jump tracking are
4309    /// all applied via `vim::execute_motion` (for Down/Up) or the same helpers
4310    /// used by the FSM arms.
4311    ///
4312    /// Introduced in 0.6.1 as the host entry point for Phase 3a of
4313    /// kryptic-sh/hjkl#69: the app keymap dispatches `AppAction::Motion` and
4314    /// calls this method rather than re-entering the engine FSM.
4315    ///
4316    /// Engine FSM arms for `h`/`j`/`k`/`l`/`<BS>`/`<Space>`/`+`/`-` remain
4317    /// intact for macro-replay coverage (macros re-feed raw keys through the
4318    /// FSM). This method is the keymap / controller path only.
4319    pub fn apply_motion(&mut self, kind: crate::MotionKind, count: usize) {
4320        vim::apply_motion_kind(self, kind, count);
4321    }
4322
4323    /// Set `vim.pending_register` to `Some(reg)` if `reg` is a valid register
4324    /// selector (`a`–`z`, `A`–`Z`, `0`–`9`, `"`, `+`, `*`, `_`). Invalid
4325    /// chars are silently ignored (no-op), matching the engine FSM's
4326    /// `handle_select_register` behaviour.
4327    ///
4328    /// Promoted to the public surface in 0.5.17 so the hjkl-vim
4329    /// `PendingState::SelectRegister` reducer can dispatch `SetPendingRegister`
4330    /// without re-entering the engine FSM. `handle_select_register` (engine FSM
4331    /// path for macro-replay / defensive coverage) delegates here to avoid
4332    /// logic duplication.
4333    pub fn set_pending_register(&mut self, reg: char) {
4334        if reg.is_ascii_alphanumeric() || matches!(reg, '"' | '+' | '*' | '_') {
4335            self.vim.pending_register = Some(reg);
4336        }
4337        // Invalid chars silently no-op (matches engine FSM behavior).
4338    }
4339
4340    /// Record a mark named `ch` at the current cursor position.
4341    ///
4342    /// Validates `ch` (must be `a`–`z` or `A`–`Z` to match vim's mark-name
4343    /// rules). Invalid chars are silently ignored (no-op), matching the engine
4344    /// FSM's `handle_set_mark` behaviour.
4345    ///
4346    /// Promoted to the public surface in 0.6.7 so the hjkl-vim
4347    /// `PendingState::SetMark` reducer can dispatch `EngineCmd::SetMark`
4348    /// without re-entering the engine FSM. `handle_set_mark` delegates here.
4349    pub fn set_mark_at_cursor(&mut self, ch: char) {
4350        vim::set_mark_at_cursor(self, ch);
4351    }
4352
4353    /// `.` dot-repeat: replay the last buffered change at the current cursor.
4354    /// `count` scales repeats (e.g. `3.` runs the last change 3 times). When
4355    /// `count` is 0, defaults to 1. No-op when no change has been buffered yet.
4356    ///
4357    /// Storage of `LastChange` stays inside engine for now; Phase 5c of
4358    /// kryptic-sh/hjkl#71 just lifts the `.` chord binding into the app
4359    /// keymap so the engine FSM `.` arm is no longer the entry point. Engine
4360    /// FSM `.` arm stays for macro-replay defensive coverage.
4361    pub fn replay_last_change(&mut self, count: usize) {
4362        vim::replay_last_change(self, count);
4363    }
4364
4365    /// Jump to the mark named `ch`, linewise (row only; col snaps to first
4366    /// non-blank). Pushes the pre-jump position onto the jumplist if the
4367    /// cursor actually moved.
4368    ///
4369    /// Accepts the same mark chars as vim's `'<ch>` command: `a`–`z`,
4370    /// `A`–`Z`, `'`/`` ` `` (jump-back peek), `.` (last edit), and the
4371    /// special auto-marks `[`, `]`, `<`, `>`. Unset marks and invalid chars
4372    /// are silently ignored (no-op), matching the engine FSM's
4373    /// `handle_goto_mark` behaviour.
4374    ///
4375    /// Promoted to the public surface in 0.6.7 so the hjkl-vim
4376    /// `PendingState::GotoMarkLine` reducer can dispatch
4377    /// `EngineCmd::GotoMarkLine` without re-entering the engine FSM.
4378    pub fn goto_mark_line(&mut self, ch: char) {
4379        vim::goto_mark(self, ch, true);
4380    }
4381
4382    /// Jump to the mark named `ch`, charwise (exact row + col). Pushes the
4383    /// pre-jump position onto the jumplist if the cursor actually moved.
4384    ///
4385    /// Accepts the same mark chars as vim's `` `<ch> `` command: `a`–`z`,
4386    /// `A`–`Z`, `'`/`` ` `` (jump-back peek), `.` (last edit), and the
4387    /// special auto-marks `[`, `]`, `<`, `>`. Unset marks and invalid chars
4388    /// are silently ignored (no-op), matching the engine FSM's
4389    /// `handle_goto_mark` behaviour.
4390    ///
4391    /// Promoted to the public surface in 0.6.7 so the hjkl-vim
4392    /// `PendingState::GotoMarkChar` reducer can dispatch
4393    /// `EngineCmd::GotoMarkChar` without re-entering the engine FSM.
4394    pub fn goto_mark_char(&mut self, ch: char) {
4395        vim::goto_mark(self, ch, false);
4396    }
4397
4398    /// Jump to the mark named `ch`, linewise. For uppercase marks (`'A'`–`'Z'`)
4399    /// that live in a different buffer, returns `MarkJump::CrossBuffer` so the
4400    /// app can switch slots before positioning the cursor. Returns
4401    /// `MarkJump::SameBuffer` for same-buffer / lowercase / special marks, and
4402    /// `MarkJump::Unset` when the mark is not set.
4403    pub fn try_goto_mark_line(&mut self, ch: char) -> MarkJump {
4404        vim::try_goto_mark(self, ch, true)
4405    }
4406
4407    /// Jump to the mark named `ch`, charwise. For uppercase marks (`'A'`–`'Z'`)
4408    /// that live in a different buffer, returns `MarkJump::CrossBuffer` so the
4409    /// app can switch slots before positioning the cursor. Returns
4410    /// `MarkJump::SameBuffer` for same-buffer / lowercase / special marks, and
4411    /// `MarkJump::Unset` when the mark is not set.
4412    pub fn try_goto_mark_char(&mut self, ch: char) -> MarkJump {
4413        vim::try_goto_mark(self, ch, false)
4414    }
4415
4416    // ── Macro controller API (Phase 5b) ──────────────────────────────────────
4417
4418    /// Begin recording keystrokes into register `reg`. The caller (app) is
4419    /// responsible for stopping the recording via `stop_macro_record` when the
4420    /// user presses bare `q`.
4421    ///
4422    /// - Uppercase `reg` (e.g. `'A'`) appends to the existing lowercase
4423    ///   recording by pre-seeding `recording_keys` with the decoded text of the
4424    ///   matching lowercase register, matching vim's capital-register append
4425    ///   semantics.
4426    /// - Lowercase `reg` clears `recording_keys` (fresh recording).
4427    /// - Invalid chars (non-alphabetic, non-digit) are silently ignored.
4428    ///
4429    /// Promoted to the public surface in Phase 5b so the app's
4430    /// `route_chord_key` can start a recording without re-entering the engine
4431    /// FSM. `handle_record_macro_target` (engine FSM path for macro-replay
4432    /// defensive coverage) continues to use the same logic via delegation.
4433    pub fn start_macro_record(&mut self, reg: char) {
4434        if !(reg.is_ascii_alphabetic() || reg.is_ascii_digit()) {
4435            return;
4436        }
4437        self.vim.recording_macro = Some(reg);
4438        if reg.is_ascii_uppercase() {
4439            // Seed recording_keys with the existing lowercase register's text
4440            // decoded back to inputs so capital-register append continues from
4441            // where the previous recording left off.
4442            let lower = reg.to_ascii_lowercase();
4443            let text = self
4444                .registers
4445                .read(lower)
4446                .map(|s| s.text.clone())
4447                .unwrap_or_default();
4448            self.vim.recording_keys = crate::input::decode_macro(&text);
4449        } else {
4450            self.vim.recording_keys.clear();
4451        }
4452    }
4453
4454    /// Finalize the active recording: encode `recording_keys` as text and write
4455    /// to the matching (lowercase) named register. Clears both `recording_macro`
4456    /// and `recording_keys`. No-ops if no recording is active.
4457    ///
4458    /// Promoted to the public surface in Phase 5b so the app's `QChord` action
4459    /// can stop a recording when the user presses bare `q` without re-entering
4460    /// the engine FSM.
4461    pub fn stop_macro_record(&mut self) {
4462        let Some(reg) = self.vim.recording_macro.take() else {
4463            return;
4464        };
4465        let keys = std::mem::take(&mut self.vim.recording_keys);
4466        let text = crate::input::encode_macro(&keys);
4467        self.set_named_register_text(reg.to_ascii_lowercase(), text);
4468    }
4469
4470    /// Returns `true` while a `q{reg}` recording is in progress.
4471    /// Hosts use this to show a "recording @r" status indicator and to decide
4472    /// whether bare `q` should stop the recording or open the `RecordMacroTarget`
4473    /// chord.
4474    pub fn is_recording_macro(&self) -> bool {
4475        self.vim.recording_macro.is_some()
4476    }
4477
4478    /// Returns `true` while a macro is being replayed. The app sets this flag
4479    /// (via `play_macro`) and clears it (via `end_macro_replay`) around the
4480    /// re-feed loop so the recorder hook can skip double-capture.
4481    pub fn is_replaying_macro(&self) -> bool {
4482        self.vim.replaying_macro
4483    }
4484
4485    /// Decode the named register `reg` into a `Vec<crate::input::Input>` and
4486    /// prepare for replay, returning the inputs the app should re-feed through
4487    /// `route_chord_key`.
4488    ///
4489    /// Resolves `reg`:
4490    /// - `'@'` → use `vim.last_macro`; returns empty vec if none.
4491    /// - Any other char → lowercase it, read the register, decode.
4492    ///
4493    /// Side-effects:
4494    /// - Sets `vim.last_macro` to the resolved register.
4495    /// - Sets `vim.replaying_macro = true` so the recorder hook skips during
4496    ///   replay. The app calls `end_macro_replay` after the loop finishes.
4497    ///
4498    /// Returns an empty vec (and no side-effects for `'@'`) if the register is
4499    /// unset or empty.
4500    pub fn play_macro(&mut self, reg: char, count: usize) -> Vec<crate::input::Input> {
4501        let resolved = if reg == '@' {
4502            match self.vim.last_macro {
4503                Some(r) => r,
4504                None => return vec![],
4505            }
4506        } else {
4507            reg.to_ascii_lowercase()
4508        };
4509        let text = match self.registers.read(resolved) {
4510            Some(slot) if !slot.text.is_empty() => slot.text.clone(),
4511            _ => return vec![],
4512        };
4513        let keys = crate::input::decode_macro(&text);
4514        self.vim.last_macro = Some(resolved);
4515        self.vim.replaying_macro = true;
4516        // Multiply by count (minimum 1).
4517        keys.repeat(count.max(1))
4518    }
4519
4520    /// Clear the `replaying_macro` flag. Called by the app after the
4521    /// re-feed loop in the `PlayMacro` commit arm completes (or aborts).
4522    pub fn end_macro_replay(&mut self) {
4523        self.vim.replaying_macro = false;
4524    }
4525
4526    /// Append `input` to the active recording (`recording_keys`) if and only
4527    /// if a recording is in progress AND we are not currently replaying.
4528    /// Called by the app's `route_chord_key` recorder hook so that user
4529    /// keystrokes captured through the app-level chord path are recorded
4530    /// (rather than relying solely on the engine FSM's in-step hook).
4531    pub fn record_input(&mut self, input: crate::input::Input) {
4532        if self.vim.recording_macro.is_some() && !self.vim.replaying_macro {
4533            self.vim.recording_keys.push(input);
4534        }
4535    }
4536
4537    // ─── Phase 6.1: public insert-mode primitives (kryptic-sh/hjkl#87) ────────
4538    //
4539    // Each method is the publicly callable form of one insert-mode action.
4540    // All logic lives in the corresponding `vim::*_bridge` free function;
4541    // these methods are thin delegators so the public surface stays on `Editor`.
4542    //
4543    // Invariants (enforced by the bridge fns):
4544    //   - Buffer mutations go through `mutate_edit` (dirty/undo/change-list).
4545    //   - Navigation keys call `break_undo_group_in_insert` when the FSM did.
4546    //   - `push_buffer_cursor_to_textarea` is called after every mutation
4547    //     (currently a no-op, kept for migration hygiene).
4548
4549    /// Insert `ch` at the cursor. In Replace mode, overstrike the cell under
4550    /// the cursor instead of inserting; at end-of-line, always appends. With
4551    /// `smartindent` on, closing brackets (`}`/`)`/`]`) trigger one-unit
4552    /// dedent on an otherwise-whitespace line.
4553    ///
4554    /// Callers must ensure the editor is in Insert or Replace mode before
4555    /// calling this method.
4556    pub fn insert_char(&mut self, ch: char) {
4557        if vim::insert_char_bridge(self, ch) {
4558            self.after_insert_mutation();
4559        }
4560    }
4561
4562    /// Insert a newline at the cursor, applying autoindent / smartindent to
4563    /// prefix the new line with the appropriate leading whitespace.
4564    ///
4565    /// Callers must ensure the editor is in Insert mode before calling.
4566    pub fn insert_newline(&mut self) {
4567        if vim::insert_newline_bridge(self) {
4568            self.after_insert_mutation();
4569        }
4570    }
4571
4572    /// Common post-mutation sync for the `insert_*` primitives. The vim
4573    /// FSM's `step` runs `ensure_cursor_in_scrolloff` at the end of every
4574    /// normal/visual motion; insert-mode primitives bypass `step` and
4575    /// must self-correct or the cursor scrolls off the viewport (held
4576    /// Enter, multi-line backspace at BOL, arrow keys at edge, etc.).
4577    ///
4578    /// Marks the content dirty, widens the insert row's autoindent
4579    /// tracking, and re-checks scrolloff.
4580    fn after_insert_mutation(&mut self) {
4581        self.mark_content_dirty();
4582        let (row, _) = self.cursor();
4583        self.vim.widen_insert_row(row);
4584        self.ensure_cursor_in_scrolloff();
4585    }
4586
4587    /// Like `after_insert_mutation` but for cursor-only insert ops that
4588    /// don't change content (arrows, Home/End, PageUp/Down). Skips the
4589    /// dirty mark.
4590    fn after_insert_motion(&mut self) {
4591        let (row, _) = self.cursor();
4592        self.vim.widen_insert_row(row);
4593        self.ensure_cursor_in_scrolloff();
4594    }
4595
4596    /// Insert a tab character (or spaces up to the next `softtabstop` boundary
4597    /// when `expandtab` is set).
4598    ///
4599    /// Callers must ensure the editor is in Insert mode before calling.
4600    pub fn insert_tab(&mut self) {
4601        if vim::insert_tab_bridge(self) {
4602            self.after_insert_mutation();
4603        }
4604    }
4605
4606    /// Delete the character before the cursor (Backspace). With `softtabstop`
4607    /// active, deletes the entire soft-tab run at an aligned boundary. Joins
4608    /// with the previous line when at column 0.
4609    ///
4610    /// Callers must ensure the editor is in Insert mode before calling.
4611    pub fn insert_backspace(&mut self) {
4612        if vim::insert_backspace_bridge(self) {
4613            self.after_insert_mutation();
4614        }
4615    }
4616
4617    /// Delete the character under the cursor (Delete key). Joins with the
4618    /// next line when at end-of-line.
4619    ///
4620    /// Callers must ensure the editor is in Insert mode before calling.
4621    pub fn insert_delete(&mut self) {
4622        if vim::insert_delete_bridge(self) {
4623            self.after_insert_mutation();
4624        }
4625    }
4626
4627    /// Move the cursor one step in `dir` (arrow key), breaking the undo group
4628    /// per `undo_break_on_motion`.
4629    ///
4630    /// Callers must ensure the editor is in Insert mode before calling.
4631    pub fn insert_arrow(&mut self, dir: vim::InsertDir) {
4632        vim::insert_arrow_bridge(self, dir);
4633        self.after_insert_motion();
4634    }
4635
4636    /// Move the cursor to the start of the current line (Home key), breaking
4637    /// the undo group.
4638    ///
4639    /// Callers must ensure the editor is in Insert mode before calling.
4640    pub fn insert_home(&mut self) {
4641        vim::insert_home_bridge(self);
4642        self.after_insert_motion();
4643    }
4644
4645    /// Move the cursor to the end of the current line (End key), breaking the
4646    /// undo group.
4647    ///
4648    /// Callers must ensure the editor is in Insert mode before calling.
4649    pub fn insert_end(&mut self) {
4650        vim::insert_end_bridge(self);
4651        self.after_insert_motion();
4652    }
4653
4654    /// Scroll up one full viewport height (PageUp), moving the cursor with it.
4655    /// `viewport_h` is the current viewport height in rows; pass
4656    /// `self.viewport_height_value()` if the stored value is current.
4657    ///
4658    /// Callers must ensure the editor is in Insert mode before calling.
4659    pub fn insert_pageup(&mut self, viewport_h: u16) {
4660        vim::insert_pageup_bridge(self, viewport_h);
4661        self.after_insert_motion();
4662    }
4663
4664    /// Scroll down one full viewport height (PageDown), moving the cursor with
4665    /// it. `viewport_h` is the current viewport height in rows.
4666    ///
4667    /// Callers must ensure the editor is in Insert mode before calling.
4668    pub fn insert_pagedown(&mut self, viewport_h: u16) {
4669        vim::insert_pagedown_bridge(self, viewport_h);
4670        self.after_insert_motion();
4671    }
4672
4673    /// Delete from the cursor back to the start of the previous word (`Ctrl-W`).
4674    /// At column 0, joins with the previous line (vim `b`-motion semantics).
4675    ///
4676    /// Callers must ensure the editor is in Insert mode before calling.
4677    pub fn insert_ctrl_w(&mut self) {
4678        if vim::insert_ctrl_w_bridge(self) {
4679            self.after_insert_mutation();
4680        }
4681    }
4682
4683    /// Delete from the cursor back to the start of the current line (`Ctrl-U`).
4684    /// No-op when already at column 0.
4685    ///
4686    /// Callers must ensure the editor is in Insert mode before calling.
4687    pub fn insert_ctrl_u(&mut self) {
4688        if vim::insert_ctrl_u_bridge(self) {
4689            self.after_insert_mutation();
4690        }
4691    }
4692
4693    /// Delete one character backwards (`Ctrl-H`) — alias for Backspace in
4694    /// insert mode. Joins with the previous line when at col 0.
4695    ///
4696    /// Callers must ensure the editor is in Insert mode before calling.
4697    pub fn insert_ctrl_h(&mut self) {
4698        if vim::insert_ctrl_h_bridge(self) {
4699            self.after_insert_mutation();
4700        }
4701    }
4702
4703    /// Enter "one-shot normal" mode (`Ctrl-O`): suspend insert for the next
4704    /// complete normal-mode command, then return to insert automatically.
4705    ///
4706    /// Callers must ensure the editor is in Insert mode before calling.
4707    pub fn insert_ctrl_o_arm(&mut self) {
4708        vim::insert_ctrl_o_bridge(self);
4709    }
4710
4711    /// Arm the register-paste selector (`Ctrl-R`). The next call to
4712    /// `insert_paste_register(reg)` will insert the register contents.
4713    /// Alternatively, feeding a `Key::Char(c)` through the FSM will consume
4714    /// the armed state and paste register `c`.
4715    ///
4716    /// Callers must ensure the editor is in Insert mode before calling.
4717    pub fn insert_ctrl_r_arm(&mut self) {
4718        vim::insert_ctrl_r_bridge(self);
4719    }
4720
4721    /// Indent the current line by one `shiftwidth` and shift the cursor right
4722    /// by the same amount (`Ctrl-T`).
4723    ///
4724    /// Callers must ensure the editor is in Insert mode before calling.
4725    pub fn insert_ctrl_t(&mut self) {
4726        let mutated = vim::insert_ctrl_t_bridge(self);
4727        if mutated {
4728            self.mark_content_dirty();
4729            let (row, _) = self.cursor();
4730            self.vim.widen_insert_row(row);
4731        }
4732    }
4733
4734    /// Outdent the current line by up to one `shiftwidth` and shift the cursor
4735    /// left by the amount stripped (`Ctrl-D`).
4736    ///
4737    /// Callers must ensure the editor is in Insert mode before calling.
4738    pub fn insert_ctrl_d(&mut self) {
4739        let mutated = vim::insert_ctrl_d_bridge(self);
4740        if mutated {
4741            self.mark_content_dirty();
4742            let (row, _) = self.cursor();
4743            self.vim.widen_insert_row(row);
4744        }
4745    }
4746
4747    /// Paste the contents of register `reg` at the cursor (the commit arm of
4748    /// `Ctrl-R {reg}`). Unknown or empty registers are a no-op.
4749    ///
4750    /// Callers must ensure the editor is in Insert mode before calling.
4751    pub fn insert_paste_register(&mut self, reg: char) {
4752        vim::insert_paste_register_bridge(self, reg);
4753        let (row, _) = self.cursor();
4754        self.vim.widen_insert_row(row);
4755    }
4756
4757    /// Exit insert mode to Normal: finish the insert session, step the cursor
4758    /// one cell left (vim convention on Esc), record the `gi` target position,
4759    /// and update the sticky column.
4760    ///
4761    /// Callers must ensure the editor is in Insert mode before calling.
4762    pub fn leave_insert_to_normal(&mut self) {
4763        vim::leave_insert_to_normal_bridge(self);
4764    }
4765
4766    // ── Phase 6.2: normal-mode primitive controller methods ───────────────────
4767    //
4768    // Each method is a thin wrapper around a `pub(crate) fn *_bridge` in
4769    // `vim.rs` following the same pattern as Phase 6.1. The FSM's
4770    // `handle_normal_only` now calls the same bridges so both paths are
4771    // identical. See kryptic-sh/hjkl#88 for the full promotion plan.
4772
4773    /// `i` — transition to Insert mode at the current cursor position.
4774    /// `count` is stored in the insert session and replayed by dot-repeat
4775    /// as a repeat count on the inserted text.
4776    pub fn enter_insert_i(&mut self, count: usize) {
4777        vim::enter_insert_i_bridge(self, count);
4778    }
4779
4780    /// `I` — move to the first non-blank character on the line, then
4781    /// transition to Insert mode. `count` is stored for dot-repeat.
4782    pub fn enter_insert_shift_i(&mut self, count: usize) {
4783        vim::enter_insert_shift_i_bridge(self, count);
4784    }
4785
4786    /// `a` — advance the cursor one cell past the current position, then
4787    /// transition to Insert mode (append). `count` is stored for dot-repeat.
4788    pub fn enter_insert_a(&mut self, count: usize) {
4789        vim::enter_insert_a_bridge(self, count);
4790    }
4791
4792    /// `A` — move the cursor to the end of the line, then transition to
4793    /// Insert mode (append at end). `count` is stored for dot-repeat.
4794    pub fn enter_insert_shift_a(&mut self, count: usize) {
4795        vim::enter_insert_shift_a_bridge(self, count);
4796    }
4797
4798    /// `o` — open a new line below the current line with smart-indent, then
4799    /// transition to Insert mode. `count` is stored for dot-repeat replay.
4800    pub fn open_line_below(&mut self, count: usize) {
4801        vim::open_line_below_bridge(self, count);
4802    }
4803
4804    /// `O` — open a new line above the current line with smart-indent, then
4805    /// transition to Insert mode. `count` is stored for dot-repeat replay.
4806    pub fn open_line_above(&mut self, count: usize) {
4807        vim::open_line_above_bridge(self, count);
4808    }
4809
4810    /// `R` — enter Replace mode: subsequent typed characters overstrike the
4811    /// cell under the cursor rather than inserting. `count` is for replay.
4812    pub fn enter_replace_mode(&mut self, count: usize) {
4813        vim::enter_replace_mode_bridge(self, count);
4814    }
4815
4816    /// `x` — delete `count` characters forward from the cursor and write them
4817    /// to the unnamed register. No-op on an empty line. Records for `.`.
4818    pub fn delete_char_forward(&mut self, count: usize) {
4819        vim::delete_char_forward_bridge(self, count);
4820    }
4821
4822    /// `X` — delete `count` characters backward from the cursor and write
4823    /// them to the unnamed register. No-op at column 0. Records for `.`.
4824    pub fn delete_char_backward(&mut self, count: usize) {
4825        vim::delete_char_backward_bridge(self, count);
4826    }
4827
4828    /// `s` — substitute `count` characters: delete them (writing to the
4829    /// unnamed register) then enter Insert mode. Equivalent to `cl`.
4830    /// Records as `OpMotion { Change, Right }` for dot-repeat.
4831    pub fn substitute_char(&mut self, count: usize) {
4832        vim::substitute_char_bridge(self, count);
4833    }
4834
4835    /// `S` — substitute the current line: wipe its contents (writing to the
4836    /// unnamed register) then enter Insert mode. Equivalent to `cc`.
4837    /// Records as `LineOp { Change }` for dot-repeat.
4838    pub fn substitute_line(&mut self, count: usize) {
4839        vim::substitute_line_bridge(self, count);
4840    }
4841
4842    /// `D` — delete from the cursor to end-of-line, writing to the unnamed
4843    /// register. The cursor parks on the new last character. Records for `.`.
4844    pub fn delete_to_eol(&mut self) {
4845        vim::delete_to_eol_bridge(self);
4846    }
4847
4848    /// `C` — change from the cursor to end-of-line: delete to EOL then enter
4849    /// Insert mode. Equivalent to `c$`. Does not record its own `last_change`
4850    /// (the insert session records `DeleteToEol` on exit, like `c` motions).
4851    pub fn change_to_eol(&mut self) {
4852        vim::change_to_eol_bridge(self);
4853    }
4854
4855    /// `Y` — yank from the cursor to end-of-line into the unnamed register.
4856    /// Vim 8 default: equivalent to `y$`. `count` multiplies the motion.
4857    pub fn yank_to_eol(&mut self, count: usize) {
4858        vim::yank_to_eol_bridge(self, count);
4859    }
4860
4861    /// `J` — join `count` lines (default 2) onto the current line, inserting
4862    /// a single space between each non-empty pair. Records for dot-repeat.
4863    pub fn join_line(&mut self, count: usize) {
4864        vim::join_line_bridge(self, count);
4865    }
4866
4867    /// `~` — toggle the case of `count` characters from the cursor, advancing
4868    /// right after each toggle. Records `ToggleCase` for dot-repeat.
4869    pub fn toggle_case_at_cursor(&mut self, count: usize) {
4870        vim::toggle_case_at_cursor_bridge(self, count);
4871    }
4872
4873    /// `p` — paste the unnamed register (or the register selected via `"r`)
4874    /// after the cursor. Linewise content opens a new line below; charwise
4875    /// content is inserted inline. Records `Paste { before: false }` for `.`.
4876    pub fn paste_after(&mut self, count: usize) {
4877        vim::paste_after_bridge(self, count);
4878    }
4879
4880    /// `P` — paste the unnamed register (or the `"r` register) before the
4881    /// cursor. Linewise content opens a new line above; charwise is inline.
4882    /// Records `Paste { before: true }` for dot-repeat.
4883    pub fn paste_before(&mut self, count: usize) {
4884        vim::paste_before_bridge(self, count);
4885    }
4886
4887    /// `<C-o>` — jump back `count` entries in the jumplist, saving the
4888    /// current position on the forward stack so `<C-i>` can return.
4889    pub fn jump_back(&mut self, count: usize) {
4890        vim::jump_back_bridge(self, count);
4891    }
4892
4893    /// `<C-i>` / `Tab` — redo `count` entries on the forward jumplist stack,
4894    /// saving the current position on the backward stack.
4895    pub fn jump_forward(&mut self, count: usize) {
4896        vim::jump_forward_bridge(self, count);
4897    }
4898
4899    /// `<C-f>` / `<C-b>` — scroll the cursor by one full viewport height
4900    /// (height − 2 rows, preserving two-line overlap). `count` multiplies.
4901    /// `dir = Down` for `<C-f>`, `Up` for `<C-b>`.
4902    pub fn scroll_full_page(&mut self, dir: vim::ScrollDir, count: usize) {
4903        vim::scroll_full_page_bridge(self, dir, count);
4904    }
4905
4906    /// `<C-d>` / `<C-u>` — scroll the cursor by half the viewport height.
4907    /// `count` multiplies the step. `dir = Down` for `<C-d>`, `Up` for `<C-u>`.
4908    pub fn scroll_half_page(&mut self, dir: vim::ScrollDir, count: usize) {
4909        vim::scroll_half_page_bridge(self, dir, count);
4910    }
4911
4912    /// `<C-e>` / `<C-y>` — scroll the viewport `count` lines without moving
4913    /// the cursor (cursor is clamped to the new visible region if necessary).
4914    /// `dir = Down` for `<C-e>` (scroll text up), `Up` for `<C-y>`.
4915    pub fn scroll_line(&mut self, dir: vim::ScrollDir, count: usize) {
4916        vim::scroll_line_bridge(self, dir, count);
4917    }
4918
4919    /// `n` — repeat the last `/` or `?` search `count` times in its original
4920    /// direction. `forward = true` keeps the direction; `false` inverts (`N`).
4921    pub fn search_repeat(&mut self, forward: bool, count: usize) {
4922        vim::search_repeat_bridge(self, forward, count);
4923    }
4924
4925    /// `*` / `#` / `g*` / `g#` — search for the word under the cursor.
4926    /// `forward` chooses direction; `whole_word` wraps the pattern in `\b`
4927    /// anchors (true for `*` / `#`, false for `g*` / `g#`). `count` repeats.
4928    pub fn word_search(&mut self, forward: bool, whole_word: bool, count: usize) {
4929        vim::word_search_bridge(self, forward, whole_word, count);
4930    }
4931
4932    // ── Phase 6.3: visual-mode primitive controller methods ──────────────────
4933    //
4934    // Each method is a thin wrapper around a `pub(crate) fn *_bridge` in
4935    // `vim.rs` following the same pattern as Phase 6.1 / 6.2. Both the FSM
4936    // and these wrappers write `current_mode` so `vim_mode()` returns correct
4937    // values regardless of which path performed the transition.
4938    // See kryptic-sh/hjkl#89 for the full promotion plan.
4939
4940    /// `v` from Normal — enter charwise Visual mode, anchoring the selection
4941    /// at the current cursor position.
4942    pub fn enter_visual_char(&mut self) {
4943        vim::enter_visual_char_bridge(self);
4944    }
4945
4946    /// `V` from Normal — enter linewise Visual mode, anchoring on the current
4947    /// line. Motions extend the selection by whole lines.
4948    pub fn enter_visual_line(&mut self) {
4949        vim::enter_visual_line_bridge(self);
4950    }
4951
4952    /// `<C-v>` from Normal — enter Visual-block mode. The selection is a
4953    /// rectangle whose corners are the anchor and the live cursor.
4954    pub fn enter_visual_block(&mut self) {
4955        vim::enter_visual_block_bridge(self);
4956    }
4957
4958    /// Esc from any visual mode — set `<` / `>` marks, stash the selection
4959    /// for `gv` re-entry, then return to Normal mode.
4960    pub fn exit_visual_to_normal(&mut self) {
4961        vim::exit_visual_to_normal_bridge(self);
4962    }
4963
4964    /// `o` in Visual / VisualLine / VisualBlock — swap the cursor and anchor
4965    /// so the user can extend the other end of the selection. Does NOT
4966    /// mutate the selection range; only the active endpoint changes.
4967    pub fn visual_o_toggle(&mut self) {
4968        vim::visual_o_toggle_bridge(self);
4969    }
4970
4971    /// `gv` — restore the last visual selection (mode + anchor + cursor
4972    /// position). No-op when no visual selection has been exited yet.
4973    pub fn reenter_last_visual(&mut self) {
4974        vim::reenter_last_visual_bridge(self);
4975    }
4976
4977    /// Direct mode-transition entry point. Sets both the internal FSM mode
4978    /// and the stable `current_mode` field read by [`Editor::vim_mode`].
4979    ///
4980    /// Prefer the semantic primitives (`enter_visual_char`, `enter_insert_i`,
4981    /// …) which also set up required bookkeeping (anchors, sessions, …).
4982    /// Use `set_mode` only when you need a raw mode flip without side-effects.
4983    pub fn set_mode(&mut self, mode: VimMode) {
4984        vim::set_mode_bridge(self, mode);
4985    }
4986}
4987
4988// ── Phase 6.6b: FSM state accessors (for hjkl-vim ownership) ─────────────────
4989//
4990// The FSM (now in hjkl-vim) reads/writes `VimState` fields through public
4991// `Editor` accessors and mutators defined in this block. Each method gets a
4992// one-line `///` rustdoc. Fields mutated as a unit get a combined action method
4993// rather than individual getters + setters (e.g. `accumulate_count_digit`).
4994
4995/// State carried between [`Editor::begin_step`] and [`Editor::end_step`].
4996///
4997/// Treat as opaque — construct by calling `begin_step` and pass the
4998/// returned value directly into `end_step` without modification.
4999/// The fields capture per-step pre-dispatch state that the epilogue
5000/// needs to run its invariants correctly.
5001pub struct StepBookkeeping {
5002    /// True when the pending chord before this step was a macro-chord
5003    /// (`q{reg}` or `@{reg}`). The recorder hook skips these bookkeeping
5004    /// keys so that only the *payload* keys enter `recording_keys`.
5005    pub pending_was_macro_chord: bool,
5006    /// True when the mode was Insert *before* the FSM body ran. Used by
5007    /// the Ctrl-o one-shot-normal epilogue to decide whether to bounce
5008    /// back into Insert.
5009    pub was_insert: bool,
5010    /// Pre-dispatch visual snapshot. When the FSM body transitions out of
5011    /// a visual mode the epilogue uses this to set the `<`/`>` marks and
5012    /// store `last_visual` for `gv`.
5013    pub pre_visual_snapshot: Option<vim::LastVisual>,
5014}
5015
5016impl<H: crate::types::Host> Editor<hjkl_buffer::Buffer, H> {
5017    // ── Pending chord ─────────────────────────────────────────────────────────
5018
5019    /// Return a clone of the current pending chord state.
5020    pub fn pending(&self) -> vim::Pending {
5021        self.vim.pending.clone()
5022    }
5023
5024    /// Overwrite the pending chord state.
5025    pub fn set_pending(&mut self, p: vim::Pending) {
5026        self.vim.pending = p;
5027    }
5028
5029    /// Atomically take the pending chord, replacing it with `Pending::None`.
5030    pub fn take_pending(&mut self) -> vim::Pending {
5031        std::mem::take(&mut self.vim.pending)
5032    }
5033
5034    // ── Count prefix ──────────────────────────────────────────────────────────
5035
5036    /// Return the raw digit-prefix count (`0` = no prefix typed yet).
5037    pub fn count(&self) -> usize {
5038        self.vim.count
5039    }
5040
5041    /// Overwrite the digit-prefix count directly.
5042    pub fn set_count(&mut self, c: usize) {
5043        self.vim.count = c;
5044    }
5045
5046    /// Accumulate one more digit into the count prefix (mirrors `count * 10 + digit`).
5047    pub fn accumulate_count_digit(&mut self, digit: usize) {
5048        self.vim.count = self.vim.count.saturating_mul(10) + digit;
5049    }
5050
5051    /// Reset the count prefix to zero (no pending count).
5052    pub fn reset_count(&mut self) {
5053        self.vim.count = 0;
5054    }
5055
5056    /// Consume the count and return it; resets to zero. Returns `1` when no
5057    /// prefix was typed (mirrors `take_count` in vim.rs).
5058    pub fn take_count(&mut self) -> usize {
5059        if self.vim.count > 0 {
5060            let n = self.vim.count;
5061            self.vim.count = 0;
5062            n
5063        } else {
5064            1
5065        }
5066    }
5067
5068    // ── Internal FSM mode ─────────────────────────────────────────────────────
5069
5070    /// Return the FSM-internal mode (Normal / Insert / Visual / …).
5071    pub fn fsm_mode(&self) -> vim::Mode {
5072        self.vim.mode
5073    }
5074
5075    /// Overwrite the FSM-internal mode without side-effects. Prefer the
5076    /// semantic primitives (`enter_insert_i`, `enter_visual_char`, …).
5077    pub fn set_fsm_mode(&mut self, m: vim::Mode) {
5078        self.vim.mode = m;
5079        self.vim.current_mode = self.vim.public_mode();
5080    }
5081
5082    // ── Replaying flag ────────────────────────────────────────────────────────
5083
5084    /// `true` while the `.` dot-repeat replay is running.
5085    pub fn is_replaying(&self) -> bool {
5086        self.vim.replaying
5087    }
5088
5089    /// Set or clear the dot-replay flag.
5090    pub fn set_replaying(&mut self, v: bool) {
5091        self.vim.replaying = v;
5092    }
5093
5094    // ── One-shot normal (Ctrl-o) ──────────────────────────────────────────────
5095
5096    /// `true` when we entered Normal from Insert via `Ctrl-o` and will return
5097    /// to Insert after the next complete command.
5098    pub fn is_one_shot_normal(&self) -> bool {
5099        self.vim.one_shot_normal
5100    }
5101
5102    /// Set or clear the Ctrl-o one-shot-normal flag.
5103    pub fn set_one_shot_normal(&mut self, v: bool) {
5104        self.vim.one_shot_normal = v;
5105    }
5106
5107    // ── Last find (f/F/t/T target) ────────────────────────────────────────────
5108
5109    /// Return the last `f`/`F`/`t`/`T` target as `(char, forward, till)`, or
5110    /// `None` before any find command was executed.
5111    pub fn last_find(&self) -> Option<(char, bool, bool)> {
5112        self.vim.last_find
5113    }
5114
5115    /// Overwrite the stored last-find target.
5116    pub fn set_last_find(&mut self, target: Option<(char, bool, bool)>) {
5117        self.vim.last_find = target;
5118    }
5119
5120    // ── Sneak motion ──────────────────────────────────────────────────────────
5121
5122    /// Perform a vim-sneak style two-char digraph jump. Scans the buffer
5123    /// from the current cursor for the `count`-th occurrence of `c1+c2`.
5124    /// `forward=true` searches ahead; `forward=false` searches backward.
5125    /// Respects `Settings::motion_sneak` — callers (hjkl-vim FSM) should
5126    /// already gate on the setting; this method always executes the sneak.
5127    pub fn sneak(&mut self, c1: char, c2: char, forward: bool, count: usize) {
5128        vim::apply_sneak(self, c1, c2, forward, count.max(1));
5129    }
5130
5131    /// Apply an operator over a sneak digraph range. Charwise exclusive —
5132    /// deletes from cursor up to (not including) the first char of the match.
5133    pub fn apply_op_sneak(
5134        &mut self,
5135        op: vim::Operator,
5136        c1: char,
5137        c2: char,
5138        forward: bool,
5139        total_count: usize,
5140    ) {
5141        vim::apply_op_sneak(self, op, c1, c2, forward, total_count);
5142    }
5143
5144    /// Return the last sneak digraph and direction stored after a sneak motion.
5145    /// `Some(((c1, c2), forward))` when a sneak has been performed this session;
5146    /// `None` before any sneak. Used by `;`/`,` repeat and tests.
5147    pub fn last_sneak(&self) -> Option<((char, char), bool)> {
5148        self.vim.last_sneak
5149    }
5150
5151    // ── Last change (dot-repeat payload) ─────────────────────────────────────
5152
5153    /// Return a clone of the last recorded mutating change, or `None` before
5154    /// any change has been made.
5155    pub fn last_change(&self) -> Option<vim::LastChange> {
5156        self.vim.last_change.clone()
5157    }
5158
5159    /// Overwrite the stored last-change record.
5160    pub fn set_last_change(&mut self, lc: Option<vim::LastChange>) {
5161        self.vim.last_change = lc;
5162    }
5163
5164    /// Borrow the last-change record mutably (e.g. to fill in an `inserted`
5165    /// field after the insert session completes).
5166    pub fn last_change_mut(&mut self) -> Option<&mut vim::LastChange> {
5167        self.vim.last_change.as_mut()
5168    }
5169
5170    // ── Insert session ────────────────────────────────────────────────────────
5171
5172    /// Borrow the active insert session, or `None` when not in Insert mode.
5173    pub fn insert_session(&self) -> Option<&vim::InsertSession> {
5174        self.vim.insert_session.as_ref()
5175    }
5176
5177    /// Borrow the active insert session mutably.
5178    pub fn insert_session_mut(&mut self) -> Option<&mut vim::InsertSession> {
5179        self.vim.insert_session.as_mut()
5180    }
5181
5182    /// Atomically take the insert session out, leaving `None`.
5183    pub fn take_insert_session(&mut self) -> Option<vim::InsertSession> {
5184        self.vim.insert_session.take()
5185    }
5186
5187    /// Install a new insert session, replacing any existing one.
5188    pub fn set_insert_session(&mut self, s: Option<vim::InsertSession>) {
5189        self.vim.insert_session = s;
5190    }
5191
5192    // ── Visual anchors ────────────────────────────────────────────────────────
5193
5194    /// Return the charwise Visual-mode anchor `(row, col)`.
5195    pub fn visual_anchor(&self) -> (usize, usize) {
5196        self.vim.visual_anchor
5197    }
5198
5199    /// Overwrite the charwise Visual-mode anchor.
5200    pub fn set_visual_anchor(&mut self, anchor: (usize, usize)) {
5201        self.vim.visual_anchor = anchor;
5202    }
5203
5204    /// Return the VisualLine anchor row.
5205    pub fn visual_line_anchor(&self) -> usize {
5206        self.vim.visual_line_anchor
5207    }
5208
5209    /// Overwrite the VisualLine anchor row.
5210    pub fn set_visual_line_anchor(&mut self, row: usize) {
5211        self.vim.visual_line_anchor = row;
5212    }
5213
5214    /// Return the VisualBlock anchor `(row, col)`.
5215    pub fn block_anchor(&self) -> (usize, usize) {
5216        self.vim.block_anchor
5217    }
5218
5219    /// Overwrite the VisualBlock anchor.
5220    pub fn set_block_anchor(&mut self, anchor: (usize, usize)) {
5221        self.vim.block_anchor = anchor;
5222    }
5223
5224    /// Return the VisualBlock virtual column used to survive j/k row clamping.
5225    pub fn block_vcol(&self) -> usize {
5226        self.vim.block_vcol
5227    }
5228
5229    /// Overwrite the VisualBlock virtual column.
5230    pub fn set_block_vcol(&mut self, vcol: usize) {
5231        self.vim.block_vcol = vcol;
5232    }
5233
5234    // ── Yank linewise flag ────────────────────────────────────────────────────
5235
5236    /// `true` when the last yank/cut was linewise (affects `p`/`P` layout).
5237    pub fn yank_linewise(&self) -> bool {
5238        self.vim.yank_linewise
5239    }
5240
5241    /// Set or clear the linewise-yank flag.
5242    pub fn set_yank_linewise(&mut self, v: bool) {
5243        self.vim.yank_linewise = v;
5244    }
5245
5246    // ── Pending register selector ─────────────────────────────────────────────
5247    // Note: `pending_register()` getter already exists at line ~1254 (Phase 4e).
5248    // Only the mutators are new here.
5249
5250    /// Overwrite the pending register selector (Phase 6.6b mutator companion to
5251    /// the existing `pending_register()` getter).
5252    pub fn set_pending_register_raw(&mut self, reg: Option<char>) {
5253        self.vim.pending_register = reg;
5254    }
5255
5256    /// Atomically take the pending register, returning `None` afterward.
5257    pub fn take_pending_register_raw(&mut self) -> Option<char> {
5258        self.vim.pending_register.take()
5259    }
5260
5261    // ── Macro recording ───────────────────────────────────────────────────────
5262
5263    /// Return the register currently being recorded into, or `None`.
5264    pub fn recording_macro(&self) -> Option<char> {
5265        self.vim.recording_macro
5266    }
5267
5268    /// Overwrite the recording-macro target register.
5269    pub fn set_recording_macro(&mut self, reg: Option<char>) {
5270        self.vim.recording_macro = reg;
5271    }
5272
5273    /// Append one input to the in-progress macro recording buffer.
5274    pub fn push_recording_key(&mut self, input: crate::input::Input) {
5275        self.vim.recording_keys.push(input);
5276    }
5277
5278    /// Atomically take the recorded key sequence, leaving an empty vec.
5279    pub fn take_recording_keys(&mut self) -> Vec<crate::input::Input> {
5280        std::mem::take(&mut self.vim.recording_keys)
5281    }
5282
5283    /// Overwrite the recording-keys buffer (e.g. to seed from a register).
5284    pub fn set_recording_keys(&mut self, keys: Vec<crate::input::Input>) {
5285        self.vim.recording_keys = keys;
5286    }
5287
5288    /// Return the number of keys currently in the recording buffer.
5289    /// Useful for integration tests that verify macro-recording bookkeeping
5290    /// without draining the buffer via [`take_recording_keys`].
5291    pub fn recording_keys_len(&self) -> usize {
5292        self.vim.recording_keys.len()
5293    }
5294
5295    // ── Macro replay flag ─────────────────────────────────────────────────────
5296
5297    /// `true` while `@reg` macro replay is running (suppresses re-recording).
5298    pub fn is_replaying_macro_raw(&self) -> bool {
5299        self.vim.replaying_macro
5300    }
5301
5302    /// Set or clear the macro-replay-in-progress flag.
5303    pub fn set_replaying_macro_raw(&mut self, v: bool) {
5304        self.vim.replaying_macro = v;
5305    }
5306
5307    // ── Last macro register ───────────────────────────────────────────────────
5308
5309    /// Return the register of the most recently played macro (`@@` source).
5310    pub fn last_macro(&self) -> Option<char> {
5311        self.vim.last_macro
5312    }
5313
5314    /// Overwrite the last-played-macro register.
5315    pub fn set_last_macro(&mut self, reg: Option<char>) {
5316        self.vim.last_macro = reg;
5317    }
5318
5319    // ── Last insert position ──────────────────────────────────────────────────
5320
5321    /// Return the cursor position when Insert mode was last exited (for `gi`).
5322    pub fn last_insert_pos(&self) -> Option<(usize, usize)> {
5323        self.vim.last_insert_pos
5324    }
5325
5326    /// Overwrite the stored last-insert position.
5327    pub fn set_last_insert_pos(&mut self, pos: Option<(usize, usize)>) {
5328        self.vim.last_insert_pos = pos;
5329    }
5330
5331    // ── Last visual selection ─────────────────────────────────────────────────
5332
5333    /// Return the saved visual selection snapshot for `gv`, or `None`.
5334    pub fn last_visual(&self) -> Option<vim::LastVisual> {
5335        self.vim.last_visual
5336    }
5337
5338    /// Overwrite the saved visual selection snapshot.
5339    pub fn set_last_visual(&mut self, snap: Option<vim::LastVisual>) {
5340        self.vim.last_visual = snap;
5341    }
5342
5343    // ── Viewport-pinned flag ──────────────────────────────────────────────────
5344
5345    /// `true` when `zz`/`zt`/`zb` pinned the viewport this step (suppresses
5346    /// the end-of-step scrolloff pass).
5347    pub fn viewport_pinned(&self) -> bool {
5348        self.vim.viewport_pinned
5349    }
5350
5351    /// Set or clear the viewport-pinned flag.
5352    pub fn set_viewport_pinned(&mut self, v: bool) {
5353        self.vim.viewport_pinned = v;
5354    }
5355
5356    // ── Insert pending register (Ctrl-R wait) ─────────────────────────────────
5357
5358    /// `true` while waiting for the register-name key after `Ctrl-R` in
5359    /// Insert mode.
5360    pub fn insert_pending_register(&self) -> bool {
5361        self.vim.insert_pending_register
5362    }
5363
5364    /// Set or clear the `Ctrl-R` register-wait flag.
5365    pub fn set_insert_pending_register(&mut self, v: bool) {
5366        self.vim.insert_pending_register = v;
5367    }
5368
5369    // ── Change-mark start ─────────────────────────────────────────────────────
5370
5371    /// Return the stashed `[` mark start for a Change operation, or `None`.
5372    pub fn change_mark_start(&self) -> Option<(usize, usize)> {
5373        self.vim.change_mark_start
5374    }
5375
5376    /// Atomically take the change-mark start, leaving `None`.
5377    pub fn take_change_mark_start(&mut self) -> Option<(usize, usize)> {
5378        self.vim.change_mark_start.take()
5379    }
5380
5381    /// Overwrite the change-mark start.
5382    pub fn set_change_mark_start(&mut self, pos: Option<(usize, usize)>) {
5383        self.vim.change_mark_start = pos;
5384    }
5385
5386    // ── Timeout tracking ──────────────────────────────────────────────────────
5387
5388    /// Return the wall-clock `Instant` of the last keystroke.
5389    pub fn last_input_at(&self) -> Option<std::time::Instant> {
5390        self.vim.last_input_at
5391    }
5392
5393    /// Overwrite the wall-clock last-input timestamp.
5394    pub fn set_last_input_at(&mut self, t: Option<std::time::Instant>) {
5395        self.vim.last_input_at = t;
5396    }
5397
5398    /// Return the `Host::now()` duration at the last keystroke.
5399    pub fn last_input_host_at(&self) -> Option<core::time::Duration> {
5400        self.vim.last_input_host_at
5401    }
5402
5403    /// Overwrite the host-clock last-input timestamp.
5404    pub fn set_last_input_host_at(&mut self, d: Option<core::time::Duration>) {
5405        self.vim.last_input_host_at = d;
5406    }
5407
5408    // ── Search prompt ──────────────────────────────────────────────────────────
5409
5410    /// Borrow the live search prompt, or `None` when not in search-prompt mode.
5411    pub fn search_prompt_state(&self) -> Option<&vim::SearchPrompt> {
5412        self.vim.search_prompt.as_ref()
5413    }
5414
5415    /// Borrow the live search prompt mutably.
5416    pub fn search_prompt_state_mut(&mut self) -> Option<&mut vim::SearchPrompt> {
5417        self.vim.search_prompt.as_mut()
5418    }
5419
5420    /// Atomically take the search prompt, leaving `None`.
5421    pub fn take_search_prompt_state(&mut self) -> Option<vim::SearchPrompt> {
5422        self.vim.search_prompt.take()
5423    }
5424
5425    /// Install a new search prompt (entering search-prompt mode).
5426    pub fn set_search_prompt_state(&mut self, prompt: Option<vim::SearchPrompt>) {
5427        self.vim.search_prompt = prompt;
5428    }
5429
5430    // ── Last search pattern / direction ───────────────────────────────────────
5431    // Note: `last_search_forward()` getter already exists at line ~1909.
5432    // `set_last_search()` combined mutator exists at line ~1918.
5433    // Only new / complementary accessors are added here.
5434
5435    /// Return the most recently committed search pattern, or `None`.
5436    pub fn last_search_pattern(&self) -> Option<&str> {
5437        self.vim.last_search.as_deref()
5438    }
5439
5440    /// Overwrite the stored last-search pattern without changing direction
5441    /// (use the existing `set_last_search` for the combined update).
5442    pub fn set_last_search_pattern_only(&mut self, pattern: Option<String>) {
5443        self.vim.last_search = pattern;
5444    }
5445
5446    /// Overwrite only the last-search direction flag.
5447    pub fn set_last_search_forward_only(&mut self, forward: bool) {
5448        self.vim.last_search_forward = forward;
5449    }
5450
5451    // ── Search history ────────────────────────────────────────────────────────
5452
5453    /// Borrow the committed search-pattern history (oldest first).
5454    pub fn search_history(&self) -> &[String] {
5455        &self.vim.search_history
5456    }
5457
5458    /// Borrow the search history mutably (e.g. to push a new entry).
5459    pub fn search_history_mut(&mut self) -> &mut Vec<String> {
5460        &mut self.vim.search_history
5461    }
5462
5463    /// Return the current search-history navigation cursor index.
5464    pub fn search_history_cursor(&self) -> Option<usize> {
5465        self.vim.search_history_cursor
5466    }
5467
5468    /// Overwrite the search-history navigation cursor.
5469    pub fn set_search_history_cursor(&mut self, idx: Option<usize>) {
5470        self.vim.search_history_cursor = idx;
5471    }
5472
5473    // ── Jump lists ────────────────────────────────────────────────────────────
5474
5475    /// Borrow the back half of the jump list (entries Ctrl-o pops from).
5476    pub fn jump_back_list(&self) -> &[(usize, usize)] {
5477        &self.vim.jump_back
5478    }
5479
5480    /// Borrow the back jump list mutably (push / pop).
5481    pub fn jump_back_list_mut(&mut self) -> &mut Vec<(usize, usize)> {
5482        &mut self.vim.jump_back
5483    }
5484
5485    /// Borrow the forward half of the jump list (entries Ctrl-i pops from).
5486    pub fn jump_fwd_list(&self) -> &[(usize, usize)] {
5487        &self.vim.jump_fwd
5488    }
5489
5490    /// Borrow the forward jump list mutably (push / pop / clear).
5491    pub fn jump_fwd_list_mut(&mut self) -> &mut Vec<(usize, usize)> {
5492        &mut self.vim.jump_fwd
5493    }
5494
5495    // ── Phase 6.6c: search + jump helpers (public Editor API) ───────────────
5496    //
5497    // `push_search_pattern`, `push_jump`, `record_search_history`, and
5498    // `walk_search_history` are public `Editor` methods so that `hjkl-vim`'s
5499    // search-prompt and normal-mode FSM can call them via the public API.
5500
5501    /// Compile `pattern` into a regex and install it as the active search
5502    /// pattern. Respects `:set ignorecase` / `:set smartcase` and inline
5503    /// `\c`/`\C` overrides. An empty or invalid pattern clears the highlight
5504    /// without raising an error.
5505    pub fn push_search_pattern(&mut self, pattern: &str) {
5506        let compiled = if pattern.is_empty() {
5507            None
5508        } else {
5509            use crate::search::{CaseMode, resolve_case_mode};
5510            let base =
5511                CaseMode::from_options(self.settings().ignore_case, self.settings().smartcase);
5512            let (stripped, mode) = resolve_case_mode(pattern, base);
5513            let src = if mode == CaseMode::Insensitive {
5514                format!("(?i){stripped}")
5515            } else {
5516                stripped
5517            };
5518            regex::Regex::new(&src).ok()
5519        };
5520        let wrap = self.settings().wrapscan;
5521        self.set_search_pattern(compiled);
5522        self.search_state_mut().wrap_around = wrap;
5523    }
5524
5525    /// Record a pre-jump cursor position onto the back jumplist. Called
5526    /// before any "big jump" motion (`gg`/`G`, `%`, `*`/`#`, `n`/`N`,
5527    /// committed `/` or `?`, …). Branching off the history clears the
5528    /// forward half, matching vim's "redo-is-lost" semantics.
5529    pub fn push_jump(&mut self, from: (usize, usize)) {
5530        self.vim.jump_back.push(from);
5531        if self.vim.jump_back.len() > vim::JUMPLIST_MAX {
5532            self.vim.jump_back.remove(0);
5533        }
5534        self.vim.jump_fwd.clear();
5535    }
5536
5537    /// Push `pattern` onto the committed search history. Skips if the
5538    /// most recent entry already matches (consecutive dedupe) and trims
5539    /// the oldest entries beyond the history cap.
5540    pub fn record_search_history(&mut self, pattern: &str) {
5541        if pattern.is_empty() {
5542            return;
5543        }
5544        if self.vim.search_history.last().map(String::as_str) == Some(pattern) {
5545            return;
5546        }
5547        self.vim.search_history.push(pattern.to_string());
5548        let len = self.vim.search_history.len();
5549        if len > vim::SEARCH_HISTORY_MAX {
5550            self.vim
5551                .search_history
5552                .drain(0..len - vim::SEARCH_HISTORY_MAX);
5553        }
5554    }
5555
5556    /// Walk the search-prompt history by `dir` steps. `dir = -1` moves
5557    /// toward older entries (Ctrl-P / Up); `dir = 1` toward newer ones
5558    /// (Ctrl-N / Down). Stops at the ends; does nothing if there is no
5559    /// active search prompt.
5560    pub fn walk_search_history(&mut self, dir: isize) {
5561        if self.vim.search_history.is_empty() || self.vim.search_prompt.is_none() {
5562            return;
5563        }
5564        let len = self.vim.search_history.len();
5565        let next_idx = match (self.vim.search_history_cursor, dir) {
5566            (None, -1) => Some(len - 1),
5567            (None, 1) => return,
5568            (Some(i), -1) => i.checked_sub(1),
5569            (Some(i), 1) if i + 1 < len => Some(i + 1),
5570            _ => None,
5571        };
5572        let Some(idx) = next_idx else {
5573            return;
5574        };
5575        self.vim.search_history_cursor = Some(idx);
5576        let text = self.vim.search_history[idx].clone();
5577        if let Some(prompt) = self.vim.search_prompt.as_mut() {
5578            prompt.cursor = text.chars().count();
5579            prompt.text = text.clone();
5580        }
5581        self.push_search_pattern(&text);
5582    }
5583
5584    // ── Phase 6.6d: pre/post FSM bookkeeping ────────────────────────────────
5585    //
5586    // `begin_step` and `end_step` are the bookkeeping prelude/epilogue that
5587    // `hjkl_vim::dispatch_input` wraps around its per-mode FSM dispatch.
5588
5589    /// Pre-dispatch bookkeeping that must run before every per-mode FSM step.
5590    ///
5591    /// Call this at the start of every step; pass the returned
5592    /// [`StepBookkeeping`] to [`end_step`] after the FSM body finishes.
5593    ///
5594    /// Returns `Ok(bk)` when the caller should proceed with FSM dispatch.
5595    /// Returns `Err(consumed)` when the prelude itself handled the input
5596    /// (macro-stop chord); in that case skip the FSM body and do NOT call
5597    /// `end_step` — the macro-stop path is a true short-circuit with no
5598    /// epilogue needed.
5599    ///
5600    /// This method does NOT handle the search-prompt intercept — callers
5601    /// must check `search_prompt_state().is_some()` before calling `begin_step`
5602    /// and dispatch to the search-prompt FSM body directly.
5603    pub fn begin_step(&mut self, input: Input) -> Result<StepBookkeeping, bool> {
5604        use crate::input::Key;
5605        use vim::{Mode, Pending};
5606        // ── Timestamps ───────────────────────────────────────────────────────
5607        // Phase 7f: sync buffer before motion handlers see it.
5608        self.sync_buffer_content_from_textarea();
5609        // `:set timeoutlen` chord-timeout handling.
5610        let now = std::time::Instant::now();
5611        let host_now = self.host.now();
5612        let timed_out = match self.vim.last_input_host_at {
5613            Some(prev) => host_now.saturating_sub(prev) > self.settings.timeout_len,
5614            None => false,
5615        };
5616        if timed_out {
5617            let chord_in_flight = !matches!(self.vim.pending, Pending::None)
5618                || self.vim.count != 0
5619                || self.vim.pending_register.is_some()
5620                || self.vim.insert_pending_register;
5621            if chord_in_flight {
5622                self.vim.clear_pending_prefix();
5623            }
5624        }
5625        self.vim.last_input_at = Some(now);
5626        self.vim.last_input_host_at = Some(host_now);
5627        // ── Macro-stop: bare `q` outside Insert ends the recording ───────────
5628        if self.vim.recording_macro.is_some()
5629            && !self.vim.replaying_macro
5630            && matches!(self.vim.pending, Pending::None)
5631            && self.vim.mode != Mode::Insert
5632            && input.key == Key::Char('q')
5633            && !input.ctrl
5634            && !input.alt
5635        {
5636            let reg = self.vim.recording_macro.take().unwrap();
5637            let keys = std::mem::take(&mut self.vim.recording_keys);
5638            let text = crate::input::encode_macro(&keys);
5639            self.set_named_register_text(reg.to_ascii_lowercase(), text);
5640            return Err(true);
5641        }
5642        // ── Snapshots for epilogue ────────────────────────────────────────────
5643        let pending_was_macro_chord = matches!(
5644            self.vim.pending,
5645            Pending::RecordMacroTarget | Pending::PlayMacroTarget { .. }
5646        );
5647        let was_insert = self.vim.mode == Mode::Insert;
5648        let pre_visual_snapshot = match self.vim.mode {
5649            Mode::Visual => Some(vim::LastVisual {
5650                mode: Mode::Visual,
5651                anchor: self.vim.visual_anchor,
5652                cursor: self.cursor(),
5653                block_vcol: 0,
5654            }),
5655            Mode::VisualLine => Some(vim::LastVisual {
5656                mode: Mode::VisualLine,
5657                anchor: (self.vim.visual_line_anchor, 0),
5658                cursor: self.cursor(),
5659                block_vcol: 0,
5660            }),
5661            Mode::VisualBlock => Some(vim::LastVisual {
5662                mode: Mode::VisualBlock,
5663                anchor: self.vim.block_anchor,
5664                cursor: self.cursor(),
5665                block_vcol: self.vim.block_vcol,
5666            }),
5667            _ => None,
5668        };
5669        Ok(StepBookkeeping {
5670            pending_was_macro_chord,
5671            was_insert,
5672            pre_visual_snapshot,
5673        })
5674    }
5675
5676    /// Post-dispatch bookkeeping that must run after every per-mode FSM step.
5677    ///
5678    /// `input` is the same input that was passed to `begin_step`.
5679    /// `bk` is the [`StepBookkeeping`] returned by `begin_step`.
5680    /// `consumed` is the return value of the FSM body; this method returns
5681    /// it after running all epilogue invariants.
5682    ///
5683    /// Must NOT be called when `begin_step` returned `Err(...)`.
5684    pub fn end_step(&mut self, input: Input, bk: StepBookkeeping, consumed: bool) -> bool {
5685        use crate::input::Key;
5686        use vim::{Mode, Pending};
5687        let StepBookkeeping {
5688            pending_was_macro_chord,
5689            was_insert,
5690            pre_visual_snapshot,
5691        } = bk;
5692        // ── Visual-exit: set `<`/`>` marks and stash `last_visual` ───────────
5693        if let Some(snap) = pre_visual_snapshot
5694            && !matches!(
5695                self.vim.mode,
5696                Mode::Visual | Mode::VisualLine | Mode::VisualBlock
5697            )
5698        {
5699            let (lo, hi) = match snap.mode {
5700                Mode::Visual => {
5701                    if snap.anchor <= snap.cursor {
5702                        (snap.anchor, snap.cursor)
5703                    } else {
5704                        (snap.cursor, snap.anchor)
5705                    }
5706                }
5707                Mode::VisualLine => {
5708                    let r_lo = snap.anchor.0.min(snap.cursor.0);
5709                    let r_hi = snap.anchor.0.max(snap.cursor.0);
5710                    let vl_rope = self.buffer().rope();
5711                    let r_hi_clamped = r_hi.min(vl_rope.len_lines().saturating_sub(1));
5712                    let last_col = hjkl_buffer::rope_line_str(&vl_rope, r_hi_clamped)
5713                        .chars()
5714                        .count()
5715                        .saturating_sub(1);
5716                    ((r_lo, 0), (r_hi, last_col))
5717                }
5718                Mode::VisualBlock => {
5719                    let (r1, c1) = snap.anchor;
5720                    let (r2, c2) = snap.cursor;
5721                    ((r1.min(r2), c1.min(c2)), (r1.max(r2), c1.max(c2)))
5722                }
5723                _ => {
5724                    if snap.anchor <= snap.cursor {
5725                        (snap.anchor, snap.cursor)
5726                    } else {
5727                        (snap.cursor, snap.anchor)
5728                    }
5729                }
5730            };
5731            self.set_mark('<', lo);
5732            self.set_mark('>', hi);
5733            self.vim.last_visual = Some(snap);
5734        }
5735        // ── Ctrl-o one-shot-normal return to Insert ───────────────────────────
5736        if !was_insert
5737            && self.vim.one_shot_normal
5738            && self.vim.mode == Mode::Normal
5739            && matches!(self.vim.pending, Pending::None)
5740        {
5741            self.vim.one_shot_normal = false;
5742            self.vim.mode = Mode::Insert;
5743        }
5744        // ── Content + viewport sync ───────────────────────────────────────────
5745        self.sync_buffer_content_from_textarea();
5746        if !self.vim.viewport_pinned {
5747            self.ensure_cursor_in_scrolloff();
5748        }
5749        self.vim.viewport_pinned = false;
5750        // ── Recorder hook ─────────────────────────────────────────────────────
5751        if self.vim.recording_macro.is_some()
5752            && !self.vim.replaying_macro
5753            && input.key != Key::Char('q')
5754            && !pending_was_macro_chord
5755        {
5756            self.vim.recording_keys.push(input);
5757        }
5758        // ── Phase 6.3: current_mode sync ─────────────────────────────────────
5759        self.vim.current_mode = self.vim.public_mode();
5760        consumed
5761    }
5762
5763    // ── Phase 6.6e: additional public primitives for hjkl-vim::normal ─────────
5764
5765    /// `true` when the editor is in any visual mode (Visual / VisualLine /
5766    /// VisualBlock). Convenience wrapper around `vim_mode()` for hjkl-vim.
5767    pub fn is_visual(&self) -> bool {
5768        matches!(
5769            self.vim.mode,
5770            vim::Mode::Visual | vim::Mode::VisualLine | vim::Mode::VisualBlock
5771        )
5772    }
5773
5774    /// Compute the VisualBlock rectangle corners: `(top_row, bot_row,
5775    /// left_col, right_col)`. Uses `block_anchor` and `block_vcol` (the
5776    /// virtual column, which survives j/k clamping to shorter rows).
5777    ///
5778    /// Promoted in Phase 6.6e so `hjkl-vim::normal` can compute the block
5779    /// extents needed for VisualBlock `I` / `A` / `r` without accessing
5780    /// engine-private helpers.
5781    pub fn visual_block_bounds(&self) -> (usize, usize, usize, usize) {
5782        let (ar, ac) = self.vim.block_anchor;
5783        let (cr, _) = self.cursor();
5784        let cc = self.vim.block_vcol;
5785        let top = ar.min(cr);
5786        let bot = ar.max(cr);
5787        let left = ac.min(cc);
5788        let right = ac.max(cc);
5789        (top, bot, left, right)
5790    }
5791
5792    /// Return the character count (code-point count) of line `row`, or `0`
5793    /// when `row` is out of range. Used by hjkl-vim::normal for VisualBlock
5794    /// I / A column computations.
5795    pub fn line_char_count(&self, row: usize) -> usize {
5796        buf_line_chars(&self.buffer, row)
5797    }
5798
5799    /// Apply operator over `motion` with `count` repetitions. The full
5800    /// vim-quirks path (operator context for `l`, clamping, etc.) is applied.
5801    ///
5802    /// Promoted to the public surface in Phase 6.6e so `hjkl-vim::normal`'s
5803    /// relocated `handle_after_op` can call it directly with a parsed `Motion`
5804    /// without re-entering the engine FSM.
5805    pub fn apply_op_with_motion_direct(
5806        &mut self,
5807        op: crate::vim::Operator,
5808        motion: &crate::vim::Motion,
5809        count: usize,
5810    ) {
5811        vim::apply_op_with_motion(self, op, motion, count);
5812    }
5813
5814    /// `Ctrl-a` / `Ctrl-x` — adjust the number under or after the cursor.
5815    /// `delta = 1` increments; `delta = -1` decrements; larger deltas
5816    /// multiply as in vim's `5<C-a>`. Promoted in Phase 6.6e so
5817    /// `hjkl-vim::normal` can dispatch `Ctrl-a` / `Ctrl-x`.
5818    pub fn adjust_number(&mut self, delta: i64) {
5819        vim::adjust_number(self, delta);
5820    }
5821
5822    /// Open the `/` or `?` search prompt. `forward = true` for `/`,
5823    /// `false` for `?`. Promoted in Phase 6.6e so `hjkl-vim::normal` can
5824    /// dispatch `/` and `?` without re-entering the engine FSM.
5825    pub fn enter_search(&mut self, forward: bool) {
5826        vim::enter_search(self, forward);
5827    }
5828
5829    /// Enter Insert mode at the left edge of a VisualBlock selection for
5830    /// `I`. Moves the cursor to `(top, col)`, resets to Normal internally,
5831    /// then begins an insert session with `InsertReason::BlockEdge`.
5832    ///
5833    /// Promoted in Phase 6.6e so `hjkl-vim::normal` can dispatch the
5834    /// VisualBlock `I` command without accessing engine-private helpers.
5835    pub fn visual_block_insert_at_left(&mut self, top: usize, bot: usize, col: usize) {
5836        self.jump_cursor(top, col);
5837        self.vim.mode = vim::Mode::Normal;
5838        vim::begin_insert(self, 1, vim::InsertReason::BlockEdge { top, bot, col });
5839    }
5840
5841    /// Enter Insert mode at the right edge of a VisualBlock selection for
5842    /// `A`. Moves the cursor to `(top, col)`, resets to Normal internally,
5843    /// then begins an insert session with `InsertReason::BlockEdge`.
5844    ///
5845    /// Promoted in Phase 6.6e so `hjkl-vim::normal` can dispatch the
5846    /// VisualBlock `A` command without accessing engine-private helpers.
5847    pub fn visual_block_append_at_right(&mut self, top: usize, bot: usize, col: usize) {
5848        self.jump_cursor(top, col);
5849        self.vim.mode = vim::Mode::Normal;
5850        vim::begin_insert(self, 1, vim::InsertReason::BlockEdge { top, bot, col });
5851    }
5852
5853    /// Execute a motion (cursor movement), push to the jumplist for big jumps,
5854    /// and update the sticky column. Mirrors the engine FSM's `execute_motion`
5855    /// free function. Promoted in Phase 6.6e for `hjkl-vim::normal`.
5856    pub fn execute_motion(&mut self, motion: crate::vim::Motion, count: usize) {
5857        vim::execute_motion(self, motion, count);
5858    }
5859
5860    /// Update the VisualBlock virtual column after a motion in VisualBlock mode.
5861    /// Horizontal motions sync `block_vcol` to the cursor column; vertical /
5862    /// non-h/l motions leave it alone so the intended column survives clamping
5863    /// to shorter rows. Promoted in Phase 6.6e for `hjkl-vim::normal`.
5864    pub fn update_block_vcol(&mut self, motion: &crate::vim::Motion) {
5865        vim::update_block_vcol(self, motion);
5866    }
5867
5868    /// Apply `op` over the current visual selection (char-wise, linewise, or
5869    /// block). Mirrors the engine's internal `apply_visual_operator` free fn.
5870    /// Promoted in Phase 6.6e for `hjkl-vim::normal`.
5871    pub fn apply_visual_operator(&mut self, op: crate::vim::Operator) {
5872        vim::apply_visual_operator(self, op);
5873    }
5874
5875    /// Replace each character cell in the current VisualBlock selection with
5876    /// `ch`. Mirrors the engine's `block_replace` free fn. Promoted in Phase
5877    /// 6.6e for the VisualBlock `r<ch>` command in `hjkl-vim::normal`.
5878    pub fn replace_block_char(&mut self, ch: char) {
5879        vim::block_replace(self, ch);
5880    }
5881
5882    /// Extend the current visual selection to cover the text object identified
5883    /// by `ch` and `inner`. Maps `ch` to a `TextObject`, resolves its range
5884    /// via `text_object_range`, then updates the visual anchor and cursor.
5885    ///
5886    /// Promoted in Phase 6.6e for the visual-mode `i<ch>` / `a<ch>` commands
5887    /// in `hjkl-vim::normal::handle_visual_text_obj`.
5888    pub fn visual_text_obj_extend(&mut self, ch: char, inner: bool) {
5889        use crate::vim::{Mode, TextObject};
5890        let obj = match ch {
5891            'w' => TextObject::Word { big: false },
5892            'W' => TextObject::Word { big: true },
5893            '"' | '\'' | '`' => TextObject::Quote(ch),
5894            '(' | ')' | 'b' => TextObject::Bracket('('),
5895            '[' | ']' => TextObject::Bracket('['),
5896            '{' | '}' | 'B' => TextObject::Bracket('{'),
5897            '<' | '>' => TextObject::Bracket('<'),
5898            'p' => TextObject::Paragraph,
5899            't' => TextObject::XmlTag,
5900            's' => TextObject::Sentence,
5901            _ => return,
5902        };
5903        let Some((start, end, kind)) = vim::text_object_range(self, obj, inner, 1) else {
5904            return;
5905        };
5906        match kind {
5907            crate::vim::RangeKind::Linewise => {
5908                self.vim.visual_line_anchor = start.0;
5909                self.vim.mode = Mode::VisualLine;
5910                self.vim.current_mode = VimMode::VisualLine;
5911                self.jump_cursor(end.0, 0);
5912            }
5913            _ => {
5914                self.vim.mode = Mode::Visual;
5915                self.vim.current_mode = VimMode::Visual;
5916                self.vim.visual_anchor = (start.0, start.1);
5917                let (er, ec) = vim::retreat_one(self, end);
5918                self.jump_cursor(er, ec);
5919            }
5920        }
5921    }
5922}
5923
5924/// Visual column of the character at `char_col` in `line`, treating `\t`
5925/// as expansion to the next `tab_width` stop and every other char as
5926/// 1 cell wide. Wide-char support (CJK, emoji) is a separate concern —
5927/// the cursor math elsewhere also assumes single-cell chars.
5928fn visual_col_for_char(line: &str, char_col: usize, tab_width: usize) -> usize {
5929    let mut visual = 0usize;
5930    for (i, ch) in line.chars().enumerate() {
5931        if i >= char_col {
5932            break;
5933        }
5934        if ch == '\t' {
5935            visual += tab_width - (visual % tab_width);
5936        } else {
5937            visual += 1;
5938        }
5939    }
5940    visual
5941}
5942
5943#[cfg(test)]
5944mod shift_syntax_spans_tests {
5945    use super::*;
5946    use crate::types::{ContentEdit, DefaultHost, Options, Style};
5947    use hjkl_buffer::Buffer;
5948
5949    fn ed_with_spans(line_count: usize) -> Editor<Buffer, DefaultHost> {
5950        let text = (0..line_count)
5951            .map(|i| format!("row{i}"))
5952            .collect::<Vec<_>>()
5953            .join("\n");
5954        let buf = Buffer::from_str(&text);
5955        let mut e = Editor::new(buf, DefaultHost::new(), Options::default());
5956        // Synthesize span rows so we can detect which survive a shift.
5957        // Use a distinct fg colour per row so spans are identifiable.
5958        let style = Style::default();
5959        let spans: Vec<Vec<(usize, usize, Style)>> =
5960            (0..line_count).map(|_| vec![(0, 1, style)]).collect();
5961        e.install_syntax_spans(spans);
5962        e
5963    }
5964
5965    fn edit_insert_newline_at(row: u32, col: u32) -> ContentEdit {
5966        // Pressing Enter: zero-width insertion that produces one new row.
5967        ContentEdit {
5968            start_byte: 0,
5969            old_end_byte: 0,
5970            new_end_byte: 1,
5971            start_position: (row, col),
5972            old_end_position: (row, col),
5973            new_end_position: (row + 1, 0),
5974        }
5975    }
5976
5977    fn edit_join_rows(row: u32, col: u32) -> ContentEdit {
5978        // Backspace at start of `row+1`: removes the newline, joining the
5979        // two rows. old_end is on `row+1`, new_end on `row`.
5980        ContentEdit {
5981            start_byte: 0,
5982            old_end_byte: 1,
5983            new_end_byte: 0,
5984            start_position: (row, col),
5985            old_end_position: (row + 1, 0),
5986            new_end_position: (row, col),
5987        }
5988    }
5989
5990    #[test]
5991    fn insert_grows_buffer_spans_in_place() {
5992        let mut e = ed_with_spans(4);
5993        // Newline at row 1 → buffer grew by one row.
5994        e.shift_syntax_spans_for_edits(&[edit_insert_newline_at(1, 1)]);
5995        assert_eq!(
5996            e.buffer_spans().len(),
5997            5,
5998            "row-count grew → spans rows must match"
5999        );
6000        // The empty row should be at index 2 (right after the split point).
6001        assert!(e.buffer_spans()[2].is_empty(), "inserted row sits at oer+1");
6002        // Surrounding rows kept their content.
6003        assert!(!e.buffer_spans()[0].is_empty());
6004        assert!(!e.buffer_spans()[1].is_empty());
6005        assert!(!e.buffer_spans()[3].is_empty());
6006        assert!(!e.buffer_spans()[4].is_empty());
6007    }
6008
6009    #[test]
6010    fn delete_shrinks_buffer_spans_in_place() {
6011        let mut e = ed_with_spans(4);
6012        e.shift_syntax_spans_for_edits(&[edit_join_rows(1, 1)]);
6013        assert_eq!(
6014            e.buffer_spans().len(),
6015            3,
6016            "row-count shrank → spans rows must match"
6017        );
6018    }
6019
6020    #[test]
6021    fn same_row_edit_leaves_rows_untouched() {
6022        let mut e = ed_with_spans(3);
6023        let edit = ContentEdit {
6024            start_byte: 0,
6025            old_end_byte: 0,
6026            new_end_byte: 1,
6027            start_position: (1, 0),
6028            old_end_position: (1, 0),
6029            new_end_position: (1, 1),
6030        };
6031        e.shift_syntax_spans_for_edits(&[edit]);
6032        assert_eq!(e.buffer_spans().len(), 3);
6033        for row in 0..3 {
6034            assert!(
6035                !e.buffer_spans()[row].is_empty(),
6036                "row {row} should still hold its span"
6037            );
6038        }
6039    }
6040
6041    #[test]
6042    fn ordered_edits_apply_against_prior_state() {
6043        let mut e = ed_with_spans(3);
6044        // Two consecutive inserts: each adds a row.
6045        e.shift_syntax_spans_for_edits(&[
6046            edit_insert_newline_at(0, 1),
6047            edit_insert_newline_at(1, 1),
6048        ]);
6049        assert_eq!(e.buffer_spans().len(), 5);
6050    }
6051
6052    /// Build a buffer with `line_count` rows where row `i` has a span at
6053    /// column `i + 1` so the rows are independently identifiable after a
6054    /// shift (otherwise all spans look identical and can't tell which
6055    /// original row's spans landed at which post-shift index).
6056    fn ed_with_distinguishable_spans(line_count: usize) -> Editor<Buffer, DefaultHost> {
6057        let text = (0..line_count)
6058            .map(|i| format!("rowwwwwwwwww{i}"))
6059            .collect::<Vec<_>>()
6060            .join("\n");
6061        let buf = Buffer::from_str(&text);
6062        let mut e = Editor::new(buf, DefaultHost::new(), Options::default());
6063        let style = Style::default();
6064        let spans: Vec<Vec<(usize, usize, Style)>> = (0..line_count)
6065            .map(|i| vec![(i + 1, i + 2, style)])
6066            .collect();
6067        e.install_syntax_spans(spans);
6068        e
6069    }
6070
6071    /// Regression for off-by-one in `shift_syntax_spans_for_edits`.
6072    ///
6073    /// `P` (paste-before) at column 0 of row 0 inserts new lines BEFORE
6074    /// row 0. The pre-paste rows should shift down by N. The fix inserts
6075    /// empty rows at idx `start.row` (not `oer + 1`) when `start.col == 0`.
6076    ///
6077    /// Symptom before the fix: row 0's spans stayed at idx 0 after a
6078    /// 4-row `ggP`, but the file's row 0 was now the pasted content (no
6079    /// spans available yet). Display: pasted row 0 painted with the
6080    /// pre-paste row 0's spans (LUCKILY identical content in many cases)
6081    /// while the *shifted* pre-paste row 0 (now at file row 4) painted
6082    /// with the pre-paste row 1's spans — visible as the WRONG row
6083    /// showing the wrong-row colours.
6084    #[test]
6085    fn shift_for_paste_at_start_of_row_zero() {
6086        let mut e = ed_with_distinguishable_spans(7);
6087        // Snapshot: row i has a span at col (i+1, i+2).
6088        let pre = e.buffer_spans().to_vec();
6089        // P at (0, 0) inserting 4 lines.
6090        let edit = ContentEdit {
6091            start_byte: 0,
6092            old_end_byte: 0,
6093            new_end_byte: 4,
6094            start_position: (0, 0),
6095            old_end_position: (0, 0),
6096            new_end_position: (4, 0),
6097        };
6098        e.shift_syntax_spans_for_edits(&[edit]);
6099        assert_eq!(e.buffer_spans().len(), 11, "row count grew by 4");
6100        // Rows 0..4 are the new pasted lines — should be EMPTY placeholders.
6101        for row in 0..4 {
6102            assert!(
6103                e.buffer_spans()[row].is_empty(),
6104                "row {row} (new paste) must be empty placeholder, got {:?}",
6105                e.buffer_spans()[row]
6106            );
6107        }
6108        // Rows 4..11 are the original rows 0..7 shifted down by 4.
6109        for (orig_row, orig_spans) in pre.iter().enumerate() {
6110            let new_row = orig_row + 4;
6111            assert_eq!(
6112                &e.buffer_spans()[new_row],
6113                orig_spans,
6114                "original row {orig_row} should be at file row {new_row} after \
6115                 paste-before-row-0"
6116            );
6117        }
6118    }
6119
6120    /// Same idea for paste at start of a non-zero row: `2GP` inserts 3
6121    /// lines before row 2.
6122    #[test]
6123    fn shift_for_paste_at_start_of_middle_row() {
6124        let mut e = ed_with_distinguishable_spans(5);
6125        let pre = e.buffer_spans().to_vec();
6126        // Insert 3 lines at (2, 0).
6127        let edit = ContentEdit {
6128            start_byte: 0,
6129            old_end_byte: 0,
6130            new_end_byte: 3,
6131            start_position: (2, 0),
6132            old_end_position: (2, 0),
6133            new_end_position: (5, 0),
6134        };
6135        e.shift_syntax_spans_for_edits(&[edit]);
6136        assert_eq!(e.buffer_spans().len(), 8);
6137        // Rows 0..2 unchanged (before the insertion point).
6138        assert_eq!(e.buffer_spans()[0], pre[0]);
6139        assert_eq!(e.buffer_spans()[1], pre[1]);
6140        // Rows 2..5 are new pasted lines.
6141        for row in 2..5 {
6142            assert!(
6143                e.buffer_spans()[row].is_empty(),
6144                "row {row} must be empty placeholder"
6145            );
6146        }
6147        // Rows 5..8 are originals 2..5 shifted down by 3.
6148        for (orig_row, orig_spans) in pre.iter().enumerate().take(5).skip(2) {
6149            let new_row = orig_row + 3;
6150            assert_eq!(
6151                &e.buffer_spans()[new_row],
6152                orig_spans,
6153                "original row {orig_row} should land at file row {new_row}"
6154            );
6155        }
6156    }
6157
6158    /// Regression: pasting N rows at the beginning of the buffer used to
6159    /// run `Vec::insert(0, ...)` once per row → O(N²) memmove. samply
6160    /// showed this path eating 87 % of paste CPU on a 60 k-row paste.
6161    /// The splice rewrite is O(N).
6162    ///
6163    /// Asserting a hard wall-clock bound is brittle on slow CI, so we
6164    /// pick a budget the old code blows past by >10×: 60 k rows in
6165    /// under 200 ms even on a debug build. Old impl: ~3-5 seconds.
6166    #[test]
6167    fn shift_for_60k_row_paste_at_row_zero_is_under_200ms() {
6168        let mut e = ed_with_distinguishable_spans(8);
6169        let edit = ContentEdit {
6170            start_byte: 0,
6171            old_end_byte: 0,
6172            new_end_byte: 60_000,
6173            start_position: (0, 0),
6174            old_end_position: (0, 0),
6175            new_end_position: (60_000, 0),
6176        };
6177        let t = std::time::Instant::now();
6178        e.shift_syntax_spans_for_edits(&[edit]);
6179        let elapsed = t.elapsed();
6180        assert!(
6181            elapsed.as_millis() < 200,
6182            "60k-row shift took {elapsed:?}; budget is 200 ms (catches \
6183             reintroduction of the O(N²) per-row insert loop)"
6184        );
6185        assert_eq!(e.buffer_spans().len(), 60_008);
6186    }
6187
6188    /// Regression: `push_undo` used to clone every line into a
6189    /// `Vec<String>` (162 k heap allocations on a 162 k-row buffer per
6190    /// snapshot). Now stores an `Arc<String>` shared with
6191    /// `Buffer::content_joined`'s per-dirty_gen cache — a warm snapshot
6192    /// is an `Arc::clone` (one ptr bump).
6193    ///
6194    /// Test: snapshot a 60 k-row buffer 100 times. With the Arc impl
6195    /// this is essentially free (one join then 99 Arc::clones). The
6196    /// old `Vec<String>` impl required 60 k allocations per call =
6197    /// 6 M allocations, easily seconds even on release.
6198    #[test]
6199    fn push_undo_snapshot_arc_clone_is_under_100ms_for_100_snapshots() {
6200        use crate::types::{DefaultHost, Options};
6201        let text = "x\n".repeat(60_000);
6202        let buf = hjkl_buffer::Buffer::from_str(&text);
6203        let mut e = Editor::new(buf, DefaultHost::default(), Options::default());
6204        // Warm the cache: one join, subsequent snapshots Arc::clone it.
6205        e.push_undo();
6206        let t = std::time::Instant::now();
6207        for _ in 0..100 {
6208            e.push_undo();
6209        }
6210        let elapsed = t.elapsed();
6211        assert!(
6212            elapsed.as_millis() < 100,
6213            "100 snapshots of a 60k-row buffer took {elapsed:?}; budget \
6214             100 ms. Likely regressed to per-line cloning."
6215        );
6216    }
6217}
6218
6219#[cfg(test)]
6220mod earlier_later_tests {
6221    use super::*;
6222    use crate::types::{DefaultHost, Options};
6223    use hjkl_buffer::Buffer;
6224    use std::time::{Duration, SystemTime};
6225
6226    fn make_ed(content: &str) -> Editor<Buffer, DefaultHost> {
6227        let buf = Buffer::from_str(content);
6228        Editor::new(buf, DefaultHost::default(), Options::default())
6229    }
6230
6231    // ── step-based ───────────────────────────────────────────────────────────
6232
6233    #[test]
6234    fn earlier_by_steps_n_undoes_n_changes() {
6235        let mut ed = make_ed("hello");
6236        ed.push_undo(); // snap 1
6237        ed.push_undo(); // snap 2
6238        ed.push_undo(); // snap 3
6239        assert_eq!(ed.undo_stack_len(), 3);
6240        let applied = ed.earlier_by_steps(2);
6241        assert_eq!(applied, 2);
6242        assert_eq!(ed.undo_stack_len(), 1);
6243    }
6244
6245    #[test]
6246    fn earlier_by_steps_caps_at_stack_size() {
6247        let mut ed = make_ed("hello");
6248        ed.push_undo(); // snap 1
6249        // Ask for 10 but only 1 available.
6250        let applied = ed.earlier_by_steps(10);
6251        assert_eq!(applied, 1);
6252        assert_eq!(ed.undo_stack_len(), 0);
6253    }
6254
6255    #[test]
6256    fn later_by_steps_n_redoes_n_changes() {
6257        let mut ed = make_ed("hello");
6258        ed.push_undo(); // snap 1
6259        ed.push_undo(); // snap 2
6260        ed.push_undo(); // snap 3
6261        // Undo all 3 so they're on redo stack.
6262        ed.earlier_by_steps(3);
6263        assert_eq!(ed.undo_stack_len(), 0);
6264        let applied = ed.later_by_steps(2);
6265        assert_eq!(applied, 2);
6266        assert_eq!(ed.undo_stack_len(), 2);
6267    }
6268
6269    #[test]
6270    fn later_by_steps_caps_at_redo_stack_size() {
6271        let mut ed = make_ed("hello");
6272        ed.push_undo(); // snap 1
6273        ed.earlier_by_steps(1); // moves to redo
6274        let applied = ed.later_by_steps(99);
6275        assert_eq!(applied, 1);
6276    }
6277
6278    // ── time-based ───────────────────────────────────────────────────────────
6279
6280    fn epoch_plus(secs: u64) -> SystemTime {
6281        SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
6282    }
6283
6284    #[test]
6285    fn earlier_by_time_stops_at_target_boundary() {
6286        let mut ed = make_ed("hello");
6287        // Push 3 entries at t-30s, t-20s, t-10s (relative to epoch).
6288        ed.push_undo_at(epoch_plus(30));
6289        ed.push_undo_at(epoch_plus(40));
6290        ed.push_undo_at(epoch_plus(50));
6291        // Redo stack is empty; undo has 3 entries.
6292        // target = epoch+35 → should undo entries at t=50 and t=40, stop at t=30
6293        let target = epoch_plus(35);
6294        let applied = ed.earlier_by_time(target);
6295        assert_eq!(applied, 2, "should undo t=50 and t=40; stop at t=30");
6296        assert_eq!(ed.undo_stack_len(), 1, "t=30 entry remains");
6297    }
6298
6299    #[test]
6300    fn earlier_by_time_empty_stack_returns_zero() {
6301        let mut ed = make_ed("hello");
6302        let applied = ed.earlier_by_time(epoch_plus(999));
6303        assert_eq!(applied, 0);
6304        assert_eq!(ed.undo_stack_len(), 0);
6305    }
6306
6307    #[test]
6308    fn later_by_time_target_in_future_redoes_all() {
6309        let mut ed = make_ed("hello");
6310        ed.push_undo_at(epoch_plus(10));
6311        ed.push_undo_at(epoch_plus(20));
6312        // Undo both → they move to redo stack with their timestamps preserved.
6313        ed.earlier_by_steps(2);
6314        // target far in future: should redo all.
6315        let applied = ed.later_by_time(epoch_plus(9999));
6316        assert_eq!(applied, 2);
6317        assert_eq!(ed.undo_stack_len(), 2);
6318    }
6319}
6320
6321#[cfg(test)]
6322mod insert_mode_scrolloff_tests {
6323    use super::*;
6324    use crate::types::{DefaultHost, Host, Options};
6325    use crate::vim::Mode;
6326    use hjkl_buffer::Buffer;
6327
6328    fn ed_with_lines(line_count: usize) -> Editor<Buffer, DefaultHost> {
6329        let text = (0..line_count)
6330            .map(|i| format!("row{i}"))
6331            .collect::<Vec<_>>()
6332            .join("\n");
6333        let buf = Buffer::from_str(&text);
6334        let mut e = Editor::new(buf, DefaultHost::new(), Options::default());
6335        // Viewport: 20 rows tall, starts at top.
6336        let vp = e.host_mut().viewport_mut();
6337        vp.width = 80;
6338        vp.height = 20;
6339        vp.top_row = 0;
6340        vp.top_col = 0;
6341        e.set_viewport_height(20);
6342        e.vim.mode = Mode::Insert;
6343        e
6344    }
6345
6346    /// Regression: holding Enter in insert mode used to scroll the cursor
6347    /// off the viewport because `insert_newline` (called from the app's
6348    /// `dispatch_insert_key`) bypasses the FSM `step` that runs
6349    /// `ensure_cursor_in_scrolloff`. The post-mutation helper now runs
6350    /// scrolloff for every insert primitive — the cursor must stay
6351    /// within `scrolloff` rows of the bottom edge.
6352    #[test]
6353    fn insert_newline_keeps_cursor_in_scrolloff() {
6354        let mut e = ed_with_lines(200);
6355        // Park cursor at the bottom edge of the viewport (row 19).
6356        e.set_cursor_doc(19, 0);
6357        // Press Enter 50 times. Cursor moves down each newline; without
6358        // scrolloff the cursor would slide off the bottom of the
6359        // viewport at row 20+ and the user would type blind.
6360        for _ in 0..50 {
6361            e.insert_newline();
6362        }
6363        let (cursor_row, _) = e.cursor();
6364        let vp = e.host().viewport();
6365        let cursor_screen_row = cursor_row.saturating_sub(vp.top_row);
6366        let scrolloff = e.settings().scrolloff;
6367        let margin = scrolloff.min(vp.height as usize - 1) / 2;
6368        let max_screen_row = vp.height as usize - 1 - margin;
6369        assert!(
6370            cursor_screen_row <= max_screen_row,
6371            "cursor screen row {cursor_screen_row} exceeded scrolloff bound {max_screen_row} \
6372             (cursor_row={cursor_row}, vp.top_row={vp_top}, vp.height={vp_h})",
6373            vp_top = vp.top_row,
6374            vp_h = vp.height,
6375        );
6376    }
6377
6378    /// Same check for `insert_arrow(Down)` — cursor-only motion that also
6379    /// must trigger scrolloff.
6380    #[test]
6381    fn insert_arrow_down_keeps_cursor_in_scrolloff() {
6382        let mut e = ed_with_lines(200);
6383        e.set_cursor_doc(19, 0);
6384        for _ in 0..50 {
6385            e.insert_arrow(vim::InsertDir::Down);
6386        }
6387        let (cursor_row, _) = e.cursor();
6388        let vp = e.host().viewport();
6389        let cursor_screen_row = cursor_row.saturating_sub(vp.top_row);
6390        let scrolloff = e.settings().scrolloff;
6391        let margin = scrolloff.min(vp.height as usize - 1) / 2;
6392        let max_screen_row = vp.height as usize - 1 - margin;
6393        assert!(
6394            cursor_screen_row <= max_screen_row,
6395            "cursor screen row {cursor_screen_row} exceeded scrolloff bound {max_screen_row}"
6396        );
6397    }
6398}