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