Skip to main content

hjkl_engine/
editor.rs

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