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::KeybindingMode;
10use std::sync::atomic::{AtomicU16, Ordering};
11use std::time::SystemTime;
12
13/// Map a [`hjkl_buffer::Edit`] to one or more SPEC
14/// [`crate::types::Edit`] (`EditOp`) records.
15///
16/// Most buffer edits map to a single EditOp. Block ops
17/// ([`hjkl_buffer::Edit::InsertBlock`] /
18/// [`hjkl_buffer::Edit::DeleteBlockChunks`]) emit one EditOp per row
19/// touched — they edit non-contiguous cells and a single
20/// `range..range` can't represent the rectangle.
21///
22/// Returns an empty vec when the edit isn't representable (no buffer
23/// variant currently fails this check).
24fn edit_to_editops(edit: &hjkl_buffer::Edit) -> Vec<crate::types::Edit> {
25    use crate::types::{Edit as Op, Pos};
26    use hjkl_buffer::Edit as B;
27    let to_pos = |p: hjkl_buffer::Position| Pos {
28        line: p.row as u32,
29        col: p.col as u32,
30    };
31    match edit {
32        B::InsertChar { at, ch } => vec![Op {
33            range: to_pos(*at)..to_pos(*at),
34            replacement: ch.to_string(),
35        }],
36        B::InsertStr { at, text } => vec![Op {
37            range: to_pos(*at)..to_pos(*at),
38            replacement: text.clone(),
39        }],
40        B::DeleteRange { start, end, .. } => vec![Op {
41            range: to_pos(*start)..to_pos(*end),
42            replacement: String::new(),
43        }],
44        B::Replace { start, end, with } => vec![Op {
45            range: to_pos(*start)..to_pos(*end),
46            replacement: with.clone(),
47        }],
48        B::JoinLines {
49            row,
50            count,
51            with_space,
52        } => {
53            // Joining `count` rows after `row` collapses
54            // [(row+1, 0) .. (row+count, EOL)] into the joined
55            // sentinel. The replacement is either an empty string
56            // (gJ) or " " between segments (J).
57            let start = Pos {
58                line: *row as u32 + 1,
59                col: 0,
60            };
61            let end = Pos {
62                line: (*row + *count) as u32,
63                col: u32::MAX, // covers to EOL of the last source row
64            };
65            vec![Op {
66                range: start..end,
67                replacement: if *with_space {
68                    " ".into()
69                } else {
70                    String::new()
71                },
72            }]
73        }
74        B::SplitLines {
75            row,
76            cols,
77            inserted_space: _,
78        } => {
79            // SplitLines reverses a JoinLines: insert a `\n`
80            // (and optional dropped space) at each col on `row`.
81            cols.iter()
82                .map(|c| {
83                    let p = Pos {
84                        line: *row as u32,
85                        col: *c as u32,
86                    };
87                    Op {
88                        range: p..p,
89                        replacement: "\n".into(),
90                    }
91                })
92                .collect()
93        }
94        B::InsertBlock { at, chunks } => {
95            // One EditOp per row in the block — non-contiguous edits.
96            chunks
97                .iter()
98                .enumerate()
99                .map(|(i, chunk)| {
100                    let p = Pos {
101                        line: at.row as u32 + i as u32,
102                        col: at.col as u32,
103                    };
104                    Op {
105                        range: p..p,
106                        replacement: chunk.clone(),
107                    }
108                })
109                .collect()
110        }
111        B::DeleteBlockChunks { at, widths } => {
112            // One EditOp per row, deleting `widths[i]` chars at
113            // `(at.row + i, at.col)`.
114            widths
115                .iter()
116                .enumerate()
117                .map(|(i, w)| {
118                    let start = Pos {
119                        line: at.row as u32 + i as u32,
120                        col: at.col as u32,
121                    };
122                    let end = Pos {
123                        line: at.row as u32 + i as u32,
124                        col: at.col as u32 + *w as u32,
125                    };
126                    Op {
127                        range: start..end,
128                        replacement: String::new(),
129                    }
130                })
131                .collect()
132        }
133    }
134}
135
136/// Sum of bytes from the start of the buffer to the start of `row`.
137/// Byte offset of the first byte of `row` within the canonical
138/// `lines().join("\n")` byte rendering. Pre-rope this walked every row
139/// from 0 to `row` allocating a `String` per row to read its `.len()` —
140/// O(row) allocations per call, fired from `position_to_byte_coords` on
141/// every `insert_char`. At the bottom of a 1.86 M-line buffer that was
142/// 1.86 M String allocations per keystroke (the dominant cost of the
143/// "edits at the bottom of the file are slow" symptom).
144///
145/// Now O(log N): ropey's `line_to_byte` walks the B-tree's per-node
146/// byte counts. No String materialization.
147#[inline]
148fn buffer_byte_of_row(buf: &hjkl_buffer::Buffer, row: usize) -> usize {
149    let rope = buf.rope();
150    let row = row.min(rope.len_lines());
151    rope.line_to_byte(row)
152}
153
154/// Convert an `hjkl_buffer::Position` (char-indexed col) into byte
155/// coordinates `(byte_within_buffer, (row, col_byte))` against the
156/// **pre-edit** buffer.
157fn position_to_byte_coords(
158    buf: &hjkl_buffer::Buffer,
159    pos: hjkl_buffer::Position,
160) -> (usize, (u32, u32)) {
161    let row = pos.row.min(buf.row_count().saturating_sub(1));
162    let rope = buf.rope();
163    let line = hjkl_buffer::rope_line_str(&rope, row);
164    let col_byte = pos.byte_offset(&line);
165    let byte = buffer_byte_of_row(buf, row) + col_byte;
166    (byte, (row as u32, col_byte as u32))
167}
168
169/// Walk `bytes[..end]` counting newlines and return the (row, col_byte)
170/// position at byte offset `end`. `col_byte` is the byte distance from
171/// the most recent `\n` (or buffer start). Used to translate a byte
172/// offset into a tree-sitter `Point`.
173fn byte_to_row_col(bytes: &[u8], end: usize) -> (u32, u32) {
174    let end = end.min(bytes.len());
175    let mut row: u32 = 0;
176    let mut row_start: usize = 0;
177    for (i, &b) in bytes[..end].iter().enumerate() {
178        if b == b'\n' {
179            row += 1;
180            row_start = i + 1;
181        }
182    }
183    (row, (end - row_start) as u32)
184}
185
186/// Rope-backed minimal content-edit diff for the undo/redo
187/// `restore_text` path. Walks `old_rope` chunk-by-chunk for the
188/// common-prefix / common-suffix scan instead of forcing a full
189/// `content_joined()` materialization (~3 MB per undo on huge files).
190///
191/// `ropey::Rope::bytes()` and `bytes_at(n).reversed()` give O(log N)
192/// seek + O(1)-per-byte step, so the scan cost matches the contiguous
193/// `&[u8]` version without the materialization alloc.
194fn minimal_content_edit_rope(old_rope: &ropey::Rope, new_text: &str) -> crate::types::ContentEdit {
195    let new_bytes = new_text.as_bytes();
196    let old_len = old_rope.len_bytes();
197    let new_len = new_bytes.len();
198    let common = old_len.min(new_len);
199
200    // Common prefix length — forward walk through rope bytes.
201    let mut prefix = 0;
202    let mut fwd = old_rope.bytes();
203    while prefix < common {
204        match fwd.next() {
205            Some(b) if b == new_bytes[prefix] => prefix += 1,
206            _ => break,
207        }
208    }
209    while prefix > 0 && prefix < old_len && (old_rope.byte(prefix) & 0b1100_0000) == 0b1000_0000 {
210        prefix -= 1;
211    }
212
213    // Common suffix length — backward walk through rope bytes.
214    let mut suffix = 0;
215    let max_suffix = (old_len - prefix).min(new_len - prefix);
216    let mut rev = old_rope.bytes_at(old_len).reversed();
217    while suffix < max_suffix {
218        match rev.next() {
219            Some(b) if b == new_bytes[new_len - 1 - suffix] => suffix += 1,
220            _ => break,
221        }
222    }
223    while suffix > 0
224        && suffix < old_len
225        && (old_rope.byte(old_len - suffix) & 0b1100_0000) == 0b1000_0000
226    {
227        suffix -= 1;
228    }
229
230    let start_byte = prefix;
231    let old_end_byte = old_len - suffix;
232    let new_end_byte = new_len - suffix;
233
234    crate::types::ContentEdit {
235        start_byte,
236        old_end_byte,
237        new_end_byte,
238        start_position: rope_byte_to_row_col(old_rope, start_byte),
239        old_end_position: rope_byte_to_row_col(old_rope, old_end_byte),
240        new_end_position: byte_to_row_col(new_bytes, new_end_byte),
241    }
242}
243
244#[inline]
245fn rope_byte_to_row_col(rope: &ropey::Rope, byte_idx: usize) -> (u32, u32) {
246    let byte_idx = byte_idx.min(rope.len_bytes());
247    let line = rope.byte_to_line(byte_idx);
248    let line_start = rope.line_to_byte(line);
249    (line as u32, (byte_idx - line_start) as u32)
250}
251
252/// Compute the byte position after inserting `text` starting at
253/// `start_byte` / `start_pos`. Returns `(end_byte, end_position)`.
254fn advance_by_text(text: &str, start_byte: usize, start_pos: (u32, u32)) -> (usize, (u32, u32)) {
255    let new_end_byte = start_byte + text.len();
256    let newlines = text.bytes().filter(|&b| b == b'\n').count();
257    let end_pos = if newlines == 0 {
258        (start_pos.0, start_pos.1 + text.len() as u32)
259    } else {
260        // Bytes after the last newline determine the trailing column.
261        let last_nl = text.rfind('\n').unwrap();
262        let tail_bytes = (text.len() - last_nl - 1) as u32;
263        (start_pos.0 + newlines as u32, tail_bytes)
264    };
265    (new_end_byte, end_pos)
266}
267
268/// Translate a single `hjkl_buffer::Edit` into one or more
269/// [`crate::types::ContentEdit`] records using the **pre-edit** buffer
270/// state for byte/position lookups. Block ops fan out to one entry per
271/// touched row (matches `edit_to_editops`).
272fn content_edits_from_buffer_edit(
273    buf: &hjkl_buffer::Buffer,
274    edit: &hjkl_buffer::Edit,
275) -> Vec<crate::types::ContentEdit> {
276    use hjkl_buffer::Edit as B;
277    use hjkl_buffer::Position;
278
279    let mut out: Vec<crate::types::ContentEdit> = Vec::new();
280
281    match edit {
282        B::InsertChar { at, ch } => {
283            let (start_byte, start_pos) = position_to_byte_coords(buf, *at);
284            let new_end_byte = start_byte + ch.len_utf8();
285            let new_end_pos = (start_pos.0, start_pos.1 + ch.len_utf8() as u32);
286            out.push(crate::types::ContentEdit {
287                start_byte,
288                old_end_byte: start_byte,
289                new_end_byte,
290                start_position: start_pos,
291                old_end_position: start_pos,
292                new_end_position: new_end_pos,
293            });
294        }
295        B::InsertStr { at, text } => {
296            let (start_byte, start_pos) = position_to_byte_coords(buf, *at);
297            let (new_end_byte, new_end_pos) = advance_by_text(text, start_byte, start_pos);
298            out.push(crate::types::ContentEdit {
299                start_byte,
300                old_end_byte: start_byte,
301                new_end_byte,
302                start_position: start_pos,
303                old_end_position: start_pos,
304                new_end_position: new_end_pos,
305            });
306        }
307        B::DeleteRange { start, end, kind } => {
308            let (start, end) = if start <= end {
309                (*start, *end)
310            } else {
311                (*end, *start)
312            };
313            match kind {
314                hjkl_buffer::MotionKind::Char => {
315                    let (start_byte, start_pos) = position_to_byte_coords(buf, start);
316                    let (old_end_byte, old_end_pos) = position_to_byte_coords(buf, end);
317                    out.push(crate::types::ContentEdit {
318                        start_byte,
319                        old_end_byte,
320                        new_end_byte: start_byte,
321                        start_position: start_pos,
322                        old_end_position: old_end_pos,
323                        new_end_position: start_pos,
324                    });
325                }
326                hjkl_buffer::MotionKind::Line => {
327                    // Linewise delete drops rows [start.row..=end.row]. Map
328                    // to a span from start of `start.row` through start of
329                    // (end.row + 1). The buffer's own `do_delete_range`
330                    // collapses to row `start.row` after dropping.
331                    let lo = start.row;
332                    let hi = end.row.min(buf.row_count().saturating_sub(1));
333                    let start_byte = buffer_byte_of_row(buf, lo);
334                    let next_row_byte = if hi + 1 < buf.row_count() {
335                        buffer_byte_of_row(buf, hi + 1)
336                    } else {
337                        // No row after; clamp to end-of-buffer byte.
338                        let last_row = buf.row_count().saturating_sub(1);
339                        buffer_byte_of_row(buf, buf.row_count())
340                            + hjkl_buffer::rope_line_bytes(&buf.rope(), last_row)
341                    };
342                    out.push(crate::types::ContentEdit {
343                        start_byte,
344                        old_end_byte: next_row_byte,
345                        new_end_byte: start_byte,
346                        start_position: (lo as u32, 0),
347                        old_end_position: ((hi + 1) as u32, 0),
348                        new_end_position: (lo as u32, 0),
349                    });
350                }
351                hjkl_buffer::MotionKind::Block => {
352                    // Block delete removes a rectangle of chars per row.
353                    // Fan out to one ContentEdit per row.
354                    let (left_col, right_col) = (start.col.min(end.col), start.col.max(end.col));
355                    for row in start.row..=end.row {
356                        let row_start_pos = Position::new(row, left_col);
357                        let row_end_pos = Position::new(row, right_col + 1);
358                        let (sb, sp) = position_to_byte_coords(buf, row_start_pos);
359                        let (eb, ep) = position_to_byte_coords(buf, row_end_pos);
360                        if eb <= sb {
361                            continue;
362                        }
363                        out.push(crate::types::ContentEdit {
364                            start_byte: sb,
365                            old_end_byte: eb,
366                            new_end_byte: sb,
367                            start_position: sp,
368                            old_end_position: ep,
369                            new_end_position: sp,
370                        });
371                    }
372                }
373            }
374        }
375        B::Replace { start, end, with } => {
376            let (start, end) = if start <= end {
377                (*start, *end)
378            } else {
379                (*end, *start)
380            };
381            let (start_byte, start_pos) = position_to_byte_coords(buf, start);
382            let (old_end_byte, old_end_pos) = position_to_byte_coords(buf, end);
383            let (new_end_byte, new_end_pos) = advance_by_text(with, start_byte, start_pos);
384            out.push(crate::types::ContentEdit {
385                start_byte,
386                old_end_byte,
387                new_end_byte,
388                start_position: start_pos,
389                old_end_position: old_end_pos,
390                new_end_position: new_end_pos,
391            });
392        }
393        B::JoinLines {
394            row,
395            count,
396            with_space,
397        } => {
398            // Joining `count` rows after `row` collapses the bytes
399            // between EOL of `row` and EOL of `row + count` into either
400            // an empty string (gJ) or a single space per join (J — but
401            // only when both sides are non-empty; we approximate with
402            // a single space for simplicity).
403            let row = (*row).min(buf.row_count().saturating_sub(1));
404            let last_join_row = (row + count).min(buf.row_count().saturating_sub(1));
405            let buf_rope = buf.rope();
406            let line = hjkl_buffer::rope_line_str(&buf_rope, row);
407            let row_eol_byte = buffer_byte_of_row(buf, row) + line.len();
408            let row_eol_col = line.len() as u32;
409            let next_row_after = last_join_row + 1;
410            let old_end_byte = if next_row_after < buf.row_count() {
411                buffer_byte_of_row(buf, next_row_after).saturating_sub(1)
412            } else {
413                let last_row = buf.row_count().saturating_sub(1);
414                buffer_byte_of_row(buf, buf.row_count())
415                    + hjkl_buffer::rope_line_bytes(&buf_rope, last_row)
416            };
417            let last_line = hjkl_buffer::rope_line_str(&buf_rope, last_join_row);
418            let old_end_pos = (last_join_row as u32, last_line.len() as u32);
419            let replacement_len = if *with_space { 1 } else { 0 };
420            let new_end_byte = row_eol_byte + replacement_len;
421            let new_end_pos = (row as u32, row_eol_col + replacement_len as u32);
422            out.push(crate::types::ContentEdit {
423                start_byte: row_eol_byte,
424                old_end_byte,
425                new_end_byte,
426                start_position: (row as u32, row_eol_col),
427                old_end_position: old_end_pos,
428                new_end_position: new_end_pos,
429            });
430        }
431        B::SplitLines {
432            row,
433            cols,
434            inserted_space,
435        } => {
436            // Splits insert "\n" (or "\n " inverse) at each col on `row`.
437            // The buffer applies all splits left-to-right via the
438            // do_split_lines path; we emit one ContentEdit per col,
439            // each treated as an insert at that col on `row`. Note: the
440            // buffer state during emission is *pre-edit*, so all cols
441            // index into the same pre-edit row.
442            let row = (*row).min(buf.row_count().saturating_sub(1));
443            let split_rope = buf.rope();
444            let line = hjkl_buffer::rope_line_str(&split_rope, row);
445            let row_byte = buffer_byte_of_row(buf, row);
446            let insert = if *inserted_space { "\n " } else { "\n" };
447            for &c in cols {
448                let pos = Position::new(row, c);
449                let col_byte = pos.byte_offset(&line);
450                let start_byte = row_byte + col_byte;
451                let start_pos = (row as u32, col_byte as u32);
452                let (new_end_byte, new_end_pos) = advance_by_text(insert, start_byte, start_pos);
453                out.push(crate::types::ContentEdit {
454                    start_byte,
455                    old_end_byte: start_byte,
456                    new_end_byte,
457                    start_position: start_pos,
458                    old_end_position: start_pos,
459                    new_end_position: new_end_pos,
460                });
461            }
462        }
463        B::InsertBlock { at, chunks } => {
464            // One ContentEdit per chunk; each lands at `(at.row + i,
465            // at.col)` in the pre-edit buffer.
466            for (i, chunk) in chunks.iter().enumerate() {
467                let pos = Position::new(at.row + i, at.col);
468                let (start_byte, start_pos) = position_to_byte_coords(buf, pos);
469                let (new_end_byte, new_end_pos) = advance_by_text(chunk, start_byte, start_pos);
470                out.push(crate::types::ContentEdit {
471                    start_byte,
472                    old_end_byte: start_byte,
473                    new_end_byte,
474                    start_position: start_pos,
475                    old_end_position: start_pos,
476                    new_end_position: new_end_pos,
477                });
478            }
479        }
480        B::DeleteBlockChunks { at, widths } => {
481            for (i, w) in widths.iter().enumerate() {
482                let row = at.row + i;
483                let start_pos = Position::new(row, at.col);
484                let end_pos = Position::new(row, at.col + *w);
485                let (sb, sp) = position_to_byte_coords(buf, start_pos);
486                let (eb, ep) = position_to_byte_coords(buf, end_pos);
487                if eb <= sb {
488                    continue;
489                }
490                out.push(crate::types::ContentEdit {
491                    start_byte: sb,
492                    old_end_byte: eb,
493                    new_end_byte: sb,
494                    start_position: sp,
495                    old_end_position: ep,
496                    new_end_position: sp,
497                });
498            }
499        }
500    }
501
502    out
503}
504
505/// Where the cursor should land in the viewport after a `z`-family
506/// scroll (`zz` / `zt` / `zb`).
507#[derive(Debug, Clone, Copy, PartialEq, Eq)]
508pub enum CursorScrollTarget {
509    Center,
510    Top,
511    Bottom,
512}
513
514// ── Trait-surface cast helpers ────────────────────────────────────
515//
516// 0.0.42 (Patch C-δ.7): the helpers introduced in 0.0.41 were
517// promoted to [`crate::buf_helpers`] so `vim.rs` free fns can route
518// their reaches through the same primitives. Re-import via
519// `use` so the editor body keeps its terse call shape.
520
521use crate::buf_helpers::{
522    apply_buffer_edit, buf_cursor_pos, buf_cursor_rc, buf_cursor_row, buf_line, buf_line_chars,
523    buf_row_count, buf_set_cursor_rc,
524};
525
526/// Return value from the engine's `try_goto_mark_*` methods. Tells the
527/// caller (app layer) whether a cross-buffer switch is required.
528///
529/// - `SameBuffer` — cursor moved (or mark was unset → no-op) within the
530///   same buffer; no buffer switch needed.
531/// - `CrossBuffer` — the mark lives in a different buffer. The app must
532///   switch to the slot whose `buffer_id` matches, then position the cursor
533///   at `(row, col)` using `Editor::jump_cursor`.
534/// - `Unset` — mark not set; no action needed.
535#[derive(Debug, Clone, PartialEq, Eq)]
536pub enum MarkJump {
537    SameBuffer,
538    CrossBuffer {
539        buffer_id: u64,
540        row: usize,
541        col: usize,
542    },
543    Unset,
544}
545
546pub struct Editor<
547    B: crate::types::Buffer = hjkl_buffer::Buffer,
548    H: crate::types::Host = crate::types::DefaultHost,
549> {
550    pub keybinding_mode: KeybindingMode,
551    /// The installed keyboard discipline's FSM state, type-erased (#265 G3).
552    ///
553    /// The engine never names the concrete type: it only projects a
554    /// [`CoarseMode`] and asks for idle resets through
555    /// [`DisciplineState`]. The owning discipline crate downcasts through
556    /// [`Editor::discipline_mut`] to reach its own state (e.g. `hjkl-vim`'s
557    /// `VimState`).
558    ///
559    /// [`CoarseMode`]: crate::CoarseMode
560    /// [`DisciplineState`]: crate::DisciplineState
561    discipline: Box<dyn crate::DisciplineState>,
562    /// Secondary selections for multi-cursor editing (#63).
563    ///
564    /// The **primary** selection is not in here: its head stays `Buffer::cursor`
565    /// (so the ~130 places across the engine and the disciplines that move the
566    /// cursor keep working untouched) and its anchor lives in the discipline's
567    /// own state (vim's `visual_anchor`, helix's `anchor`). That asymmetry is
568    /// deliberate — see [`crate::selection_shift::Sel`].
569    ///
570    /// Each entry carries BOTH ends, so an operator can act on a *range* at every
571    /// cursor, not just the char under it. [`Editor::mutate_edit`] rewrites both
572    /// ends against the pre-edit geometry after every edit, and drops the whole
573    /// selection if either end becomes untrackable — never half of one.
574    ///
575    /// Char columns, matching `Buffer::cursor` and [`hjkl_buffer::Edit`] — NOT
576    /// the grapheme columns that `types::Pos` uses.
577    ///
578    /// Empty for a single-cursor editor, which is every editor today: vim drives
579    /// one caret, so this costs an `is_empty()` check per edit and nothing else.
580    extra_selections: Vec<crate::selection_shift::Sel>,
581    /// Read-only view overlay (git blame, …) layered over the input mode.
582    /// Discipline-agnostic engine substrate (#265 G3): hoisted out of
583    /// `VimState` because the core edit funnel (`mutate_edit`) and render/chrome
584    /// (`is_blame`/`view_mode`) read it, and any discipline can present an
585    /// overlay. Orthogonal to the input mode; auto-reset to `Normal` whenever
586    /// the input mode leaves Normal (see `drop_blame_if_left_normal`).
587    pub(crate) view: crate::ViewMode,
588    /// Position of the most recent buffer mutation, recorded by the core edit
589    /// funnel ([`Editor::mutate_edit`]). Surfaced via the `'.` / `` `. `` marks.
590    /// Discipline-agnostic substrate (#265 G3): the engine-core edit path writes
591    /// it and any discipline can offer "back to last edit", so it lives on
592    /// `Editor`, not `VimState`.
593    pub(crate) last_edit_pos: Option<(usize, usize)>,
594    /// Bounded ring of recent edit positions (newest at back), maintained by
595    /// `mutate_edit`. `g;` walks toward older, `g,` toward newer. Capped at
596    /// [`crate::types::CHANGE_LIST_MAX`]. Substrate — see [`Editor::last_edit_pos`].
597    pub(crate) change_list: Vec<(usize, usize)>,
598    /// Index into `change_list` while walking; `None` outside a walk (any new
599    /// edit clears it and trims forward entries). Substrate.
600    pub(crate) change_list_cursor: Option<usize>,
601    /// Undo history: each entry is `(joined_document, cursor)` before the
602    /// edit. Stored as `Arc<String>` so it shares the
603    /// Undo history: snapshots taken via `Buffer::rope()` — `ropey::Rope::clone`
604    /// is O(1) (Arc-clone of the B-tree root). Previously stored
605    /// `Arc<String>` from `content_joined()`, which on the rope storage
606    /// builds the entire document `String` via `rope.to_string()` — that
607    /// turned every `i` / `o` keystroke into a ~3 MB allocation on a
608    /// 1.86 M-line file.
609    // undo_stack, redo_stack, content_dirty, cached_content (as
610    // cached_editor_content), pending_fold_ops, change_log,
611    // pending_content_edits, pending_content_reset are now stored on
612    // Content (inside self.buffer) and accessed via Buffer accessor methods.
613    /// Last rendered viewport height (text rows only, no chrome). Written
614    /// by the draw path via [`set_viewport_height`] so the scroll helpers
615    /// can clamp the cursor to stay visible without plumbing the height
616    /// through every call.
617    pub(super) viewport_height: AtomicU16,
618    /// Pending LSP intent set by a normal-mode chord (e.g. `gd` for
619    /// goto-definition). The host app drains this each step and fires
620    /// the matching request against its own LSP client.
621    pub(super) pending_lsp: Option<LspIntent>,
622    /// Buffer storage.
623    ///
624    /// 0.1.0 (Patch C-δ): generic over `B: Buffer` per SPEC §"Editor
625    /// surface". Default `B = hjkl_buffer::Buffer`. The vim FSM body
626    /// and `Editor::mutate_edit` are concrete on `hjkl_buffer::Buffer`
627    /// for 0.1.0 — see `crate::buf_helpers::apply_buffer_edit`.
628    pub(super) buffer: B,
629    /// Engine-native style intern table. Opaque `Span::style` ids index
630    /// into this table; the render path resolves ids back to
631    /// [`crate::types::Style`]. Ratatui hosts convert at the boundary via
632    /// `hjkl_engine_tui::style_to_ratatui`. Always present — no cfg-mutex.
633    pub(super) style_table: Vec<crate::types::Style>,
634    /// Vim-style register bank — `"`, `"0`–`"9`, `"a`–`"z`. Sources
635    /// every `p` / `P` via the active selector (default unnamed).
636    /// Internal — read via [`Editor::registers`]; mutated by yank /
637    /// delete / paste FSM paths and by [`Editor::seed_yank`].
638    pub(crate) registers: std::sync::Arc<std::sync::Mutex<crate::registers::Registers>>,
639    /// Per-row syntax styling in engine-native form. Always present —
640    /// populated by [`Editor::install_syntax_spans`]. Ratatui hosts use
641    /// `hjkl_engine_tui::EditorRatatuiExt::install_ratatui_syntax_spans`.
642    pub styled_spans: Vec<Vec<(usize, usize, crate::types::Style)>>,
643    /// Per-editor settings tweakable via `:set`. Exposed by reference
644    /// so handlers (indent, search) read the live value rather than a
645    /// snapshot taken at startup. Read via [`Editor::settings`];
646    /// mutate via [`Editor::settings_mut`].
647    pub(crate) settings: Settings,
648    /// Global (uppercase) marks that carry a `buffer_id` so they can jump
649    /// across buffers. Keyed by `'A'`–`'Z'`; values are
650    /// `(buffer_id, row, col)`. Set by `m{A-Z}`, resolved by
651    /// `try_goto_mark_line` / `try_goto_mark_char`.
652    pub(crate) global_marks: std::collections::BTreeMap<char, (u64, usize, usize)>,
653
654    // ── Navigation history / viewport (discipline-agnostic, #265) ────────────
655    //
656    // Hoisted off `VimState` because they are not vim concepts: a jumplist is
657    // navigation history (VSCode's Go Back / Go Forward wants the same list),
658    // and the viewport flags are render state. A future helix/vscode
659    // discipline needs these without depending on hjkl-vim, so they live on
660    // the engine seam.
661    /// Positions pushed on "big" motions. Newest at the back — `Ctrl-o` pops
662    /// from here.
663    pub(crate) jump_back: Vec<(usize, usize)>,
664    /// Forward stack, refilled by `Ctrl-o` so `Ctrl-i` can return.
665    pub(crate) jump_fwd: Vec<(usize, usize)>,
666    /// When set, the viewport does not scroll-follow the cursor.
667    pub(crate) viewport_pinned: bool,
668    /// One-shot hint that the last scroll should be animated by the renderer.
669    pub(crate) scroll_anim_hint: bool,
670
671    // ── Search state (discipline-agnostic, #265) ─────────────────────────────
672    //
673    // Every editor has find. A vscode/helix discipline needs the pattern,
674    // direction and history without depending on hjkl-vim.
675    /// Live `/` or `?` prompt while the user is typing a pattern.
676    pub(crate) search_prompt: Option<crate::search::SearchPrompt>,
677    /// Last committed search pattern, for `n` / `N` (or Find Next).
678    pub(crate) last_search: Option<String>,
679    /// Direction of the last committed search.
680    pub(crate) last_search_forward: bool,
681    /// Search history, oldest first.
682    pub(crate) search_history: Vec<String>,
683    /// Cursor while walking search history with Up/Down.
684    pub(crate) search_history_cursor: Option<usize>,
685
686    // ── Input timing (discipline-agnostic) ───────────────────────────────────
687    //
688    // Any chorded FSM needs a timeout clock, not just vim.
689    /// Instant of the last input, when the host supplies a monotonic clock.
690    pub(crate) last_input_at: Option<std::time::Instant>,
691    /// Host-supplied elapsed time at the last input (no_std hosts).
692    pub(crate) last_input_host_at: Option<core::time::Duration>,
693
694    /// Last `:s` command, for `:&` / `:&&`. This is ex-command state owned by
695    /// the hjkl-ex seam, not vim FSM state.
696    pub(crate) last_substitute: Option<crate::substitute::SubstituteCmd>,
697
698    // ── Autopair / abbreviations (discipline-agnostic, #265) ─────────────────
699    //
700    // Neither is a vim concept. Autopair is an editor feature gated by
701    // `Settings::autopair` (VSCode has it too), and the abbreviation table is
702    // driven by hjkl-ex's `:abbreviate` / `:iabbrev` — hjkl-ex is in fact the
703    // only caller of the add/remove/clear accessors.
704    /// Close-brackets queued by autopair, as `(row, col, ch)`. Typing the
705    /// matching close char consumes the queued one instead of inserting.
706    pub(crate) pending_closes: Vec<(usize, usize, char)>,
707    /// Active abbreviation table (insert-mode + cmdline entries).
708    pub(crate) abbrevs: Vec<crate::abbrev::Abbrev>,
709
710    /// Whether the unnamed register's current content is linewise. This is
711    /// register metadata, not vim FSM state — any discipline that yanks and
712    /// pastes needs it (#265).
713    pub(crate) yank_linewise: bool,
714
715    /// The `buffer_id` this editor instance is currently attached to.
716    /// Updated by the host app on every `switch_to` / slot creation so
717    /// global-mark writes record the correct id without requiring the app
718    /// to pass the id on every keystroke.
719    pub(crate) current_buffer_id: u64,
720    // change_log moved to Content; accessed via self.buffer.take_change_log() etc.
721    /// Vim's "sticky column" (curswant). `None` before the first
722    /// motion — the next vertical motion bootstraps from the live
723    /// cursor column. Horizontal motions refresh this to the new
724    /// column; vertical motions read it back so bouncing through a
725    /// shorter row doesn't drag the cursor to col 0. Hoisted out of
726    /// `hjkl_buffer::Buffer` (and `VimState`) in 0.0.28 — Editor is
727    /// the single owner now. Buffer motion methods that need it
728    /// take a `&mut Option<usize>` parameter.
729    pub(crate) sticky_col: Option<usize>,
730    /// Host adapter for clipboard, cursor-shape, time, viewport, and
731    /// search-prompt / cancellation side-channels.
732    ///
733    /// 0.1.0 (Patch C-δ): generic over `H: Host` per SPEC §"Editor
734    /// surface". Default `H = DefaultHost`. The pre-0.1.0 `EngineHost`
735    /// dyn-shim is gone — every method now dispatches through `H`'s
736    /// `Host` trait surface directly.
737    pub(crate) host: H,
738    /// Last public mode the cursor-shape emitter saw. Drives
739    /// [`Editor::emit_cursor_shape_if_changed`] so `Host::emit_cursor_shape`
740    /// fires exactly once per mode transition without sprinkling the
741    /// call across every `vim.mode = ...` site.
742    pub(crate) last_emitted_mode: crate::CoarseMode,
743    /// Search FSM state (pattern + per-row match cache + wrapscan).
744    /// 0.0.35: relocated out of `hjkl_buffer::Buffer` per
745    /// `DESIGN_33_METHOD_CLASSIFICATION.md` step 1.
746    /// 0.0.37: the buffer-side bridge (`Buffer::search_pattern`) is
747    /// gone; `BufferView` now takes the active regex as a `&Regex`
748    /// parameter, sourced from `Editor::search_state().pattern`.
749    pub(crate) search_state: crate::search::SearchState,
750    /// Per-row syntax span overlay. Source of truth for the host's
751    /// renderer ([`hjkl_buffer::BufferView::spans`]). Populated by
752    /// [`Editor::install_syntax_spans`] (ratatui hosts use
753    /// `hjkl_engine_tui::EditorRatatuiExt::install_ratatui_syntax_spans`)
754    /// and, in due course, by `Host::syntax_highlights` once the engine
755    /// drives that path directly.
756    ///
757    /// 0.0.37: lifted out of `hjkl_buffer::Buffer` per step 3 of
758    /// `DESIGN_33_METHOD_CLASSIFICATION.md`. The buffer-side cache +
759    /// `Buffer::set_spans` / `Buffer::spans` accessors are gone.
760    pub(crate) buffer_spans: Vec<Vec<hjkl_buffer::Span>>,
761    // pending_content_edits and pending_content_reset moved to Content;
762    // accessed via self.buffer.take_pending_content_edits() etc.
763    /// Row range touched by the most recent `auto_indent_rows` call.
764    /// `(top_row, bot_row)` inclusive. Set by the engine after every
765    /// auto-indent operation; drained (and cleared) by the host via
766    /// [`Editor::take_last_indent_range`] so it can display a brief
767    /// visual flash over the reindented rows.
768    pub(crate) last_indent_range: Option<(usize, usize)>,
769}
770
771/// Vim-style options surfaced by `:set`. New fields land here as
772/// individual ex commands gain `:set` plumbing.
773#[derive(Debug, Clone)]
774pub struct Settings {
775    /// Spaces per shift step for `>>` / `<<` / `Ctrl-T` / `Ctrl-D`.
776    pub shiftwidth: usize,
777    /// Visual width of a `\t` character. Stored for future render
778    /// hookup; not yet consumed by the buffer renderer.
779    pub tabstop: usize,
780    /// When true, `/` / `?` patterns and `:s/.../.../` ignore case
781    /// without an explicit `i` flag.
782    pub ignore_case: bool,
783    /// When true *and* `ignore_case` is true, an uppercase letter in
784    /// the pattern flips that search back to case-sensitive. Matches
785    /// vim's `:set smartcase`. Default `false`.
786    pub smartcase: bool,
787    /// Wrap searches past buffer ends. Matches vim's `:set wrapscan`.
788    /// Default `true`.
789    pub wrapscan: bool,
790    /// Wrap column for `gq{motion}` text reflow. Vim's default is 79.
791    pub textwidth: usize,
792    /// When `true`, the Tab key in insert mode inserts `tabstop` spaces
793    /// instead of a literal `\t`. Matches vim's `:set expandtab`.
794    /// Default `false`.
795    pub expandtab: bool,
796    /// Soft tab stop in spaces. When `> 0`, Tab inserts spaces to the
797    /// next softtabstop boundary (when `expandtab`), and Backspace at the
798    /// end of a softtabstop-aligned space run deletes the entire run as
799    /// if it were one tab. `0` disables. Matches vim's `:set softtabstop`.
800    pub softtabstop: usize,
801    /// Soft-wrap mode the renderer + scroll math + `gj` / `gk` use.
802    /// Default is [`hjkl_buffer::Wrap::None`] — long lines extend
803    /// past the right edge and `top_col` clips the left side.
804    /// `:set wrap` flips to char-break wrap; `:set linebreak` flips
805    /// to word-break wrap; `:set nowrap` resets.
806    pub wrap: hjkl_buffer::Wrap,
807    /// When true, the engine drops every edit before it touches the
808    /// buffer — undo, dirty flag, and change log all stay clean.
809    /// Matches vim's `:set readonly` / `:set ro`. Default `false`.
810    pub readonly: bool,
811    /// When `false`, ALL buffer modifications are blocked, including entering
812    /// insert/replace mode. Matches vim's `:set nomodifiable` / `:set noma`.
813    /// Default `true`.
814    pub modifiable: bool,
815    /// When `true`, pressing Enter in insert mode copies the leading
816    /// whitespace of the current line onto the new line. Matches vim's
817    /// `:set autoindent`. Default `true` (vim parity).
818    pub autoindent: bool,
819    /// When `true`, bumps indent by one `shiftwidth` after a line ending
820    /// in `{` / `(` / `[`, and strips one indent unit when the user types
821    /// `}` / `)` / `]` on a whitespace-only line. See `compute_enter_indent`
822    /// in `vim.rs` for the tree-sitter plug-in seam. Default `true`.
823    pub smartindent: bool,
824    /// Cap on undo-stack length. Older entries are pruned past this
825    /// bound. `0` means unlimited. Matches vim's `:set undolevels`.
826    /// Default `1000`.
827    pub undo_levels: u32,
828    /// When `true`, cursor motions inside insert mode break the
829    /// current undo group (so a single `u` only reverses the run of
830    /// keystrokes that preceded the motion). Default `true`.
831    /// Currently a no-op — engine doesn't yet break the undo group
832    /// on insert-mode motions; field is wired through `:set
833    /// undobreak` for forward compatibility.
834    pub undo_break_on_motion: bool,
835    /// Vim-flavoured "what counts as a word" character class.
836    /// Comma-separated tokens: `@` = `is_alphabetic()`, `_` = literal
837    /// `_`, `48-57` = decimal char range, bare integer = single char
838    /// code, single ASCII punctuation = literal. Default
839    /// `"@,48-57,_,192-255"` matches vim.
840    pub iskeyword: String,
841    /// Multi-key sequence timeout (e.g. `gg`, `dd`). When the user
842    /// pauses longer than this between keys, any pending prefix is
843    /// abandoned and the next key starts a fresh sequence. Matches
844    /// vim's `:set timeoutlen` / `:set tm` (millis). Default 1000ms.
845    pub timeout_len: core::time::Duration,
846    /// When true, render absolute line numbers in the gutter. Matches
847    /// vim's `:set number` / `:set nu`. Default `true`.
848    pub number: bool,
849    /// When true, render line numbers as offsets from the cursor row.
850    /// Combined with `number`, the cursor row shows its absolute number
851    /// while other rows show the relative offset (vim's `nu+rnu` hybrid).
852    /// Matches vim's `:set relativenumber` / `:set rnu`. Default `false`.
853    pub relativenumber: bool,
854    /// Minimum gutter width in cells for the line-number column.
855    /// Width grows past this to fit the largest displayed number.
856    /// Matches vim's `:set numberwidth` / `:set nuw`. Default `4`.
857    /// Range 1..=20.
858    pub numberwidth: usize,
859    /// Highlight the row where the cursor sits. Matches vim's `:set cursorline`.
860    /// Default `false`.
861    pub cursorline: bool,
862    /// Highlight the column where the cursor sits. Matches vim's `:set cursorcolumn`.
863    /// Default `false`.
864    pub cursorcolumn: bool,
865    /// Sign-column display mode. Matches vim's `:set signcolumn`.
866    /// Default [`crate::types::SignColumnMode::Auto`].
867    pub signcolumn: crate::types::SignColumnMode,
868    /// Number of cells reserved for a fold-marker gutter.
869    /// Matches vim's `:set foldcolumn`. Default `0`.
870    pub foldcolumn: u32,
871    /// How folds are automatically generated. Default `Expr` (tree-sitter).
872    /// Alias `fdm`. Matches vim's `:set foldmethod`.
873    pub foldmethod: crate::types::FoldMethod,
874    /// Enable automatic folds. Default `true`. Alias `fen`.
875    /// Matches vim's `:set foldenable`.
876    pub foldenable: bool,
877    /// Level at which auto-folds start open. `99` = all open (default). Alias `fls`.
878    /// Matches vim's `:set foldlevelstart`.
879    pub foldlevelstart: u32,
880    /// Open/close markers for `foldmethod=marker`, comma-separated `open,close`.
881    /// Matches vim's `:set foldmarker` / `fmr`. Default `"{{{,}}}"`.
882    pub foldmarker: String,
883    /// Comma-separated 1-based column indices for vertical rulers.
884    /// Matches vim's `:set colorcolumn`. Default `""`.
885    pub colorcolumn: String,
886    /// Format options flags (subset of vim's `formatoptions`).
887    /// `r` — auto-continue line comments on `<Enter>` in insert mode.
888    /// `o` — auto-continue line comments on `o` / `O` in normal mode.
889    /// Default: both on (`"ro"`).
890    pub formatoptions: String,
891    /// Active filetype (language name) for the current buffer.
892    /// Used by comment-continuation and future language-aware features.
893    /// Matches vim's `:set filetype` / `:set ft`. Default `""` (plain text).
894    pub filetype: String,
895    /// Override comment-string for the current buffer.
896    ///
897    /// When non-empty, used by `toggle_comment_range` instead of the
898    /// per-filetype default from `hjkl_lang::comment::commentstring_for_lang`.
899    /// Follows vim's `:set commentstring=…` — use `%s` as the text placeholder
900    /// (e.g. `"// %s"`) for compatibility; the toggle strips/inserts only the
901    /// prefix/suffix portion (before/after `%s`).  An empty string means "use
902    /// the filetype default".  Default `""`.
903    pub commentstring: String,
904    /// Program run by `:make` (vim's `makeprg`). Its stdout+stderr are parsed
905    /// via the errorformat into the quickfix list. Default `"cargo check"`.
906    pub makeprg: String,
907    /// Comma-separated list of errorformat patterns used by `:cexpr` /
908    /// `:lgetexpr` etc. to parse text into quickfix entries. Follows vim's
909    /// `'errorformat'` / `'efm'`. Default: `"%f:%l:%c:%m,%f:%l:%m,%l:%c:%m"`.
910    pub errorformat: String,
911    /// When `true`, typing an opening bracket or quote automatically inserts
912    /// the matching close character and parks the cursor between them.
913    /// Matches vim's `set autopairs` (Neovim) / nvim-autopairs behaviour.
914    /// Default `true`.
915    pub autopair: bool,
916    /// When `true`, typing `>` to close an HTML/XML opening tag automatically
917    /// inserts `</tagname>` after the cursor. Only fires for filetypes in the
918    /// HTML/XML family (`html`, `xml`, `svg`, `jsx`, `tsx`, `vue`, `svelte`).
919    /// Matches common editor "autoclose tag" behaviour. Default: `true` for
920    /// those filetypes (the caller gates on filetype), `true` stored here so
921    /// `:set noautoclose-tag` can disable it globally.
922    pub autoclose_tag: bool,
923    /// Minimum context rows kept visible above/below the cursor when scrolling.
924    /// Capped at (height - 1) / 2 for tiny viewports. `0` = no margin.
925    /// Matches vim's `:set scrolloff` / `:set so`. Default `5`.
926    pub scrolloff: usize,
927    /// Minimum context columns kept visible left/right of the cursor (no-wrap
928    /// mode only). `0` = no margin (vim default). Matches `:set sidescrolloff`.
929    /// Default `0`.
930    pub sidescrolloff: usize,
931    /// Auto-reload a clean buffer when its file changes on disk. Matches vim's
932    /// `:set autoread`. Default `true`. Consumed by the host's `:checktime`.
933    pub autoreload: bool,
934    /// Enable vim-sneak style two-char digraph jump via `s` (forward) and
935    /// `S` (backward). When `true` (default), `s`/`S` no longer behave as
936    /// vim's built-in substitute-char / substitute-line; `;`/`,` smart-fall-
937    /// back to sneak-repeat when the last horizontal motion was a sneak.
938    /// Set `:set nomotion_sneak` to revert `s`/`S` to stock vim behavior.
939    /// Default `true` — **BREAKING** for users relying on `s` = substitute-char.
940    pub motion_sneak: bool,
941    /// Render invisible characters (tabs, trailing spaces, EOL markers).
942    /// Matches vim's `:set list` / `:set nolist`. Default `false`.
943    pub list: bool,
944    /// Show Nerd-Font filetype icons in the tabline. `:set tabline_icons` /
945    /// `:set notabline_icons`. Default `true`.
946    pub tabline_icons: bool,
947    /// Show inline git blame as end-of-line virtual text on the cursor line
948    /// (gitsigns-style). Default `true`. (#202)
949    pub blame_inline: bool,
950    /// Inline diagnostic ghost-text mode (Error-Lens style `// message` at the
951    /// end of the line). Default [`crate::types::DiagInlineMode::All`].
952    pub diagnostics_inline: crate::types::DiagInlineMode,
953    /// Characters used to represent invisibles when `list` is on.
954    /// Matches vim's `:set listchars` / `:set lcs`.
955    pub listchars: crate::types::ListChars,
956    /// Render thin vertical indent guides at every `shiftwidth`-aligned
957    /// column. hjkl-specific. Default `true`.
958    pub indent_guides: bool,
959    /// Character used to draw indent guides. Default `'│'`.
960    pub indent_guide_char: char,
961    /// Enable inline color-literal preview. hjkl-specific. Default `true`.
962    pub colorizer: bool,
963    /// Filetype allowlist for the colorizer. Default CSS/template languages.
964    pub colorizer_filetypes: Vec<String>,
965    /// Run hjkl-mangler formatter before each `:w` save. Default `false`.
966    pub format_on_save: bool,
967    /// Strip trailing whitespace before each `:w` save. Default `false`.
968    pub trim_trailing_whitespace: bool,
969    /// Enable helix-style rainbow bracket coloring. hjkl-specific. Default `true`.
970    pub rainbow_brackets: bool,
971    /// Milliseconds of inactivity before swap-file write. Default `4000`.
972    /// Matches Vim's `updatetime`; alias `ut`.
973    pub updatetime: u32,
974    /// Highlight matching bracket pair under the cursor. hjkl-specific. Default `true`.
975    /// `:set nomatchparen` / `:set mps` to toggle. Only the char-scan path
976    /// (C-style brackets) is active; tag-pair matching is pending #240.
977    pub matchparen: bool,
978    /// Smooth-scroll animation duration for page/recenter motions, ms.
979    /// `:set scroll_duration_ms`. Default `0` (instant — animation off).
980    pub scroll_duration_ms: u16,
981    /// When `true`, char-wise Visual selections are treated as
982    /// **half-open** (exclusive end): the cell at the cursor/head position
983    /// is NOT included in the selection. This matches VSCode / kakoune
984    /// bar-cursor semantics where the caret sits *between* characters.
985    /// Default `false` (vim inclusive). The vim oracle path must leave this
986    /// at `false`; set it programmatically for VSCode keybinding mode.
987    pub selection_exclusive: bool,
988    /// How coarsely a single `u` (or Ctrl+Z) step walks back through
989    /// changes made during an insert session.
990    ///
991    /// - `InsertSession` (default, vim parity): one undo step reverts the
992    ///   entire session from `i` to `<Esc>`. This is byte-identical to
993    ///   vim's behaviour and must never be changed for the vim path.
994    /// - `Word`: mid-session undo breaks are inserted at word boundaries
995    ///   (non-whitespace char following whitespace, or a newline). One
996    ///   step of `u` then reverts roughly one word of typing at a time —
997    ///   matching VSCode's "edit-chunked Ctrl+Z" experience.
998    ///
999    /// The vim oracle path **must** leave this at `InsertSession`.
1000    /// VSCode keybinding mode sets it to `Word` via
1001    /// `propagate_vscode_settings`. Other future FSMs may choose freely.
1002    pub undo_granularity: UndoGranularity,
1003}
1004
1005/// Controls the granularity of per-insert-session undo steps.
1006///
1007/// Discipline-agnostic: vim uses `InsertSession`, VSCode uses `Word`.
1008/// Future FSMs (emacs, kakoune, …) may adopt either or add new variants.
1009#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1010pub enum UndoGranularity {
1011    /// One `u` step reverts the entire insert session (vim default).
1012    #[default]
1013    InsertSession,
1014    /// Mid-session undo breaks at word boundaries (non-whitespace after
1015    /// whitespace, or newline). Matches VSCode's Ctrl+Z granularity.
1016    Word,
1017}
1018
1019impl Default for Settings {
1020    fn default() -> Self {
1021        Self {
1022            shiftwidth: 4,
1023            tabstop: 4,
1024            softtabstop: 4,
1025            ignore_case: true,
1026            smartcase: true,
1027            wrapscan: true,
1028            textwidth: 79,
1029            expandtab: true,
1030            wrap: hjkl_buffer::Wrap::None,
1031            readonly: false,
1032            modifiable: true,
1033            autoindent: true,
1034            smartindent: true,
1035            undo_levels: 1000,
1036            undo_break_on_motion: true,
1037            iskeyword: "@,48-57,_,192-255".to_string(),
1038            timeout_len: core::time::Duration::from_millis(1000),
1039            number: true,
1040            relativenumber: false,
1041            numberwidth: 4,
1042            cursorline: false,
1043            cursorcolumn: false,
1044            signcolumn: crate::types::SignColumnMode::Auto,
1045            foldcolumn: 0,
1046            foldmethod: crate::types::FoldMethod::Expr,
1047            foldenable: true,
1048            foldlevelstart: 99,
1049            foldmarker: "{{{,}}}".to_string(),
1050            colorcolumn: String::new(),
1051            formatoptions: "ro".to_string(),
1052            filetype: String::new(),
1053            commentstring: String::new(),
1054            makeprg: "cargo check".to_string(),
1055            errorformat: "%f:%l:%c:%m,%f:%l:%m,%l:%c:%m".to_string(),
1056            autopair: true,
1057            autoclose_tag: true,
1058            scrolloff: 5,
1059            sidescrolloff: 0,
1060            autoreload: true,
1061            motion_sneak: true,
1062            list: false,
1063            tabline_icons: true,
1064            blame_inline: true,
1065            diagnostics_inline: crate::types::DiagInlineMode::All,
1066            listchars: crate::types::ListChars::default(),
1067            indent_guides: true,
1068            indent_guide_char: '│',
1069            colorizer: true,
1070            colorizer_filetypes: vec![
1071                "css".to_string(),
1072                "scss".to_string(),
1073                "sass".to_string(),
1074                "less".to_string(),
1075                "html".to_string(),
1076                "vue".to_string(),
1077                "svelte".to_string(),
1078                "tailwindcss".to_string(),
1079                "toml".to_string(),
1080                "lua".to_string(),
1081                "vim".to_string(),
1082            ],
1083            format_on_save: true,
1084            trim_trailing_whitespace: false,
1085            rainbow_brackets: true,
1086            updatetime: 4000,
1087            matchparen: true,
1088            scroll_duration_ms: 0,
1089            selection_exclusive: false,
1090            undo_granularity: UndoGranularity::InsertSession,
1091        }
1092    }
1093}
1094
1095/// Translate a SPEC [`crate::types::Options`] into the engine's
1096/// internal [`Settings`] representation. Field-by-field map; the
1097/// shapes are isomorphic except for type widths
1098/// (`u32` vs `usize`, [`crate::types::WrapMode`] vs
1099/// [`hjkl_buffer::Wrap`]). 0.1.0 (Patch C-δ) collapses both into one
1100/// type once the `Editor<B, H>::new(buffer, host, options)` constructor
1101/// is the canonical entry point.
1102fn settings_from_options(o: &crate::types::Options) -> Settings {
1103    Settings {
1104        shiftwidth: o.shiftwidth as usize,
1105        tabstop: o.tabstop as usize,
1106        softtabstop: o.softtabstop as usize,
1107        ignore_case: o.ignorecase,
1108        smartcase: o.smartcase,
1109        wrapscan: o.wrapscan,
1110        textwidth: o.textwidth as usize,
1111        expandtab: o.expandtab,
1112        wrap: match o.wrap {
1113            crate::types::WrapMode::None => hjkl_buffer::Wrap::None,
1114            crate::types::WrapMode::Char => hjkl_buffer::Wrap::Char,
1115            crate::types::WrapMode::Word => hjkl_buffer::Wrap::Word,
1116        },
1117        readonly: o.readonly,
1118        modifiable: o.modifiable,
1119        autoindent: o.autoindent,
1120        smartindent: o.smartindent,
1121        undo_levels: o.undo_levels,
1122        undo_break_on_motion: o.undo_break_on_motion,
1123        iskeyword: o.iskeyword.clone(),
1124        timeout_len: o.timeout_len,
1125        number: o.number,
1126        relativenumber: o.relativenumber,
1127        numberwidth: o.numberwidth,
1128        cursorline: o.cursorline,
1129        cursorcolumn: o.cursorcolumn,
1130        signcolumn: o.signcolumn,
1131        foldcolumn: o.foldcolumn,
1132        foldmethod: o.foldmethod,
1133        foldenable: o.foldenable,
1134        foldlevelstart: o.foldlevelstart,
1135        foldmarker: o.foldmarker.clone(),
1136        colorcolumn: o.colorcolumn.clone(),
1137        formatoptions: o.formatoptions.clone(),
1138        filetype: o.filetype.clone(),
1139        commentstring: String::new(),
1140        makeprg: "cargo check".to_string(),
1141        errorformat: "%f:%l:%c:%m,%f:%l:%m,%l:%c:%m".to_string(),
1142        autopair: true,
1143        autoclose_tag: true,
1144        scrolloff: o.scrolloff,
1145        sidescrolloff: o.sidescrolloff,
1146        autoreload: o.autoreload,
1147        motion_sneak: o.motion_sneak,
1148        list: o.list,
1149        tabline_icons: true,
1150        blame_inline: true,
1151        diagnostics_inline: crate::types::DiagInlineMode::All,
1152        listchars: o.listchars.clone(),
1153        indent_guides: o.indent_guides,
1154        indent_guide_char: o.indent_guide_char,
1155        colorizer: o.colorizer,
1156        colorizer_filetypes: o.colorizer_filetypes.clone(),
1157        format_on_save: o.format_on_save,
1158        trim_trailing_whitespace: o.trim_trailing_whitespace,
1159        rainbow_brackets: o.rainbow_brackets,
1160        updatetime: o.updatetime,
1161        matchparen: o.matchparen,
1162        scroll_duration_ms: 0,
1163        // `selection_exclusive` is not part of `Options` — it is set
1164        // programmatically by the host (e.g. VSCode keybinding mode via
1165        // `propagate_vscode_settings`). Default to `false` (vim inclusive).
1166        selection_exclusive: false,
1167        // `undo_granularity` is not part of `Options` — set programmatically
1168        // by the host. Default: `InsertSession` (vim parity).
1169        undo_granularity: UndoGranularity::InsertSession,
1170    }
1171}
1172
1173/// Host-observable LSP requests triggered by editor bindings. The
1174/// hjkl-engine crate doesn't talk to an LSP itself — it just raises an
1175/// intent that the TUI layer picks up and routes to `sqls`.
1176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1177pub enum LspIntent {
1178    /// `gd` — textDocument/definition at the cursor.
1179    GotoDefinition,
1180}
1181
1182impl<H: crate::types::Host> Editor<hjkl_buffer::Buffer, H> {
1183    /// Build an [`Editor`] from a buffer, host adapter, and SPEC options.
1184    ///
1185    /// 0.1.0 (Patch C-δ): canonical, frozen constructor per SPEC §"Editor
1186    /// surface". Replaces the pre-0.1.0 `Editor::new(KeybindingMode)` /
1187    /// `with_host` / `with_options` triad — there is no shim.
1188    ///
1189    /// Consumers that don't need a custom host pass
1190    /// [`crate::types::DefaultHost::new()`]; consumers that don't need
1191    /// custom options pass [`crate::types::Options::default()`].
1192    pub fn new(buffer: hjkl_buffer::Buffer, host: H, options: crate::types::Options) -> Self {
1193        let settings = settings_from_options(&options);
1194        Self {
1195            keybinding_mode: KeybindingMode::Vim,
1196            // No discipline: the engine cannot name one. Callers that want vim
1197            // keys build through `hjkl_vim::vim_editor` (or call
1198            // `hjkl_vim::install_vim_discipline`), which fills this slot.
1199            discipline: Box::new(crate::NoDiscipline),
1200            extra_selections: Vec::new(),
1201            view: crate::ViewMode::default(),
1202            last_edit_pos: None,
1203            change_list: Vec::new(),
1204            change_list_cursor: None,
1205            viewport_height: AtomicU16::new(0),
1206            pending_lsp: None,
1207            buffer,
1208            style_table: Vec::new(),
1209            registers: std::sync::Arc::new(std::sync::Mutex::new(
1210                crate::registers::Registers::default(),
1211            )),
1212            styled_spans: Vec::new(),
1213            settings,
1214            global_marks: std::collections::BTreeMap::new(),
1215            jump_back: Vec::new(),
1216            jump_fwd: Vec::new(),
1217            viewport_pinned: false,
1218            scroll_anim_hint: false,
1219            search_prompt: None,
1220            last_search: None,
1221            last_search_forward: true,
1222            search_history: Vec::new(),
1223            search_history_cursor: None,
1224            last_input_at: None,
1225            last_input_host_at: None,
1226            last_substitute: None,
1227            pending_closes: Vec::new(),
1228            abbrevs: Vec::new(),
1229            yank_linewise: false,
1230            current_buffer_id: 0,
1231            sticky_col: None,
1232            host,
1233            last_emitted_mode: crate::CoarseMode::Normal,
1234            search_state: crate::search::SearchState::new(),
1235            buffer_spans: Vec::new(),
1236            last_indent_range: None,
1237        }
1238    }
1239}
1240
1241impl<B: crate::types::Buffer, H: crate::types::Host> Editor<B, H> {
1242    /// Borrow the buffer (typed `&B`). Host renders through this via
1243    /// `hjkl_buffer::BufferView` when `B = hjkl_buffer::Buffer`.
1244    pub fn buffer(&self) -> &B {
1245        &self.buffer
1246    }
1247
1248    /// Mutably borrow the buffer (typed `&mut B`).
1249    pub fn buffer_mut(&mut self) -> &mut B {
1250        &mut self.buffer
1251    }
1252
1253    /// Borrow the host adapter directly (typed `&H`).
1254    pub fn host(&self) -> &H {
1255        &self.host
1256    }
1257
1258    /// Mutably borrow the host adapter (typed `&mut H`).
1259    pub fn host_mut(&mut self) -> &mut H {
1260        &mut self.host
1261    }
1262}
1263
1264impl<H: crate::types::Host> Editor<hjkl_buffer::Buffer, H> {
1265    /// Update the active `iskeyword` spec for word motions
1266    /// (`w`/`b`/`e`/`ge` and engine-side `*`/`#` pickup). 0.0.28
1267    /// hoisted iskeyword storage out of `Buffer` — `Editor` is the
1268    /// single owner now. Equivalent to assigning
1269    /// `settings_mut().iskeyword` directly; the dedicated setter is
1270    /// retained for source-compatibility with 0.0.27 callers.
1271    pub fn set_iskeyword(&mut self, spec: impl Into<String>) {
1272        self.settings.iskeyword = spec.into();
1273    }
1274
1275    /// Emit `Host::emit_cursor_shape` if the public mode has changed
1276    /// since the last emit. Engine calls this at the end of every input
1277    /// step so mode transitions surface to the host without sprinkling
1278    /// the call across every `vim.mode = ...` site.
1279    pub fn emit_cursor_shape_if_changed(&mut self) {
1280        // Coarse, not vim: the engine emits render chrome for whatever
1281        // discipline is installed (#265).
1282        let mode = self.coarse_mode();
1283        if mode == self.last_emitted_mode {
1284            return;
1285        }
1286        let exclusive = self.settings.selection_exclusive;
1287        let shape = match mode {
1288            crate::CoarseMode::Insert => crate::types::CursorShape::Bar,
1289            // VSCode: exclusive-visual also uses a bar caret (caret between chars).
1290            crate::CoarseMode::Select if exclusive => crate::types::CursorShape::Bar,
1291            _ => crate::types::CursorShape::Block,
1292        };
1293        self.host.emit_cursor_shape(shape);
1294        self.last_emitted_mode = mode;
1295    }
1296
1297    /// Record a yank/cut payload. Forwards the text to
1298    /// [`crate::types::Host::write_clipboard`] so the platform-clipboard
1299    /// integration can store or transmit it.
1300    pub fn record_yank_to_host(&mut self, text: String) {
1301        self.host.write_clipboard(text);
1302    }
1303
1304    /// Vim's sticky column (curswant). `None` before the first motion;
1305    /// hosts shouldn't normally need to read this directly — it's
1306    /// surfaced for migration off `Buffer::sticky_col` and for
1307    /// snapshot tests.
1308    pub fn sticky_col(&self) -> Option<usize> {
1309        self.sticky_col
1310    }
1311
1312    /// Replace the sticky column. Hosts should rarely touch this —
1313    /// motion code maintains it through the standard horizontal /
1314    /// vertical motion paths.
1315    pub fn set_sticky_col(&mut self, col: Option<usize>) {
1316        self.sticky_col = col;
1317    }
1318
1319    /// Host hook: replace the cached syntax-derived block ranges that
1320    /// `:foldsyntax` consumes. the host calls this on every re-parse;
1321    /// the cost is just a `Vec` swap.
1322    /// Look up a named mark by character. Returns `(row, col)` if
1323    /// set; `None` otherwise. Both lowercase (`'a`–`'z`) and
1324    /// uppercase (`'A`–`'Z`) marks live in the same unified
1325    /// [`Editor::marks`] map as of 0.0.36.
1326    pub fn mark(&self, c: char) -> Option<(usize, usize)> {
1327        self.buffer.mark(c)
1328    }
1329
1330    /// Set the named mark `c` to `(row, col)`. Used by the FSM's
1331    /// `m{a-zA-Z}` keystroke and by [`Editor::restore_snapshot`].
1332    pub fn set_mark(&mut self, c: char, pos: (usize, usize)) {
1333        self.buffer.set_mark(c, pos);
1334    }
1335
1336    /// Remove the named mark `c` (no-op if unset).
1337    pub fn clear_mark(&mut self, c: char) {
1338        self.buffer.clear_mark(c);
1339    }
1340
1341    /// Look up an uppercase global mark by letter. Returns
1342    /// `(buffer_id, row, col)` if set; `None` otherwise.
1343    pub fn global_mark(&self, c: char) -> Option<(u64, usize, usize)> {
1344        self.global_marks.get(&c).copied()
1345    }
1346
1347    /// Set an uppercase global mark `c` to `(buffer_id, row, col)`.
1348    pub fn set_global_mark(&mut self, c: char, buffer_id: u64, pos: (usize, usize)) {
1349        self.global_marks.insert(c, (buffer_id, pos.0, pos.1));
1350    }
1351
1352    /// Return the `buffer_id` this editor is currently attached to.
1353    pub fn current_buffer_id(&self) -> u64 {
1354        self.current_buffer_id
1355    }
1356
1357    /// Update the `buffer_id` this editor is attached to. Called by the
1358    /// app on every `switch_to` so global-mark sets record the correct id.
1359    pub fn set_current_buffer_id(&mut self, id: u64) {
1360        self.current_buffer_id = id;
1361    }
1362
1363    /// Iterate all global marks (`'A'`–`'Z'`), yielding
1364    /// `(mark_char, buffer_id, row, col)`.
1365    pub fn global_marks_iter(&self) -> impl Iterator<Item = (char, u64, usize, usize)> + '_ {
1366        self.global_marks
1367            .iter()
1368            .map(|(c, &(bid, r, col))| (*c, bid, r, col))
1369    }
1370
1371    /// Look up a buffer-local lowercase mark (`'a`–`'z`). Kept as a
1372    /// thin wrapper over [`Editor::mark`] for source compatibility
1373    /// with pre-0.0.36 callers; new code should call
1374    /// [`Editor::mark`] directly.
1375    #[deprecated(
1376        since = "0.0.36",
1377        note = "use Editor::mark — lowercase + uppercase marks now live in a single map"
1378    )]
1379    pub fn buffer_mark(&self, c: char) -> Option<(usize, usize)> {
1380        self.mark(c)
1381    }
1382
1383    /// Discard the most recent undo entry. Used by ex commands that
1384    /// pre-emptively pushed an undo state (`:s`, `:r`) but ended up
1385    /// matching nothing — popping prevents a no-op undo step from
1386    /// polluting the user's history.
1387    ///
1388    /// Returns `true` if an entry was discarded.
1389    pub fn pop_last_undo(&mut self) -> bool {
1390        self.buffer.pop_undo_entry().is_some()
1391    }
1392
1393    /// Read all named marks set this session — both lowercase
1394    /// (`'a`–`'z`) and uppercase (`'A`–`'Z`). Iteration is
1395    /// deterministic (BTreeMap-ordered) so snapshot / `:marks`
1396    /// output is stable.
1397    pub fn marks(&self) -> impl Iterator<Item = (char, (usize, usize))> {
1398        self.buffer.marks_cloned().into_iter()
1399    }
1400
1401    /// Read all buffer-local lowercase marks. Kept for source
1402    /// compatibility with pre-0.0.36 callers (e.g. `:marks` ex
1403    /// command); new code should use [`Editor::marks`] which
1404    /// iterates the unified map.
1405    #[deprecated(
1406        since = "0.0.36",
1407        note = "use Editor::marks — lowercase + uppercase marks now live in a single map"
1408    )]
1409    pub fn buffer_marks(&self) -> impl Iterator<Item = (char, (usize, usize))> {
1410        self.buffer
1411            .marks_cloned()
1412            .into_iter()
1413            .filter(|(c, _)| c.is_ascii_lowercase())
1414    }
1415
1416    /// Position of the last edit (where `.` would replay). `None` if
1417    /// no edit has happened yet in this session.
1418    pub fn last_edit_pos(&self) -> Option<(usize, usize)> {
1419        self.last_edit_pos
1420    }
1421
1422    /// Read-only view of the file-marks table — uppercase / "file"
1423    /// marks (`'A`–`'Z`) the host has set this session. Returns an
1424    /// iterator of `(mark_char, (row, col))` pairs.
1425    ///
1426    /// Mutate via the FSM (`m{A-Z}` keystroke) or via
1427    /// [`Editor::restore_snapshot`].
1428    ///
1429    /// 0.0.36: file marks now live in the unified [`Editor::marks`]
1430    /// map; this accessor is kept for source compatibility and
1431    /// filters the unified map to uppercase entries.
1432    pub fn file_marks(&self) -> impl Iterator<Item = (char, (usize, usize))> {
1433        self.buffer
1434            .marks_cloned()
1435            .into_iter()
1436            .filter(|(c, _)| c.is_ascii_uppercase())
1437    }
1438
1439    /// Read-only view of the cached syntax-derived block ranges that
1440    /// `:foldsyntax` consumes. Returns the slice the host last
1441    /// installed via [`Editor::set_syntax_fold_ranges`]; empty when
1442    /// no syntax integration is active.
1443    pub fn syntax_fold_ranges(&self) -> Vec<(usize, usize)> {
1444        self.buffer.syntax_fold_ranges_cloned()
1445    }
1446
1447    pub fn set_syntax_fold_ranges(&mut self, ranges: Vec<(usize, usize)>) {
1448        self.buffer.set_syntax_fold_ranges(ranges);
1449    }
1450
1451    /// Live settings (read-only). `:set` mutates these via
1452    /// [`Editor::settings_mut`].
1453    pub fn settings(&self) -> &Settings {
1454        &self.settings
1455    }
1456
1457    /// Live settings (mutable). `:set` flows through here to mutate
1458    /// shiftwidth / tabstop / textwidth / ignore_case / wrap. Hosts
1459    /// configuring at startup typically construct a [`Settings`]
1460    /// snapshot and overwrite via `*editor.settings_mut() = …`.
1461    pub fn settings_mut(&mut self) -> &mut Settings {
1462        &mut self.settings
1463    }
1464
1465    /// Set the active filetype (language name) for the current buffer.
1466    /// Used by comment-continuation and future language-aware features.
1467    /// Equivalent to `:set filetype=<lang>`. Pass `""` to clear.
1468    pub fn set_filetype(&mut self, lang: &str) {
1469        self.settings.filetype = lang.to_string();
1470    }
1471
1472    /// Returns `true` when `:set readonly` is active. Convenience
1473    /// accessor for hosts that cannot import the internal [`Settings`]
1474    /// type. Phase 5 binary uses this to gate `:w` writes.
1475    pub fn is_readonly(&self) -> bool {
1476        self.settings.readonly
1477    }
1478
1479    /// Returns `true` when the buffer is modifiable (default). When `false`
1480    /// (`:set nomodifiable`), ALL edits and insert-mode entry are blocked.
1481    pub fn is_modifiable(&self) -> bool {
1482        self.settings.modifiable
1483    }
1484
1485    /// Borrow the engine search state. Hosts inspecting the
1486    /// committed `/` / `?` pattern (e.g. for status-line display) or
1487    /// feeding the active regex into `BufferView::search_pattern`
1488    /// read it from here.
1489    pub fn search_state(&self) -> &crate::search::SearchState {
1490        &self.search_state
1491    }
1492
1493    /// Mutable engine search state. Hosts driving search
1494    /// programmatically (test fixtures, scripted demos) write the
1495    /// pattern through here.
1496    pub fn search_state_mut(&mut self) -> &mut crate::search::SearchState {
1497        &mut self.search_state
1498    }
1499
1500    /// Install `pattern` as the active search regex on the engine
1501    /// state and clear the cached row matches. Pass `None` to clear.
1502    /// 0.0.37: dropped the buffer-side mirror that 0.0.35 introduced
1503    /// — `BufferView` now takes the regex through its `search_pattern`
1504    /// field per step 3 of `DESIGN_33_METHOD_CLASSIFICATION.md`.
1505    pub fn set_search_pattern(&mut self, pattern: Option<regex::Regex>) {
1506        self.search_state.set_pattern(pattern);
1507    }
1508
1509    /// Drive `n` (or the `/` commit equivalent) — advance the cursor
1510    /// to the next match of `search_state.pattern` from the cursor's
1511    /// current position. Returns `true` when a match was found.
1512    /// `skip_current = true` excludes a match the cursor sits on.
1513    /// Opens any fold hiding the match row (vim-correct: search reveals folds).
1514    pub fn search_advance_forward(&mut self, skip_current: bool) -> bool {
1515        let found =
1516            crate::search::search_forward(&mut self.buffer, &mut self.search_state, skip_current);
1517        if found {
1518            let row = crate::types::Cursor::cursor(&self.buffer).line as usize;
1519            self.buffer.reveal_row(row);
1520        }
1521        found
1522    }
1523
1524    /// Drive `N` — symmetric counterpart of [`Editor::search_advance_forward`].
1525    /// Opens any fold hiding the match row (vim-correct: search reveals folds).
1526    pub fn search_advance_backward(&mut self, skip_current: bool) -> bool {
1527        let found =
1528            crate::search::search_backward(&mut self.buffer, &mut self.search_state, skip_current);
1529        if found {
1530            let row = crate::types::Cursor::cursor(&self.buffer).line as usize;
1531            self.buffer.reveal_row(row);
1532        }
1533        found
1534    }
1535
1536    /// Snapshot of the unnamed register (the default `p` / `P` source).
1537    pub fn yank(&self) -> String {
1538        self.registers.lock().unwrap().unnamed.text.clone()
1539    }
1540
1541    /// Borrow the full register bank — `"`, `"0`–`"9`, `"a`–`"z`.
1542    pub fn registers(&self) -> std::sync::MutexGuard<'_, crate::registers::Registers> {
1543        self.registers.lock().unwrap()
1544    }
1545
1546    /// Mutably borrow the full register bank. Returns a guard so callers
1547    /// can mutate in place. Signature changed from `&mut self` to `&self`
1548    /// because the interior mutability is now via `Arc<Mutex<>>`.
1549    pub fn registers_mut(&self) -> std::sync::MutexGuard<'_, crate::registers::Registers> {
1550        self.registers.lock().unwrap()
1551    }
1552
1553    /// Point this editor at a shared register bank. All editors in the
1554    /// app share one bank so yank/paste work cross-buffer without copying.
1555    pub fn set_registers_arc(
1556        &mut self,
1557        registers: std::sync::Arc<std::sync::Mutex<crate::registers::Registers>>,
1558    ) {
1559        self.registers = registers;
1560    }
1561
1562    /// Host hook: load the OS clipboard's contents into the `"+` / `"*`
1563    /// register slot. the host calls this before letting vim consume a
1564    /// paste so `"*p` / `"+p` reflect the live clipboard rather than a
1565    /// stale snapshot from the last yank.
1566    pub fn sync_clipboard_register(&mut self, text: String, linewise: bool) {
1567        self.registers.lock().unwrap().set_clipboard(text, linewise);
1568    }
1569
1570    /// Read-only view of the change list (positions of recent edits) plus
1571    /// the current walk cursor. Newest entry is at the back.
1572    pub fn change_list(&self) -> (&[(usize, usize)], Option<usize>) {
1573        (&self.change_list, self.change_list_cursor)
1574    }
1575
1576    /// Replace the unnamed register without touching any other slot.
1577    /// For host-driven imports (e.g. system clipboard); operator
1578    /// code uses [`record_yank`] / [`record_delete`].
1579    pub fn set_yank(&mut self, text: impl Into<String>) {
1580        let text = text.into();
1581        let linewise = self.yank_linewise;
1582        self.registers.lock().unwrap().unnamed = crate::registers::Slot { text, linewise };
1583    }
1584
1585    /// Record a yank into `"` and `"0`, plus the named target if the
1586    /// user prefixed `"reg`. Updates `vim.yank_linewise` for the
1587    /// paste path.
1588    pub fn record_yank(&mut self, text: String, linewise: bool, target: Option<char>) {
1589        self.yank_linewise = linewise;
1590        self.registers
1591            .lock()
1592            .unwrap()
1593            .record_yank(text, linewise, target);
1594    }
1595
1596    /// Direct write to a named register slot — bypasses the unnamed
1597    /// `"` and `"0` updates that `record_yank` does. Used by the
1598    /// macro recorder so finishing a `q{reg}` recording doesn't
1599    /// pollute the user's last yank.
1600    pub fn set_named_register_text(&mut self, reg: char, text: String) {
1601        let mut regs = self.registers.lock().unwrap();
1602        if let Some(slot) = match reg {
1603            'a'..='z' => Some(&mut regs.named[(reg as u8 - b'a') as usize]),
1604            'A'..='Z' => Some(&mut regs.named[(reg.to_ascii_lowercase() as u8 - b'a') as usize]),
1605            _ => None,
1606        } {
1607            slot.text = text;
1608            slot.linewise = false;
1609        }
1610    }
1611
1612    /// Record a delete / change into `"` and, by size, the `"1`–`"9`
1613    /// ring or the `"-` small-delete register. Honours the active
1614    /// named-register prefix.
1615    pub fn record_delete(&mut self, text: String, linewise: bool, target: Option<char>) {
1616        self.yank_linewise = linewise;
1617        self.registers
1618            .lock()
1619            .unwrap()
1620            .record_delete(text, linewise, target);
1621    }
1622
1623    /// Install styled syntax spans using the engine-native
1624    /// [`crate::types::Style`]. Always available — engine is ratatui-free.
1625    /// Ratatui hosts use
1626    /// `hjkl_engine_tui::EditorRatatuiExt::install_ratatui_syntax_spans`
1627    /// which converts at the boundary and delegates here.
1628    ///
1629    /// Renamed from `install_engine_syntax_spans` in 0.0.32 — at the
1630    /// 0.1.0 freeze the unprefixed name is the universally-available
1631    /// engine-native variant.
1632    pub fn install_syntax_spans(&mut self, spans: Vec<Vec<(usize, usize, crate::types::Style)>>) {
1633        // Note: do NOT pre-collect `line_byte_lens` here. `buf_line` clones
1634        // the row string under a content-mutex lock; pre-collecting for
1635        // every row turns a 10k-row file's install into 10k mutex-locked
1636        // String clones (visible as j/k cursor lag). The typical install
1637        // has spans on at most a few hundred rows (the parsed viewport
1638        // window); lazy lookup keeps the cost proportional to populated
1639        // rows, not file size.
1640        let mut by_row: Vec<Vec<hjkl_buffer::Span>> = Vec::with_capacity(spans.len());
1641        let mut engine_spans: Vec<Vec<(usize, usize, crate::types::Style)>> =
1642            Vec::with_capacity(spans.len());
1643        for (row, row_spans) in spans.iter().enumerate() {
1644            if row_spans.is_empty() {
1645                by_row.push(Vec::new());
1646                engine_spans.push(Vec::new());
1647                continue;
1648            }
1649            let line_len = buf_line(&self.buffer, row).map(|s| s.len()).unwrap_or(0);
1650            let mut translated = Vec::with_capacity(row_spans.len());
1651            let mut translated_e = Vec::with_capacity(row_spans.len());
1652            for (start, end, style) in row_spans {
1653                let end_clamped = (*end).min(line_len);
1654                if end_clamped <= *start {
1655                    continue;
1656                }
1657                let id = self.intern_style(*style);
1658                translated.push(hjkl_buffer::Span::new(*start, end_clamped, id));
1659                translated_e.push((*start, end_clamped, *style));
1660            }
1661            by_row.push(translated);
1662            engine_spans.push(translated_e);
1663        }
1664        self.buffer_spans = by_row;
1665        self.styled_spans = engine_spans;
1666    }
1667
1668    /// Patch only `rows` of the installed `buffer_spans` / `styled_spans`,
1669    /// leaving rows outside that range untouched. `spans` is indexed by
1670    /// row offset within `rows` — `spans[0]` is for `rows.start`,
1671    /// `spans[1]` for `rows.start + 1`, etc.
1672    ///
1673    /// Use this instead of [`Self::install_syntax_spans`] when a sync
1674    /// `query_viewport` produced spans for the visible region only.
1675    /// Walking the full `line_count` and re-installing every row on
1676    /// every j/k that nudges the viewport dominated the per-keystroke
1677    /// cost on large files; patching just the changed range keeps the
1678    /// cost proportional to viewport size, not file size.
1679    ///
1680    /// Ensures `buffer_spans` / `styled_spans` are sized to the buffer's
1681    /// current `line_count` (resizes if a row-count edit shifted them).
1682    pub fn patch_syntax_spans_range(
1683        &mut self,
1684        rows: std::ops::Range<usize>,
1685        spans: &[Vec<(usize, usize, crate::types::Style)>],
1686    ) {
1687        let line_count = buf_row_count(&self.buffer);
1688        if self.buffer_spans.len() != line_count {
1689            self.buffer_spans.resize_with(line_count, Vec::new);
1690        }
1691        if self.styled_spans.len() != line_count {
1692            self.styled_spans.resize_with(line_count, Vec::new);
1693        }
1694        for (i, row_spans) in spans.iter().enumerate() {
1695            let row = rows.start + i;
1696            if row >= line_count {
1697                break;
1698            }
1699            if row_spans.is_empty() {
1700                self.buffer_spans[row] = Vec::new();
1701                self.styled_spans[row] = Vec::new();
1702                continue;
1703            }
1704            let line_len = buf_line(&self.buffer, row).map(|s| s.len()).unwrap_or(0);
1705            let mut translated = Vec::with_capacity(row_spans.len());
1706            let mut translated_e = Vec::with_capacity(row_spans.len());
1707            for (start, end, style) in row_spans {
1708                let end_clamped = (*end).min(line_len);
1709                if end_clamped <= *start {
1710                    continue;
1711                }
1712                let id = self.intern_style(*style);
1713                translated.push(hjkl_buffer::Span::new(*start, end_clamped, id));
1714                translated_e.push((*start, end_clamped, *style));
1715            }
1716            self.buffer_spans[row] = translated;
1717            self.styled_spans[row] = translated_e;
1718        }
1719    }
1720
1721    /// Translate the cached `buffer_spans` / `styled_spans` row indices
1722    /// in-place to track a batch of [`crate::types::ContentEdit`]s without
1723    /// blanking the cache.
1724    ///
1725    /// Why: spans are installed by the async syntax worker, which can lag
1726    /// the buffer by one or more frames after an edit. If the edit changes
1727    /// the row count and we keep the old span rows in place, the renderer
1728    /// paints last-frame's spans at the wrong line — visibly garbled colours.
1729    /// The historical fix was to blank `buffer_spans` whenever a row-count
1730    /// change came through, but that produces a white flash on every Enter
1731    /// or backspace-at-BOL.
1732    ///
1733    /// What this does instead: for each edit, insert empty span rows where
1734    /// the edit grew the buffer and drain rows where it shrank, so the
1735    /// surviving rows still index the right line. Spans on the edited row
1736    /// itself stay (they'll show stale colours for that one row until the
1737    /// worker delivers a fresh parse, which is invisible compared to the
1738    /// blank flash).
1739    ///
1740    /// Edits are applied in order — each edit's `(row, col)` positions are
1741    /// taken to be relative to the post-state of the prior edits in the
1742    /// batch (matching the order the engine emitted them).
1743    pub fn shift_syntax_spans_for_edits(&mut self, edits: &[crate::types::ContentEdit]) {
1744        for edit in edits {
1745            let oer = edit.old_end_position.0 as usize;
1746            let ner = edit.new_end_position.0 as usize;
1747            if ner == oer {
1748                continue;
1749            }
1750            let start_row = edit.start_position.0 as usize;
1751            let start_col = edit.start_position.1 as usize;
1752            // Insert/drain index depends on whether the edit starts at
1753            // the BEGINNING of `start_row` or somewhere INSIDE it.
1754            //   col == 0 → edit is at the very start of `start_row`; new
1755            //              rows go BEFORE row `start_row`, so the affected
1756            //              indices begin AT `start_row`.
1757            //   col > 0 → edit is inside `start_row`; new rows go AFTER
1758            //              `start_row`, so affected indices begin at
1759            //              `start_row + 1`.
1760            //
1761            // Pre-fix this always used `oer + 1` (the col-> 0 branch),
1762            // which left row `start_row`'s spans at its old index while
1763            // the file's row `start_row` was now the freshly-pasted
1764            // content — visible as wrong-row colour mappings after
1765            // `ggP` / `P` / any insert at column 0.
1766            let affected_idx = if start_col == 0 {
1767                start_row
1768            } else {
1769                start_row + 1
1770            };
1771            if ner > oer {
1772                let n = ner - oer;
1773                // O(len + n) via splice; the prior per-row `insert(idx, ...)`
1774                // loop was O(n × (len - idx)), which on a 60k-row paste at
1775                // the BOL became ~1.8 G memmove ops (87 % of paste CPU per
1776                // samply). Splice memmove-shifts once, then fills.
1777                let idx = affected_idx.min(self.buffer_spans.len());
1778                self.buffer_spans
1779                    .splice(idx..idx, std::iter::repeat_with(Vec::new).take(n));
1780                let idx_s = affected_idx.min(self.styled_spans.len());
1781                self.styled_spans
1782                    .splice(idx_s..idx_s, std::iter::repeat_with(Vec::new).take(n));
1783            } else {
1784                let n = oer - ner;
1785                let len_b = self.buffer_spans.len();
1786                let start_b = affected_idx.min(len_b);
1787                let end_b = (start_b + n).min(len_b);
1788                if end_b > start_b {
1789                    self.buffer_spans.drain(start_b..end_b);
1790                }
1791                let len_s = self.styled_spans.len();
1792                let start_s = affected_idx.min(len_s);
1793                let end_s = (start_s + n).min(len_s);
1794                if end_s > start_s {
1795                    self.styled_spans.drain(start_s..end_s);
1796                }
1797            }
1798        }
1799    }
1800
1801    /// Read-only view of the style table in engine-native form —
1802    /// id `i` → `style_table[i]`. Always available, no cfg gate.
1803    ///
1804    /// Ratatui hosts that need a `ratatui::style::Style` slice should
1805    /// use `hjkl_engine_tui::EditorRatatuiExt::ratatui_style_table` or
1806    /// convert individual entries via `hjkl_engine_tui::style_to_ratatui`.
1807    pub fn style_table(&self) -> &[crate::types::Style] {
1808        &self.style_table
1809    }
1810
1811    /// Per-row syntax span overlay, one `Vec<Span>` per buffer row.
1812    /// Hosts feed this slice into [`hjkl_buffer::BufferView::spans`]
1813    /// per draw frame.
1814    ///
1815    /// 0.0.37: replaces `editor.buffer().spans()` per step 3 of
1816    /// `DESIGN_33_METHOD_CLASSIFICATION.md`. The buffer no longer
1817    /// caches spans; they live on the engine and route through the
1818    /// `Host::syntax_highlights` pipeline.
1819    pub fn buffer_spans(&self) -> &[Vec<hjkl_buffer::Span>] {
1820        &self.buffer_spans
1821    }
1822
1823    /// Intern a SPEC [`crate::types::Style`] and return its opaque id.
1824    /// Engine-native — the unified `style_table` is always engine-native.
1825    /// Linear-scan dedup — the table grows only as new tree-sitter token
1826    /// kinds appear, so it stays tiny. Ratatui callers use
1827    /// `hjkl_engine_tui::EditorRatatuiExt::intern_ratatui_style` which
1828    /// converts at the boundary and delegates here.
1829    ///
1830    /// Renamed from `intern_engine_style` in 0.0.32 — at 0.1.0 freeze
1831    /// the unprefixed name is the universally-available engine-native
1832    /// variant.
1833    pub fn intern_style(&mut self, style: crate::types::Style) -> u32 {
1834        if let Some(idx) = self.style_table.iter().position(|s| *s == style) {
1835            return idx as u32;
1836        }
1837        self.style_table.push(style);
1838        (self.style_table.len() - 1) as u32
1839    }
1840
1841    /// Look up an interned style by id and return it as a SPEC
1842    /// [`crate::types::Style`]. Returns `None` for ids past the end
1843    /// of the table.
1844    pub fn engine_style_at(&self, id: u32) -> Option<crate::types::Style> {
1845        self.style_table.get(id as usize).copied()
1846    }
1847
1848    /// Historical reverse-sync hook from when the textarea mirrored
1849    /// the buffer. Now that Buffer is the cursor authority this is a
1850    /// no-op; call sites can remain in place during the migration.
1851    pub fn push_buffer_cursor_to_textarea(&mut self) {}
1852
1853    /// Force the host viewport's top row without touching the
1854    /// cursor. Used by tests that simulate a scroll without the
1855    /// SCROLLOFF cursor adjustment that `scroll_down` / `scroll_up`
1856    /// apply.
1857    ///
1858    /// 0.0.34 (Patch C-δ.1): writes through `Host::viewport_mut`
1859    /// instead of the (now-deleted) `Buffer::viewport_mut`.
1860    pub fn set_viewport_top(&mut self, row: usize) {
1861        let last = buf_row_count(&self.buffer).saturating_sub(1);
1862        let target = row.min(last);
1863        self.host.viewport_mut().top_row = target;
1864    }
1865
1866    /// Set the cursor to `(row, col)`, clamped to the buffer's
1867    /// content. Hosts use this for goto-line, jump-to-mark, and
1868    /// programmatic cursor placement.
1869    ///
1870    /// Resets `sticky_col` (curswant) to `col` — every explicit jump
1871    /// (goto-line, jump-to-mark, search hit, click, `]d`) follows vim
1872    /// semantics. Only `j`/`k`/`+`/`-` READ `sticky_col`; everything
1873    /// else resets it to the column where the cursor actually landed.
1874    pub fn jump_cursor(&mut self, row: usize, col: usize) {
1875        buf_set_cursor_rc(&mut self.buffer, row, col);
1876        self.sticky_col = Some(col);
1877    }
1878
1879    /// Set the cursor to `(row, col)` without modifying `sticky_col`.
1880    ///
1881    /// Use this for host-side state restores (viewport sync, snapshot
1882    /// replay) where the cursor was already at this position semantically
1883    /// and the host's sticky tracking should remain authoritative.
1884    ///
1885    /// For user-facing jumps (goto-line, search hit, picker `<CR>`, `]d`,
1886    /// click), use [`Editor::jump_cursor`] which DOES reset `sticky_col`
1887    /// per vim curswant semantics.
1888    pub fn set_cursor_quiet(&mut self, row: usize, col: usize) {
1889        buf_set_cursor_rc(&mut self.buffer, row, col);
1890    }
1891
1892    /// `(row, col)` cursor read sourced from the migration buffer.
1893    /// Equivalent to `self.textarea.cursor()` when the two are in
1894    /// sync — which is the steady state during Phase 7f because
1895    /// every step opens with `sync_buffer_content_from_textarea` and
1896    /// every ported motion pushes the result back. Prefer this over
1897    /// `self.textarea.cursor()` so call sites keep working unchanged
1898    /// once the textarea field is ripped.
1899    pub fn cursor(&self) -> (usize, usize) {
1900        buf_cursor_rc(&self.buffer)
1901    }
1902
1903    /// The character under the cursor, or `None` at/after end of line (or on
1904    /// an empty line). Used by callers that need vim's on-blank distinctions
1905    /// (e.g. `cw` only acts like `ce` when the cursor is on a non-blank).
1906    pub fn char_at_cursor(&self) -> Option<char> {
1907        let (row, col) = self.cursor();
1908        crate::buf_helpers::buf_line(&self.buffer, row).and_then(|l| l.chars().nth(col))
1909    }
1910
1911    /// Drain any pending LSP intent raised by the last key. Returns
1912    /// `None` when no intent is armed.
1913    pub fn take_lsp_intent(&mut self) -> Option<LspIntent> {
1914        self.pending_lsp.take()
1915    }
1916
1917    /// Drain every [`crate::types::FoldOp`] raised since the last
1918    /// call. Hosts that mirror the engine's fold storage (or that
1919    /// project folds onto a separate fold tree, LSP folding ranges,
1920    /// …) drain this each step and dispatch as their own
1921    /// [`crate::types::Host::Intent`] requires.
1922    ///
1923    /// The engine has already applied every op locally against the
1924    /// in-tree [`hjkl_buffer::Buffer`] fold storage via
1925    /// [`crate::buffer_impl::BufferFoldProviderMut`], so hosts that
1926    /// don't track folds independently can ignore the queue
1927    /// (or simply never call this drain).
1928    ///
1929    /// Introduced in 0.0.38 (Patch C-δ.4).
1930    pub fn take_fold_ops(&mut self) -> Vec<crate::types::FoldOp> {
1931        self.buffer.take_fold_ops()
1932    }
1933
1934    /// Dispatch a [`crate::types::FoldOp`] through the canonical fold
1935    /// surface: queue it for host observation (drained by
1936    /// [`Editor::take_fold_ops`]) and apply it locally against the
1937    /// in-tree buffer fold storage via
1938    /// [`crate::buffer_impl::BufferFoldProviderMut`]. Engine call sites
1939    /// (vim FSM `z…` chords, `:fold*` Ex commands, edit-pipeline
1940    /// invalidation) route every fold mutation through this method.
1941    ///
1942    /// Introduced in 0.0.38 (Patch C-δ.4).
1943    pub fn apply_fold_op(&mut self, op: crate::types::FoldOp) {
1944        use crate::types::FoldProvider;
1945        self.buffer.push_fold_op(op);
1946        let mut provider = crate::buffer_impl::BufferFoldProviderMut::new(&mut self.buffer);
1947        provider.apply(op);
1948        // BUG 2 fix: after a close/toggle-that-closes, the cursor may sit on a
1949        // hidden row (inside the fold body). Vim snaps the cursor to the fold's
1950        // first line (start_row). Do it here so every call site — keyboard `za`/
1951        // `zc` AND the gutter-click path — converges on the same behaviour.
1952        let cursor_row = buf_cursor_row(&self.buffer);
1953        if self.buffer.is_row_hidden(cursor_row)
1954            && let Some(fold) = self.buffer.fold_at_row(cursor_row)
1955        {
1956            let snap_row = fold.start_row;
1957            buf_set_cursor_rc(&mut self.buffer, snap_row, 0);
1958            self.sticky_col = Some(0);
1959        }
1960    }
1961
1962    /// Refresh the host viewport's height from the cached
1963    /// `viewport_height_value()`. Called from the per-step
1964    /// boilerplate; was the textarea → buffer mirror before Phase 7f
1965    /// put Buffer in charge. 0.0.28 hoisted sticky_col out of
1966    /// `Buffer`. 0.0.34 (Patch C-δ.1) routes the height write through
1967    /// `Host::viewport_mut`.
1968    pub fn sync_buffer_from_textarea(&mut self) {
1969        let height = self.viewport_height_value();
1970        self.host.viewport_mut().height = height;
1971    }
1972
1973    /// Was the full textarea → buffer content sync. Buffer is the
1974    /// content authority now; this remains as a no-op so the per-step
1975    /// call sites don't have to be ripped in the same patch.
1976    pub fn sync_buffer_content_from_textarea(&mut self) {
1977        self.sync_buffer_from_textarea();
1978    }
1979
1980    /// Push a `(row, col)` onto the back-jumplist so `Ctrl-o` returns
1981    /// to it later. Used by host-driven jumps (e.g. `gd`) that move
1982    /// the cursor without going through the vim engine's motion
1983    /// machinery, where push_jump fires automatically.
1984    pub fn record_jump(&mut self, pos: (usize, usize)) {
1985        const JUMPLIST_MAX: usize = 100;
1986        self.jump_back.push(pos);
1987        if self.jump_back.len() > JUMPLIST_MAX {
1988            self.jump_back.remove(0);
1989        }
1990        self.jump_fwd.clear();
1991    }
1992
1993    /// Host apps call this each draw with the current text area height so
1994    /// scroll helpers can clamp the cursor without recomputing layout.
1995    pub fn set_viewport_height(&self, height: u16) {
1996        self.viewport_height.store(height, Ordering::Relaxed);
1997    }
1998
1999    /// Last height published by `set_viewport_height` (in rows).
2000    pub fn viewport_height_value(&self) -> u16 {
2001        self.viewport_height.load(Ordering::Relaxed)
2002    }
2003
2004    /// Apply `edit` against the buffer and return the inverse so the
2005    /// host can push it onto an undo stack. Side effects: dirty
2006    /// flag, change-list ring, mark / jump-list shifts, change_log
2007    /// append, fold invalidation around the touched rows.
2008    ///
2009    /// The primary edit funnel — both FSM operators and ex commands
2010    /// route mutations through here so the side effects fire
2011    /// uniformly.
2012    pub fn mutate_edit(&mut self, edit: hjkl_buffer::Edit) -> hjkl_buffer::Edit {
2013        // `nomodifiable` OR the BLAME view overlay short-circuits every
2014        // mutation funnel: no buffer change, no dirty flag, no undo entry,
2015        // no change-log emission. We swallow the requested `edit` and hand
2016        // back a self-inverse no-op (`InsertStr` of an empty string at the
2017        // current cursor) so callers that push the return value onto an undo
2018        // stack still get a structurally valid round trip.
2019        // Note: `readonly` no longer blocks edits here — it only gates `:w`.
2020        if !self.settings.modifiable || self.view == crate::ViewMode::Blame {
2021            let _ = edit;
2022            return hjkl_buffer::Edit::InsertStr {
2023                at: buf_cursor_pos(&self.buffer),
2024                text: String::new(),
2025            };
2026        }
2027        // Multi-cursor (#63): every edit cascades, so the secondary selections
2028        // have to be rewritten against the *pre-edit* geometry or they end up
2029        // pointing at the wrong text. This is the single edit funnel, so doing it
2030        // here covers every mutation in the engine by construction. BOTH ends move
2031        // together, and a selection the shift cannot track exactly is dropped
2032        // whole, never guessed and never half-tracked — see `selection_shift`.
2033        if !self.extra_selections.is_empty() {
2034            let edit_ref = &edit;
2035            // `JoinLines` geometry depends on how long each row was *before* the
2036            // join, so the metrics have to be read here — after `apply_buffer_edit`
2037            // they describe the wrong buffer.
2038            let rows = buf_row_count(&self.buffer);
2039            let lens: Vec<usize> = (0..rows).map(|r| buf_line_chars(&self.buffer, r)).collect();
2040            self.extra_selections.retain_mut(|s| {
2041                match crate::selection_shift::shift_sel(
2042                    *s,
2043                    edit_ref,
2044                    |r| lens.get(r).copied().unwrap_or(0),
2045                    rows,
2046                ) {
2047                    Some(shifted) => {
2048                        *s = shifted;
2049                        true
2050                    }
2051                    None => false,
2052                }
2053            });
2054        }
2055        let pre_row = buf_cursor_row(&self.buffer);
2056        let pre_rows = buf_row_count(&self.buffer);
2057        // Capture the pre-edit cursor for the dot mark (`'.` / `` `. ``).
2058        // Vim's `:h '.` says "the position where the last change was made",
2059        // meaning the change-start, not the post-insert cursor. We snap it
2060        // here before `apply_buffer_edit` moves the cursor.
2061        let (pre_edit_row, pre_edit_col) = buf_cursor_rc(&self.buffer);
2062        // Map the underlying buffer edit to a SPEC EditOp for
2063        // change-log emission before consuming it. Coarse — see
2064        // change_log field doc on the struct.
2065        self.buffer.extend_change_log(edit_to_editops(&edit));
2066        // Compute ContentEdit fan-out from the pre-edit buffer state.
2067        // Done before `apply_buffer_edit` consumes `edit` so we can
2068        // inspect the operation's fields and the buffer's pre-edit row
2069        // bytes (needed for byte_of_row / col_byte conversion). Edits
2070        // are pushed onto pending_content_edits for host drain.
2071        let content_edits = content_edits_from_buffer_edit(&self.buffer, &edit);
2072        self.buffer.extend_pending_content_edits(content_edits);
2073        // 0.0.42 (Patch C-δ.7): the `apply_edit` reach is centralized
2074        // in [`crate::buf_helpers::apply_buffer_edit`] (option (c) of
2075        // the 0.0.42 plan — see that fn's doc comment). The free fn
2076        // takes `&mut hjkl_buffer::Buffer` so the editor body itself
2077        // no longer carries a `self.buffer.<inherent>` hop.
2078        let inverse = apply_buffer_edit(&mut self.buffer, edit);
2079        let (pos_row, pos_col) = buf_cursor_rc(&self.buffer);
2080        // Drop any folds the edit's range overlapped — vim opens the
2081        // surrounding fold automatically when you edit inside it. The
2082        // approximation here invalidates folds covering either the
2083        // pre-edit cursor row or the post-edit cursor row, which
2084        // catches the common single-line / multi-line edit shapes.
2085        let lo = pre_row.min(pos_row);
2086        let hi = pre_row.max(pos_row);
2087        self.apply_fold_op(crate::types::FoldOp::Invalidate {
2088            start_row: lo,
2089            end_row: hi,
2090        });
2091        // Dot mark records the PRE-edit position (change start), matching
2092        // vim's `:h '.` semantics. Previously this stored the post-edit
2093        // cursor, which diverged from nvim on `iX<Esc>j`.
2094        self.last_edit_pos = Some((pre_edit_row, pre_edit_col));
2095        // Append to the change-list ring (skip when the cursor sits on
2096        // the same cell as the last entry — back-to-back keystrokes on
2097        // one column shouldn't pollute the ring). A new edit while
2098        // walking the ring trims the forward half, vim style.
2099        let entry = (pos_row, pos_col);
2100        if self.change_list.last() != Some(&entry) {
2101            if let Some(idx) = self.change_list_cursor.take() {
2102                self.change_list.truncate(idx + 1);
2103            }
2104            self.change_list.push(entry);
2105            let len = self.change_list.len();
2106            if len > crate::types::CHANGE_LIST_MAX {
2107                self.change_list
2108                    .drain(0..len - crate::types::CHANGE_LIST_MAX);
2109            }
2110        }
2111        self.change_list_cursor = None;
2112        // Shift / drop marks + jump-list entries to track the row
2113        // delta the edit produced. Without this, every line-changing
2114        // edit silently invalidates `'a`-style positions.
2115        let post_rows = buf_row_count(&self.buffer);
2116        let delta = post_rows as isize - pre_rows as isize;
2117        if delta != 0 {
2118            self.shift_marks_after_edit(pre_row, delta);
2119        }
2120        self.push_buffer_content_to_textarea();
2121        self.mark_content_dirty();
2122        inverse
2123    }
2124
2125    /// Migrate user marks + jumplist entries when an edit at row
2126    /// `edit_start` changes the buffer's row count by `delta` (positive
2127    /// for inserts, negative for deletes). Marks tied to a deleted row
2128    /// are dropped; marks past the affected band shift by `delta`.
2129    fn shift_marks_after_edit(&mut self, edit_start: usize, delta: isize) {
2130        if delta == 0 {
2131            return;
2132        }
2133        // Deleted-row band (only meaningful for delta < 0). Inclusive
2134        // start, exclusive end.
2135        let drop_end = if delta < 0 {
2136            edit_start.saturating_add((-delta) as usize)
2137        } else {
2138            edit_start
2139        };
2140        let shift_threshold = drop_end.max(edit_start.saturating_add(1));
2141
2142        self.buffer
2143            .rebase_marks(edit_start, drop_end, shift_threshold, delta);
2144
2145        // Shift global marks that belong to the current buffer.
2146        let cur_bid = self.current_buffer_id;
2147        let mut global_to_drop: Vec<char> = Vec::new();
2148        for (c, (bid, row, _col)) in self.global_marks.iter_mut() {
2149            if *bid != cur_bid {
2150                continue;
2151            }
2152            if (edit_start..drop_end).contains(row) {
2153                global_to_drop.push(*c);
2154            } else if *row >= shift_threshold {
2155                *row = ((*row as isize) + delta).max(0) as usize;
2156            }
2157        }
2158        for c in global_to_drop {
2159            self.global_marks.remove(&c);
2160        }
2161
2162        let shift_jumps = |entries: &mut Vec<(usize, usize)>| {
2163            entries.retain(|(row, _)| !(edit_start..drop_end).contains(row));
2164            for (row, _) in entries.iter_mut() {
2165                if *row >= shift_threshold {
2166                    *row = ((*row as isize) + delta).max(0) as usize;
2167                }
2168            }
2169        };
2170        shift_jumps(&mut self.jump_back);
2171        shift_jumps(&mut self.jump_fwd);
2172    }
2173
2174    /// Reverse-sync helper paired with [`Editor::mutate_edit`]: rebuild
2175    /// the textarea from the buffer's lines + cursor, preserving yank
2176    /// text. Heavy (allocates a fresh `TextArea`) but correct; the
2177    /// textarea field disappears at the end of Phase 7f anyway.
2178    /// No-op since Buffer is the content authority. Retained as a
2179    /// shim so call sites in `mutate_edit` and friends don't have to
2180    /// be ripped in lockstep with the field removal.
2181    pub(crate) fn push_buffer_content_to_textarea(&mut self) {}
2182
2183    /// Single choke-point for "the buffer just changed". Sets the
2184    /// dirty flag and drops the cached `content_arc` snapshot so
2185    /// subsequent reads rebuild from the live textarea. Callers
2186    /// mutating `textarea` directly (e.g. the TUI's bracketed-paste
2187    /// path) must invoke this to keep the cache honest.
2188    pub fn mark_content_dirty(&mut self) {
2189        self.buffer.mark_content_dirty();
2190    }
2191
2192    /// Returns true if content changed since the last call, then clears the flag.
2193    pub fn take_dirty(&mut self) -> bool {
2194        self.buffer.take_dirty()
2195    }
2196
2197    /// Drain the one-shot smooth-scroll hint (#195). True if the last step ran
2198    /// a page/recenter motion the app may animate.
2199    pub fn take_scroll_anim_hint(&mut self) -> bool {
2200        let h = self.scroll_anim_hint;
2201        self.scroll_anim_hint = false;
2202        h
2203    }
2204
2205    // ── Jumplist / viewport-pin (discipline-agnostic seam, #265) ─────────────
2206    //
2207    // Navigation history and viewport pinning are not vim concepts — VSCode's
2208    // Go Back / Go Forward wants the same jumplist, and any discipline can pin
2209    // the viewport. These accessors live on the engine so a future
2210    // helix/vscode discipline reaches them without depending on hjkl-vim. The
2211    // vim *keybindings* on top (`Ctrl-o` / `Ctrl-i`) stay in hjkl-vim.
2212
2213    /// Read-only view of the jumplist as `(jump_back, jump_fwd)`. Newest entry
2214    /// is at the back of each. Backs `:jumps`.
2215    #[allow(clippy::type_complexity)]
2216    pub fn jump_list(&self) -> (&[(usize, usize)], &[(usize, usize)]) {
2217        (&self.jump_back, &self.jump_fwd)
2218    }
2219
2220    /// Position the cursor was at when the user last jumped back. `None`
2221    /// before any jump.
2222    pub fn last_jump_back(&self) -> Option<(usize, usize)> {
2223        self.jump_back.last().copied()
2224    }
2225
2226    /// Read-only view of the jump-back stack.
2227    pub fn jump_back_list(&self) -> &[(usize, usize)] {
2228        &self.jump_back
2229    }
2230
2231    /// Mutable access to the jump-back stack.
2232    pub fn jump_back_list_mut(&mut self) -> &mut Vec<(usize, usize)> {
2233        &mut self.jump_back
2234    }
2235
2236    /// Read-only view of the jump-forward stack.
2237    pub fn jump_fwd_list(&self) -> &[(usize, usize)] {
2238        &self.jump_fwd
2239    }
2240
2241    /// Mutable access to the jump-forward stack.
2242    pub fn jump_fwd_list_mut(&mut self) -> &mut Vec<(usize, usize)> {
2243        &mut self.jump_fwd
2244    }
2245
2246    /// Whether the viewport is pinned (suppresses scroll-follow).
2247    pub fn viewport_pinned(&self) -> bool {
2248        self.viewport_pinned
2249    }
2250
2251    /// Set the viewport-pinned flag.
2252    pub fn set_viewport_pinned(&mut self, v: bool) {
2253        self.viewport_pinned = v;
2254    }
2255
2256    /// Queue an LSP intent for the host to service on the next tick.
2257    pub fn set_pending_lsp(&mut self, intent: Option<crate::editor::LspIntent>) {
2258        self.pending_lsp = intent;
2259    }
2260
2261    /// Record the row range touched by the most recent auto-indent, for the
2262    /// host to pick up via `take_last_indent_range`.
2263    pub fn set_last_indent_range(&mut self, range: Option<(usize, usize)>) {
2264        self.last_indent_range = range;
2265    }
2266
2267    /// Walk cursor into the change list (`g;` / `g,`), or `None` when not
2268    /// walking.
2269    pub fn change_list_cursor(&self) -> Option<usize> {
2270        self.change_list_cursor
2271    }
2272
2273    /// Set the change-list walk cursor.
2274    pub fn set_change_list_cursor(&mut self, idx: Option<usize>) {
2275        self.change_list_cursor = idx;
2276    }
2277
2278    /// Arm the one-shot hint that the next scroll should be animated.
2279    pub fn set_scroll_anim_hint(&mut self, v: bool) {
2280        self.scroll_anim_hint = v;
2281    }
2282
2283    /// Set the read-only view overlay (Normal / Blame).
2284    pub fn set_view_mode(&mut self, v: crate::ViewMode) {
2285        self.view = v;
2286    }
2287
2288    /// The active abbreviation table.
2289    pub fn abbrevs(&self) -> &[crate::abbrev::Abbrev] {
2290        &self.abbrevs
2291    }
2292
2293    /// Autopair's queued close-brackets, as `(row, col, ch)`. A discipline's
2294    /// insert path consumes a queued close when the user types the matching
2295    /// character instead of inserting a second one.
2296    pub fn pending_closes(&self) -> &[(usize, usize, char)] {
2297        &self.pending_closes
2298    }
2299
2300    /// Mutable access to autopair's queued close-brackets.
2301    pub fn pending_closes_mut(&mut self) -> &mut Vec<(usize, usize, char)> {
2302        &mut self.pending_closes
2303    }
2304
2305    /// Whether the unnamed register's content is linewise.
2306    pub fn yank_linewise(&self) -> bool {
2307        self.yank_linewise
2308    }
2309
2310    /// Set the linewise flag for the unnamed register.
2311    pub fn set_yank_linewise(&mut self, v: bool) {
2312        self.yank_linewise = v;
2313    }
2314
2315    // ── Search state (discipline-agnostic seam, #265) ────────────────────────
2316    //
2317    // Every editor has find. These live on the engine so a helix/vscode
2318    // discipline reaches the pattern, direction and history without depending
2319    // on hjkl-vim. The vim *keybindings* on top (`/`, `?`, `n`, `N`, `*`) stay
2320    // in hjkl-vim.
2321
2322    /// The live `/` or `?` search-prompt state, if a prompt is open.
2323    pub fn search_prompt_state(&self) -> Option<&crate::search::SearchPrompt> {
2324        self.search_prompt.as_ref()
2325    }
2326
2327    /// Mutable access to the live search-prompt state.
2328    pub fn search_prompt_state_mut(&mut self) -> Option<&mut crate::search::SearchPrompt> {
2329        self.search_prompt.as_mut()
2330    }
2331
2332    /// Take (and close) the search-prompt state.
2333    pub fn take_search_prompt_state(&mut self) -> Option<crate::search::SearchPrompt> {
2334        self.search_prompt.take()
2335    }
2336
2337    /// Install (or clear) the search-prompt state.
2338    pub fn set_search_prompt_state(&mut self, prompt: Option<crate::search::SearchPrompt>) {
2339        self.search_prompt = prompt;
2340    }
2341
2342    /// The last committed search pattern, for `n` / `N` (or Find Next).
2343    pub fn last_search_pattern(&self) -> Option<&str> {
2344        self.last_search.as_deref()
2345    }
2346
2347    /// Set the last search pattern without touching direction or highlight.
2348    pub fn set_last_search_pattern_only(&mut self, pattern: Option<String>) {
2349        self.last_search = pattern;
2350    }
2351
2352    /// Set the last search direction without touching the pattern.
2353    pub fn set_last_search_forward_only(&mut self, forward: bool) {
2354        self.last_search_forward = forward;
2355    }
2356
2357    /// Read-only view of the search history (oldest first).
2358    pub fn search_history(&self) -> &[String] {
2359        &self.search_history
2360    }
2361
2362    /// Mutable access to the search history.
2363    pub fn search_history_mut(&mut self) -> &mut Vec<String> {
2364        &mut self.search_history
2365    }
2366
2367    /// Cursor position while walking search history with Up/Down.
2368    pub fn search_history_cursor(&self) -> Option<usize> {
2369        self.search_history_cursor
2370    }
2371
2372    /// Set the search-history walk cursor.
2373    pub fn set_search_history_cursor(&mut self, idx: Option<usize>) {
2374        self.search_history_cursor = idx;
2375    }
2376
2377    // ── Input timing (discipline-agnostic seam) ──────────────────────────────
2378    //
2379    // Any chorded FSM needs a timeout clock, not just vim.
2380
2381    /// Instant of the last input, when the host supplies a monotonic clock.
2382    pub fn last_input_at(&self) -> Option<std::time::Instant> {
2383        self.last_input_at
2384    }
2385
2386    /// Set the instant of the last input.
2387    pub fn set_last_input_at(&mut self, t: Option<std::time::Instant>) {
2388        self.last_input_at = t;
2389    }
2390
2391    /// Host-supplied elapsed time at the last input (no_std hosts).
2392    pub fn last_input_host_at(&self) -> Option<core::time::Duration> {
2393        self.last_input_host_at
2394    }
2395
2396    /// Set the host-supplied elapsed time at the last input.
2397    pub fn set_last_input_host_at(&mut self, d: Option<core::time::Duration>) {
2398        self.last_input_host_at = d;
2399    }
2400
2401    // ── Scrolling (discipline-agnostic seam, #265) ───────────────────────────
2402    //
2403    // Scrolling a viewport is not a vim concept — every discipline does it.
2404    // These carry zero vim FSM state (the one field they used to touch,
2405    // `scroll_anim_hint`, now lives on the Editor), so they belong here. The
2406    // vim *keybindings* on top (`Ctrl-F`/`Ctrl-B`, `Ctrl-D`/`Ctrl-U`,
2407    // `Ctrl-E`/`Ctrl-Y`) stay in hjkl-vim.
2408
2409    /// Rows spanned by half a viewport, times `count` (min 1).
2410    pub fn viewport_half_rows(&self, count: usize) -> usize {
2411        let h = self.viewport_height_value() as usize;
2412        (h / 2).max(1).saturating_mul(count.max(1))
2413    }
2414
2415    /// Rows spanned by a full viewport (less a two-line overlap), times
2416    /// `count` (min 1).
2417    pub fn viewport_full_rows(&self, count: usize) -> usize {
2418        let h = self.viewport_height_value() as usize;
2419        h.saturating_sub(2).max(1).saturating_mul(count.max(1))
2420    }
2421
2422    /// Move the cursor `delta` rows (clamped to the buffer), landing on the
2423    /// first non-blank of the target row and resetting the sticky column.
2424    pub fn scroll_cursor_rows(&mut self, delta: isize) {
2425        if delta == 0 {
2426            return;
2427        }
2428        self.sync_buffer_content_from_textarea();
2429        let (row, _) = self.cursor();
2430        let last_row = buf_row_count(&self.buffer).saturating_sub(1);
2431        let target = (row as isize + delta).max(0).min(last_row as isize) as usize;
2432        buf_set_cursor_rc(&mut self.buffer, target, 0);
2433        crate::motions::move_first_non_blank(&mut self.buffer);
2434        self.push_buffer_cursor_to_textarea();
2435        self.sticky_col = Some(buf_cursor_pos(&self.buffer).col);
2436    }
2437
2438    /// Scroll the cursor by one full viewport height (height − 2 rows,
2439    /// preserving a two-line overlap). `count` multiplies the step.
2440    pub fn scroll_full_page(&mut self, dir: crate::types::ScrollDir, count: usize) {
2441        self.scroll_anim_hint = true;
2442        let rows = self.viewport_full_rows(count) as isize;
2443        match dir {
2444            crate::types::ScrollDir::Down => self.scroll_cursor_rows(rows),
2445            crate::types::ScrollDir::Up => self.scroll_cursor_rows(-rows),
2446        }
2447    }
2448
2449    /// Scroll the cursor by half the viewport height. `count` multiplies.
2450    pub fn scroll_half_page(&mut self, dir: crate::types::ScrollDir, count: usize) {
2451        self.scroll_anim_hint = true;
2452        let rows = self.viewport_half_rows(count) as isize;
2453        match dir {
2454            crate::types::ScrollDir::Down => self.scroll_cursor_rows(rows),
2455            crate::types::ScrollDir::Up => self.scroll_cursor_rows(-rows),
2456        }
2457    }
2458
2459    /// Scroll the viewport `count` lines without moving the cursor (the cursor
2460    /// is clamped into the new visible region if it would fall outside).
2461    pub fn scroll_line(&mut self, dir: crate::types::ScrollDir, count: usize) {
2462        let n = count.max(1);
2463        let total = buf_row_count(&self.buffer);
2464        let last = total.saturating_sub(1);
2465        let h = self.viewport_height_value() as usize;
2466        let cur_top = self.host().viewport().top_row;
2467        let new_top = match dir {
2468            crate::types::ScrollDir::Down => (cur_top + n).min(last),
2469            crate::types::ScrollDir::Up => cur_top.saturating_sub(n),
2470        };
2471        self.set_viewport_top(new_top);
2472        // Clamp cursor to stay within the new visible region.
2473        let (row, col) = self.cursor();
2474        let bot = (new_top + h).saturating_sub(1).min(last);
2475        let clamped = row.max(new_top).min(bot);
2476        if clamped != row {
2477            buf_set_cursor_rc(&mut self.buffer, clamped, col);
2478            self.push_buffer_cursor_to_textarea();
2479        }
2480    }
2481
2482    /// Drain the queue of [`crate::types::ContentEdit`]s emitted since
2483    /// the last call. Each entry corresponds to a single buffer
2484    /// mutation funnelled through [`Editor::mutate_edit`]; block edits
2485    /// fan out to one entry per row touched.
2486    ///
2487    /// Hosts call this each frame (after [`Editor::take_content_reset`])
2488    /// to fan edits into a tree-sitter parser via `Tree::edit`.
2489    pub fn take_content_edits(&mut self) -> Vec<crate::types::ContentEdit> {
2490        self.buffer.take_pending_content_edits()
2491    }
2492
2493    /// Returns `true` if a bulk buffer replacement happened since the
2494    /// last call (e.g. `set_content` / `restore` / undo restore), then
2495    /// clears the flag. When this returns `true`, hosts should drop
2496    /// any retained syntax tree before consuming
2497    /// [`Editor::take_content_edits`].
2498    pub fn take_content_reset(&mut self) -> bool {
2499        self.buffer.take_pending_content_reset()
2500    }
2501
2502    /// Pull-model coarse change observation. If content changed since
2503    /// the last call, returns `Some(Arc<String>)` with the new content
2504    /// and clears the dirty flag; otherwise returns `None`.
2505    ///
2506    /// Hosts that need fine-grained edit deltas (e.g., DOM patching at
2507    /// the character level) should diff against their own previous
2508    /// snapshot. The SPEC `take_changes() -> Vec<EditOp>` API lands
2509    /// once every edit path inside the engine is instrumented; this
2510    /// coarse form covers the pull-model use case in the meantime.
2511    pub fn take_content_change(&mut self) -> Option<std::sync::Arc<String>> {
2512        if !self.buffer.content_dirty() {
2513            return None;
2514        }
2515        let arc = self.content_arc();
2516        self.buffer.set_content_dirty(false);
2517        Some(arc)
2518    }
2519
2520    /// Width in cells of the line-number gutter for the current buffer
2521    /// and settings. Matches what [`Editor::cursor_screen_pos`] reserves
2522    /// in front of the text column. Returns `0` when both `number` and
2523    /// `relativenumber` are off.
2524    pub fn lnum_width(&self) -> u16 {
2525        if self.settings.number || self.settings.relativenumber {
2526            let needed = buf_row_count(&self.buffer).to_string().len() + 1;
2527            needed.max(self.settings.numberwidth) as u16
2528        } else {
2529            0
2530        }
2531    }
2532
2533    /// Returns the cursor's row within the visible textarea (0-based), updating
2534    /// the stored viewport top so subsequent calls remain accurate.
2535    pub fn cursor_screen_row(&mut self, height: u16) -> u16 {
2536        let cursor = buf_cursor_row(&self.buffer);
2537        let top = self.host.viewport().top_row;
2538        cursor.saturating_sub(top).min(height as usize - 1) as u16
2539    }
2540
2541    /// Returns the cursor's screen position `(x, y)` for the textarea
2542    /// described by `(area_x, area_y, area_width, area_height)`.
2543    /// Accounts for line-number gutter, viewport scroll, and any extra
2544    /// gutter width to the left of the number column (sign column, fold
2545    /// column). Returns `None` if the cursor is outside the visible
2546    /// viewport. Always available (engine-native; no ratatui dependency).
2547    ///
2548    /// `extra_gutter_width` is added to the number-column width before
2549    /// computing the cursor x position. Callers (e.g. `apps/hjkl/src/render.rs`)
2550    /// pass `sign_w + fold_w` here so the cursor lands on the correct cell
2551    /// when a dedicated sign or fold column is present.
2552    ///
2553    /// Renamed from `cursor_screen_pos_xywh` in 0.0.32.
2554    pub fn cursor_screen_pos(
2555        &self,
2556        area_x: u16,
2557        area_y: u16,
2558        area_width: u16,
2559        area_height: u16,
2560        extra_gutter_width: u16,
2561    ) -> Option<(u16, u16)> {
2562        let (pos_row, pos_col) = buf_cursor_rc(&self.buffer);
2563        let v = self.host.viewport();
2564        if pos_row < v.top_row || pos_col < v.top_col {
2565            return None;
2566        }
2567        let lnum_width = self.lnum_width();
2568        // Full offset from the left edge of the window to the first text cell.
2569        let gutter_total = lnum_width + extra_gutter_width;
2570        // Screen row delta: delegate to the single fold- and wrap-aware
2571        // calculator that already drives scrolling + scrolloff, rather than
2572        // recomputing `pos_row - top_row` here. That naive delta ignored rows
2573        // collapsed by closed folds, painting the cursor block N rows too low
2574        // while the (fold-aware) text + line-highlight rendered correctly.
2575        // One source of truth → no drift between scroll math and cursor math. (#244)
2576        let folds = crate::buffer_impl::SnapshotFoldProvider::from_buffer(&self.buffer);
2577        let dy = crate::viewport_math::cursor_screen_row_from(&self.buffer, &folds, v, v.top_row)?
2578            as u16;
2579        // Convert char column to visual column so cursor lands on the
2580        // correct cell when the line contains tabs (which the renderer
2581        // expands to TAB_WIDTH stops). Tab width must match the renderer.
2582        let cursor_rope = self.buffer.rope();
2583        let pos_row_safe = pos_row.min(cursor_rope.len_lines().saturating_sub(1));
2584        let line = hjkl_buffer::rope_line_str(&cursor_rope, pos_row_safe);
2585        let tab_width = if v.tab_width == 0 {
2586            4
2587        } else {
2588            v.tab_width as usize
2589        };
2590        let visual_pos = visual_col_for_char(&line, pos_col, tab_width);
2591        let visual_top = visual_col_for_char(&line, v.top_col, tab_width);
2592        let dx = (visual_pos - visual_top) as u16;
2593        if dy >= area_height || dx + gutter_total >= area_width {
2594            return None;
2595        }
2596        Some((area_x + gutter_total + dx, area_y + dy))
2597    }
2598
2599    /// Discipline-agnostic coarse mode for app chrome (status badge, cursor
2600    /// shape). App code that only needs "inserting / selecting / idle" — not the
2601    /// precise vim mode — should read this so it works identically under any
2602    /// keybinding discipline (vim, vscode, future helix/emacs). See
2603    /// [`crate::CoarseMode`] (epic #265 G3). Today this projects from the vim
2604    /// mode; once FSM state is pluggable each discipline supplies its own.
2605    pub fn coarse_mode(&self) -> crate::CoarseMode {
2606        self.discipline.coarse_mode()
2607    }
2608
2609    /// The secondary selections, in char columns. Empty for a single-cursor
2610    /// editor.
2611    ///
2612    /// The primary selection is *not* included: its head is [`Editor::cursor`]
2613    /// and its anchor lives in the discipline — see the `extra_selections` field
2614    /// docs for why.
2615    pub fn extra_selections(&self) -> &[crate::selection_shift::Sel] {
2616        &self.extra_selections
2617    }
2618
2619    /// The **heads** of the secondary selections — the carets a user sees.
2620    ///
2621    /// Convenience view over [`Editor::extra_selections`] for callers that only
2622    /// care where the carets are (rendering, tests).
2623    pub fn extra_cursors(&self) -> Vec<hjkl_buffer::Position> {
2624        self.extra_selections.iter().map(|s| s.head).collect()
2625    }
2626
2627    /// Replace the whole secondary set.
2628    ///
2629    /// Selections whose head duplicates the primary head, or an earlier entry's
2630    /// head, are dropped: two carets on one spot would apply every edit twice at
2631    /// the same place. Same invariant [`Editor::add_cursor`] enforces, applied to
2632    /// a bulk write — a discipline recomputing every selection after a motion
2633    /// (helix does this on every keystroke) must not be able to smuggle a
2634    /// duplicate in through the back door.
2635    pub fn set_extra_selections(&mut self, sels: Vec<crate::selection_shift::Sel>) {
2636        let (row, col) = self.cursor();
2637        let primary = hjkl_buffer::Position::new(row, col);
2638        self.extra_selections.clear();
2639        for s in sels {
2640            if s.head == primary || self.extra_selections.iter().any(|e| e.head == s.head) {
2641                continue;
2642            }
2643            self.extra_selections.push(s);
2644        }
2645    }
2646
2647    /// Add a secondary selection. Same dedup rule as [`Editor::add_cursor`].
2648    pub fn add_selection(&mut self, sel: crate::selection_shift::Sel) {
2649        let (row, col) = self.cursor();
2650        if sel.head == hjkl_buffer::Position::new(row, col)
2651            || self.extra_selections.iter().any(|s| s.head == sel.head)
2652        {
2653            return;
2654        }
2655        self.extra_selections.push(sel);
2656    }
2657
2658    /// Add a secondary cursor: a zero-width selection at `pos`. Ignores a
2659    /// position that duplicates the primary head or an existing secondary head,
2660    /// so a set never carries two carets at one spot — that would apply an edit
2661    /// twice at the same place.
2662    pub fn add_cursor(&mut self, pos: hjkl_buffer::Position) {
2663        self.add_selection(crate::selection_shift::Sel::caret(pos));
2664    }
2665
2666    /// Drop every secondary selection, collapsing back to the primary.
2667    pub fn clear_extra_cursors(&mut self) {
2668        self.extra_selections.clear();
2669    }
2670
2671    /// Apply an edit at **every** cursor — the primary and all secondaries —
2672    /// and leave each cursor where its own edit left it (#63).
2673    ///
2674    /// `make` is handed each cursor's position and returns the edit to apply
2675    /// there, so the caller writes the edit once and it fans out:
2676    ///
2677    /// ```ignore
2678    /// ed.edit_at_all_cursors(|at| Edit::InsertStr { at, text: "x".into() });
2679    /// ```
2680    ///
2681    /// Returns the inverse of each applied edit, in application order, so a
2682    /// caller can push them as one undo step. This does **not** touch the undo
2683    /// stack itself — `mutate_edit` never does, and a multi-cursor keystroke is
2684    /// one user action, so the discipline pushes undo once before calling.
2685    ///
2686    /// # Why the order matters
2687    ///
2688    /// Edits are applied **bottom-up** (last cursor in the document first). An
2689    /// edit at position P only moves positions at or after P, so working
2690    /// backwards leaves every not-yet-visited cursor's coordinates still valid.
2691    /// Going top-down would invalidate them all after the first edit.
2692    ///
2693    /// Each cursor that has already been edited is parked in `extra_cursors`,
2694    /// so [`Editor::mutate_edit`]'s shift keeps it correct as the remaining
2695    /// (earlier) edits land. The bookkeeping is the same machinery, reused.
2696    ///
2697    /// # Degradation
2698    ///
2699    /// If any cursor becomes untrackable mid-apply (see `selection_shift`), the
2700    /// secondaries are dropped and the editor collapses to the primary rather
2701    /// than carrying on with a caret that no longer knows where it is.
2702    pub fn edit_at_all_cursors(
2703        &mut self,
2704        make: impl Fn(hjkl_buffer::Position) -> hjkl_buffer::Edit,
2705    ) -> Vec<hjkl_buffer::Edit> {
2706        let (pr, pc) = self.cursor();
2707        let primary = hjkl_buffer::Position::new(pr, pc);
2708        let (inverses, _) = self.edit_at_all_selections(primary, |s| make(s.head));
2709        inverses
2710    }
2711
2712    /// Apply an edit at **every selection** — the primary and all secondaries —
2713    /// where `make` sees the whole selection, not just its head (#63).
2714    ///
2715    /// This is what an operator needs: `d` on three selections has to delete
2716    /// three *ranges*, and only the caller-visible [`Sel`] carries both ends.
2717    /// [`Editor::edit_at_all_cursors`] is the caret-only special case of this.
2718    ///
2719    /// `primary_anchor` is passed in — and the primary's *new* anchor is returned
2720    /// — because the primary selection's anchor lives in the discipline's state,
2721    /// not the engine's (see the `extra_selections` field docs).
2722    ///
2723    /// Returns `(inverse of each applied edit in application order, new primary
2724    /// anchor)`. This does **not** touch the undo stack — `mutate_edit` never
2725    /// does, and a multi-cursor keystroke is one user action, so the discipline
2726    /// pushes undo once before calling.
2727    ///
2728    /// # Why the order matters
2729    ///
2730    /// Edits are applied **bottom-up** (last selection in the document first). An
2731    /// edit at position P only moves positions at or after P, so working
2732    /// backwards leaves every not-yet-visited selection's coordinates still valid.
2733    /// Going top-down would invalidate them all after the first edit.
2734    ///
2735    /// Each selection that has already been edited is parked in
2736    /// `extra_selections`, so [`Editor::mutate_edit`]'s shift keeps it correct as
2737    /// the remaining (earlier) edits land.
2738    ///
2739    /// # What happens to the anchors
2740    ///
2741    /// Each selection's anchor is shifted through *its own* edit with the same
2742    /// insertion-point semantics [`crate::selection_shift`] uses everywhere: an
2743    /// anchor swallowed by a deletion collapses onto the deletion start, which is
2744    /// exactly where the head lands — so `d` / `c` leave a caret at each edit
2745    /// site, with no bookkeeping. An anchor sitting exactly at an insertion point
2746    /// slides right with the text. A caller that needs a selection *preserved*
2747    /// across a same-length rewrite (helix's `~`, `>`) should re-set the
2748    /// selections afterwards via [`Editor::set_extra_selections`] rather than
2749    /// rely on that shift.
2750    ///
2751    /// # Degradation
2752    ///
2753    /// If any selection becomes untrackable mid-apply (see `selection_shift`), the
2754    /// secondaries are dropped and the editor collapses to the primary rather than
2755    /// carrying on with a selection that no longer knows where it is.
2756    ///
2757    /// [`Sel`]: crate::selection_shift::Sel
2758    pub fn edit_at_all_selections(
2759        &mut self,
2760        primary_anchor: hjkl_buffer::Position,
2761        make: impl Fn(crate::selection_shift::Sel) -> hjkl_buffer::Edit,
2762    ) -> (Vec<hjkl_buffer::Edit>, hjkl_buffer::Position) {
2763        use crate::selection_shift::Sel;
2764
2765        let (pr, pc) = self.cursor();
2766        let primary = Sel::new(primary_anchor, hjkl_buffer::Position::new(pr, pc));
2767
2768        let mut all: Vec<Sel> = std::iter::once(primary)
2769            .chain(self.extra_selections.iter().copied())
2770            .collect();
2771        // Bottom-up by where each selection's edit *starts* — its earlier end.
2772        // For a caret that is just the head, so this is the same order as before.
2773        all.sort_by_key(|s| std::cmp::Reverse((s.start().row, s.start().col)));
2774
2775        // Rebuilt as we go: a selection lands in here the moment its edit is done,
2776        // which enrols it in the shift for every later edit.
2777        self.extra_selections.clear();
2778
2779        let mut inverses = Vec::with_capacity(all.len());
2780        let mut primary_idx: Option<usize> = None;
2781        let mut lost_a_selection = false;
2782
2783        for (i, s) in all.iter().copied().enumerate() {
2784            // Every previous iteration should have parked exactly one selection.
2785            // If the count slipped, `mutate_edit` dropped one it could not track.
2786            if self.extra_selections.len() != i {
2787                lost_a_selection = true;
2788                break;
2789            }
2790            let edit = make(s);
2791            // The anchor has to be shifted against the PRE-edit geometry, same as
2792            // the parked selections are — so read the metrics before applying.
2793            let rows = buf_row_count(&self.buffer);
2794            let lens: Vec<usize> = (0..rows).map(|r| buf_line_chars(&self.buffer, r)).collect();
2795            let shifted_anchor = crate::selection_shift::shift_position(
2796                s.anchor,
2797                &edit,
2798                |r| lens.get(r).copied().unwrap_or(0),
2799                rows,
2800            );
2801
2802            self.set_cursor_quiet(s.head.row, s.head.col);
2803            inverses.push(self.mutate_edit(edit));
2804            let (nr, nc) = self.cursor();
2805
2806            let Some(anchor) = shifted_anchor else {
2807                lost_a_selection = true;
2808                break;
2809            };
2810            if s == primary && primary_idx.is_none() {
2811                primary_idx = Some(self.extra_selections.len());
2812            }
2813            self.extra_selections
2814                .push(Sel::new(anchor, hjkl_buffer::Position::new(nr, nc)));
2815        }
2816
2817        match (lost_a_selection, primary_idx) {
2818            (false, Some(idx)) if idx < self.extra_selections.len() => {
2819                // Pull the primary back out of the parked set; the rest stay.
2820                let landed = self.extra_selections.remove(idx);
2821                self.set_cursor_quiet(landed.head.row, landed.head.col);
2822                (inverses, landed.anchor)
2823            }
2824            _ => {
2825                // Something went untrackable: collapse to a single selection rather
2826                // than leave one pointing at text it no longer owns.
2827                self.extra_selections.clear();
2828                let (row, col) = self.cursor();
2829                (inverses, hjkl_buffer::Position::new(row, col))
2830            }
2831        }
2832    }
2833
2834    /// The installed discipline's FSM state, type-erased.
2835    ///
2836    /// A discipline crate reaches its own concrete state by downcasting:
2837    /// `ed.discipline().as_any().downcast_ref::<VimState>()`.
2838    pub fn discipline(&self) -> &dyn crate::DisciplineState {
2839        &*self.discipline
2840    }
2841
2842    /// Mutable counterpart of [`Editor::discipline`].
2843    pub fn discipline_mut(&mut self) -> &mut dyn crate::DisciplineState {
2844        &mut *self.discipline
2845    }
2846
2847    /// Install a keyboard discipline, replacing whatever was there.
2848    ///
2849    /// Host apps call this once at construction (e.g.
2850    /// `hjkl_vim::install_vim_discipline(&mut ed)`); an `Editor` that never
2851    /// receives discipline input keeps the default
2852    /// [`NoDiscipline`](crate::NoDiscipline).
2853    pub fn set_discipline(&mut self, discipline: Box<dyn crate::DisciplineState>) {
2854        self.discipline = discipline;
2855    }
2856
2857    /// The active read-only view overlay (see [`crate::ViewMode`]). Independent
2858    /// of [`Editor::vim_mode`]; the host renderer reads this as the source of
2859    /// truth for whether to draw the git-blame framing.
2860    pub fn view_mode(&self) -> crate::ViewMode {
2861        self.view
2862    }
2863
2864    /// `true` when the git-blame read-only overlay is active. Masked on the
2865    /// input mode: BLAME is only meaningful in Normal, so this returns `false`
2866    /// the instant the editor enters Insert/Visual/etc., even before the
2867    /// overlay flag is dropped. Use this for both rendering and mode-label.
2868    pub fn is_blame(&self) -> bool {
2869        self.view == crate::ViewMode::Blame && self.coarse_mode() == crate::CoarseMode::Normal
2870    }
2871
2872    /// Enter the git-blame read-only overlay. No-op unless the editor is in
2873    /// Normal mode (BLAME is a Normal-only view). While active, every mutation
2874    /// funnel is blocked and the host renders the per-commit framing.
2875    pub fn enter_blame(&mut self) {
2876        if self.coarse_mode() == crate::CoarseMode::Normal {
2877            self.view = crate::ViewMode::Blame;
2878        }
2879    }
2880
2881    /// Leave the git-blame overlay, returning to a plain Normal view. Idempotent.
2882    pub fn exit_blame(&mut self) {
2883        self.view = crate::ViewMode::Normal;
2884    }
2885
2886    /// Bounds of the active visual-block rectangle as
2887    /// `(top_row, bot_row, left_col, right_col)` — all inclusive.
2888    /// `None` when we're not in VisualBlock mode.
2889    /// Read-only view of the live `/` or `?` prompt. `None` outside
2890    /// search-prompt mode.
2891    pub fn search_prompt(&self) -> Option<&crate::search::SearchPrompt> {
2892        self.search_prompt.as_ref()
2893    }
2894
2895    /// Most recent committed search pattern (persists across `n` / `N`
2896    /// and across prompt exits). `None` before the first search.
2897    pub fn last_search(&self) -> Option<&str> {
2898        self.last_search.as_deref()
2899    }
2900
2901    /// Whether the last committed search was a forward `/` (`true`) or
2902    /// a backward `?` (`false`). `n` and `N` consult this to honour the
2903    /// direction the user committed.
2904    pub fn last_search_forward(&self) -> bool {
2905        self.last_search_forward
2906    }
2907
2908    /// Set the most recent committed search text + direction. Used by
2909    /// host-driven prompts (e.g. apps/hjkl's `/` `?` prompt that lives
2910    /// outside the engine's vim FSM) so `n` / `N` repeat the host's
2911    /// most recent commit with the right direction. Pass `None` /
2912    /// `true` to clear.
2913    pub fn set_last_search(&mut self, text: Option<String>, forward: bool) {
2914        self.last_search = text;
2915        self.last_search_forward = forward;
2916    }
2917
2918    /// The most recent successful `:s` command. `None` before the first substitute.
2919    /// Used by `:&` / `:&&` to repeat it.
2920    pub fn last_substitute(&self) -> Option<&crate::substitute::SubstituteCmd> {
2921        self.last_substitute.as_ref()
2922    }
2923
2924    /// Store the last successful substitute so `:&` / `:&&` can repeat it.
2925    pub fn set_last_substitute(&mut self, cmd: crate::substitute::SubstituteCmd) {
2926        self.last_substitute = Some(cmd);
2927    }
2928
2929    /// Number of rows (lines) in the buffer.
2930    ///
2931    /// Convenience accessor for call sites that only need the row count without
2932    /// routing through the `Query` trait directly (e.g. the VSCode selection
2933    /// dispatcher computing buffer-end positions).
2934    pub fn row_count(&self) -> usize {
2935        buf_row_count(&self.buffer)
2936    }
2937
2938    /// Row `row` as an owned `String` (no trailing newline), or `None` when
2939    /// `row` is out of bounds.
2940    ///
2941    /// Mode-agnostic buffer read. Hosts and discipline crates (e.g. the vim
2942    /// accessors on `hjkl_vim::VimEditorExt`) use this instead of reaching for
2943    /// the engine's private `buf_line` helper.
2944    pub fn line(&self, row: usize) -> Option<String> {
2945        buf_line(&self.buffer, row)
2946    }
2947
2948    pub fn content(&self) -> String {
2949        let n = buf_row_count(&self.buffer);
2950        let mut s = String::new();
2951        for r in 0..n {
2952            if r > 0 {
2953                s.push('\n');
2954            }
2955            s.push_str(&crate::types::Query::line(&self.buffer, r as u32));
2956        }
2957        s.push('\n');
2958        s
2959    }
2960
2961    /// Same logical output as [`content`], but returns a cached
2962    /// `Arc<String>` so back-to-back reads within an un-mutated window
2963    /// are ref-count bumps instead of multi-MB joins. The cache is
2964    /// invalidated by every [`mark_content_dirty`] call.
2965    pub fn content_arc(&mut self) -> std::sync::Arc<String> {
2966        if let Some(arc) = self.buffer.cached_editor_content() {
2967            return arc;
2968        }
2969        let arc = std::sync::Arc::new(self.content());
2970        self.buffer
2971            .set_cached_editor_content(std::sync::Arc::clone(&arc));
2972        arc
2973    }
2974
2975    pub fn set_content(&mut self, text: &str) {
2976        let mut lines: Vec<String> = text.lines().map(|l| l.to_string()).collect();
2977        while lines.last().map(|l| l.is_empty()).unwrap_or(false) {
2978            lines.pop();
2979        }
2980        if lines.is_empty() {
2981            lines.push(String::new());
2982        }
2983        let _ = lines;
2984        crate::types::BufferEdit::replace_all(&mut self.buffer, text);
2985        self.buffer.clear_undo_redo();
2986        // Whole-buffer replace supersedes any queued ContentEdits.
2987        self.buffer.clear_pending_content_edits();
2988        self.buffer.set_pending_content_reset(true);
2989        self.mark_content_dirty();
2990    }
2991
2992    /// Whole-buffer replace that **preserves the undo history**.
2993    ///
2994    /// Equivalent to [`Editor::set_content`] but pushes the current buffer
2995    /// state onto the undo stack first, so a subsequent `u` walks back to
2996    /// the pre-replacement content. Use this for any operation the user
2997    /// expects to undo as a single step — e.g. external formatter output
2998    /// (`hjkl-mangler`) installed via the async [`crate::app::FormatWorker`].
2999    ///
3000    /// Like `push_undo`, this clears the redo stack (vim semantics: any
3001    /// new edit invalidates redo).
3002    pub fn set_content_undoable(&mut self, text: &str) {
3003        self.push_undo();
3004        let mut lines: Vec<String> = text.lines().map(|l| l.to_string()).collect();
3005        while lines.last().map(|l| l.is_empty()).unwrap_or(false) {
3006            lines.pop();
3007        }
3008        if lines.is_empty() {
3009            lines.push(String::new());
3010        }
3011        let _ = lines;
3012        crate::types::BufferEdit::replace_all(&mut self.buffer, text);
3013        // Whole-buffer replace supersedes any queued ContentEdits.
3014        self.buffer.clear_pending_content_edits();
3015        self.buffer.set_pending_content_reset(true);
3016        self.mark_content_dirty();
3017    }
3018
3019    /// Drain the pending change log produced by buffer mutations.
3020    ///
3021    /// Returns a `Vec<EditOp>` covering edits applied since the last
3022    /// call. Empty when no edits ran. Pull-model, complementary to
3023    /// [`Editor::take_content_change`] which gives back the new full
3024    /// content.
3025    ///
3026    /// Mapping coverage:
3027    /// - InsertChar / InsertStr → exact `EditOp` with empty range +
3028    ///   replacement.
3029    /// - DeleteRange (`Char` kind) → exact range + empty replacement.
3030    /// - Replace → exact range + new replacement.
3031    /// - DeleteRange (`Line`/`Block`), JoinLines, SplitLines,
3032    ///   InsertBlock, DeleteBlockChunks → best-effort placeholder
3033    ///   covering the touched range. Hosts wanting per-cell deltas
3034    ///   should diff their own `lines()` snapshot.
3035    pub fn take_changes(&mut self) -> Vec<crate::types::Edit> {
3036        self.buffer.take_change_log()
3037    }
3038
3039    /// Read the engine's current settings as a SPEC
3040    /// [`crate::types::Options`].
3041    ///
3042    /// Bridges between the legacy [`Settings`] (which carries fewer
3043    /// fields than SPEC) and the planned 0.1.0 trait surface. Fields
3044    /// not present in `Settings` fall back to vim defaults (e.g.,
3045    /// `expandtab=false`, `wrapscan=true`, `timeout_len=1000ms`).
3046    /// Once trait extraction lands, this becomes the canonical config
3047    /// reader and `Settings` retires.
3048    pub fn current_options(&self) -> crate::types::Options {
3049        crate::types::Options {
3050            shiftwidth: self.settings.shiftwidth as u32,
3051            tabstop: self.settings.tabstop as u32,
3052            softtabstop: self.settings.softtabstop as u32,
3053            textwidth: self.settings.textwidth as u32,
3054            expandtab: self.settings.expandtab,
3055            ignorecase: self.settings.ignore_case,
3056            smartcase: self.settings.smartcase,
3057            wrapscan: self.settings.wrapscan,
3058            wrap: match self.settings.wrap {
3059                hjkl_buffer::Wrap::None => crate::types::WrapMode::None,
3060                hjkl_buffer::Wrap::Char => crate::types::WrapMode::Char,
3061                hjkl_buffer::Wrap::Word => crate::types::WrapMode::Word,
3062            },
3063            readonly: self.settings.readonly,
3064            modifiable: self.settings.modifiable,
3065            autoindent: self.settings.autoindent,
3066            smartindent: self.settings.smartindent,
3067            undo_levels: self.settings.undo_levels,
3068            undo_break_on_motion: self.settings.undo_break_on_motion,
3069            iskeyword: self.settings.iskeyword.clone(),
3070            timeout_len: self.settings.timeout_len,
3071            ..crate::types::Options::default()
3072        }
3073    }
3074
3075    /// Apply a SPEC [`crate::types::Options`] to the engine's settings.
3076    /// Only the fields backed by today's [`Settings`] take effect;
3077    /// remaining options become live once trait extraction wires them
3078    /// through.
3079    pub fn apply_options(&mut self, opts: &crate::types::Options) {
3080        self.settings.shiftwidth = opts.shiftwidth as usize;
3081        self.settings.tabstop = opts.tabstop as usize;
3082        self.settings.softtabstop = opts.softtabstop as usize;
3083        self.settings.textwidth = opts.textwidth as usize;
3084        self.settings.expandtab = opts.expandtab;
3085        self.settings.ignore_case = opts.ignorecase;
3086        self.settings.smartcase = opts.smartcase;
3087        self.settings.wrapscan = opts.wrapscan;
3088        self.settings.wrap = match opts.wrap {
3089            crate::types::WrapMode::None => hjkl_buffer::Wrap::None,
3090            crate::types::WrapMode::Char => hjkl_buffer::Wrap::Char,
3091            crate::types::WrapMode::Word => hjkl_buffer::Wrap::Word,
3092        };
3093        self.settings.readonly = opts.readonly;
3094        self.settings.modifiable = opts.modifiable;
3095        self.settings.autoindent = opts.autoindent;
3096        self.settings.smartindent = opts.smartindent;
3097        self.settings.undo_levels = opts.undo_levels;
3098        self.settings.undo_break_on_motion = opts.undo_break_on_motion;
3099        self.set_iskeyword(opts.iskeyword.clone());
3100        self.settings.timeout_len = opts.timeout_len;
3101        self.settings.number = opts.number;
3102        self.settings.relativenumber = opts.relativenumber;
3103        self.settings.numberwidth = opts.numberwidth;
3104        self.settings.cursorline = opts.cursorline;
3105        self.settings.cursorcolumn = opts.cursorcolumn;
3106        self.settings.signcolumn = opts.signcolumn;
3107        self.settings.foldcolumn = opts.foldcolumn;
3108        self.settings.foldmethod = opts.foldmethod;
3109        self.settings.foldenable = opts.foldenable;
3110        self.settings.foldlevelstart = opts.foldlevelstart;
3111        self.settings.colorcolumn = opts.colorcolumn.clone();
3112        self.settings.scrolloff = opts.scrolloff;
3113        self.settings.sidescrolloff = opts.sidescrolloff;
3114        self.settings.autoreload = opts.autoreload;
3115        self.settings.list = opts.list;
3116        self.settings.listchars = opts.listchars.clone();
3117        self.settings.colorizer = opts.colorizer;
3118        self.settings.colorizer_filetypes = opts.colorizer_filetypes.clone();
3119        self.settings.format_on_save = opts.format_on_save;
3120        self.settings.trim_trailing_whitespace = opts.trim_trailing_whitespace;
3121        self.settings.rainbow_brackets = opts.rainbow_brackets;
3122        self.settings.matchparen = opts.matchparen;
3123    }
3124
3125    /// SPEC-typed highlights for `line`.
3126    ///
3127    /// Two emission modes:
3128    ///
3129    /// - **IncSearch**: the user is typing a `/` or `?` prompt and
3130    ///   `Editor::search_prompt` is `Some`. Live-preview matches of
3131    ///   the in-flight pattern surface as
3132    ///   [`crate::types::HighlightKind::IncSearch`].
3133    /// - **SearchMatch**: the prompt has been committed (or absent)
3134    ///   and the buffer's armed pattern is non-empty. Matches surface
3135    ///   as [`crate::types::HighlightKind::SearchMatch`].
3136    ///
3137    /// Selection / MatchParen / Syntax(id) variants land once the
3138    /// trait extraction routes the FSM's selection set + the host's
3139    /// syntax pipeline through the [`crate::types::Host`] trait.
3140    ///
3141    /// Returns an empty vec when there is nothing to highlight or
3142    /// `line` is out of bounds.
3143    pub fn highlights_for_line(&mut self, line: u32) -> Vec<crate::types::Highlight> {
3144        use crate::types::{Highlight, HighlightKind, Pos};
3145        let row = line as usize;
3146        if row >= buf_row_count(&self.buffer) {
3147            return Vec::new();
3148        }
3149
3150        // Live preview while the prompt is open beats the committed
3151        // pattern.
3152        if let Some(prompt) = self.search_prompt() {
3153            if prompt.text.is_empty() {
3154                return Vec::new();
3155            }
3156            use crate::search::{CaseMode, resolve_case_mode};
3157            let base =
3158                CaseMode::from_options(self.settings().ignore_case, self.settings().smartcase);
3159            let (stripped, mode) = resolve_case_mode(&prompt.text, base);
3160            let src = if mode == CaseMode::Insensitive {
3161                format!("(?i){stripped}")
3162            } else {
3163                stripped
3164            };
3165            let Ok(re) = regex::Regex::new(&src) else {
3166                return Vec::new();
3167            };
3168            let Some(haystack) = buf_line(&self.buffer, row) else {
3169                return Vec::new();
3170            };
3171            return re
3172                .find_iter(&haystack)
3173                .map(|m| Highlight {
3174                    range: Pos {
3175                        line,
3176                        col: m.start() as u32,
3177                    }..Pos {
3178                        line,
3179                        col: m.end() as u32,
3180                    },
3181                    kind: HighlightKind::IncSearch,
3182                })
3183                .collect();
3184        }
3185
3186        if self.search_state.pattern.is_none() {
3187            return Vec::new();
3188        }
3189        let dgen = crate::types::Query::dirty_gen(&self.buffer);
3190        crate::search::search_matches(&self.buffer, &mut self.search_state, dgen, row)
3191            .into_iter()
3192            .map(|(start, end)| Highlight {
3193                range: Pos {
3194                    line,
3195                    col: start as u32,
3196                }..Pos {
3197                    line,
3198                    col: end as u32,
3199                },
3200                kind: HighlightKind::SearchMatch,
3201            })
3202            .collect()
3203    }
3204
3205    /// Build the engine's [`crate::types::RenderFrame`] for the
3206    /// current state. Hosts call this once per redraw and diff
3207    /// across frames.
3208    ///
3209    /// Coarse today — covers mode + cursor + cursor shape + viewport
3210    /// top + line count. SPEC-target fields (selections, highlights,
3211    /// command line, search prompt, status line) land once trait
3212    /// extraction routes them through `SelectionSet` and the
3213    /// `Highlight` pipeline.
3214    pub fn render_frame(&self) -> crate::types::RenderFrame {
3215        use crate::types::{CursorShape, RenderFrame, SnapshotMode};
3216        let (cursor_row, cursor_col) = self.cursor();
3217        // Coarse, not vim: render output must not depend on which discipline
3218        // is installed (#265). CoarseMode is a bijection with SnapshotMode.
3219        let (mode, shape) = match self.coarse_mode() {
3220            crate::CoarseMode::Normal => (SnapshotMode::Normal, CursorShape::Block),
3221            crate::CoarseMode::Insert => (SnapshotMode::Insert, CursorShape::Bar),
3222            crate::CoarseMode::Select => (SnapshotMode::Visual, CursorShape::Block),
3223            crate::CoarseMode::SelectLine => (SnapshotMode::VisualLine, CursorShape::Block),
3224            crate::CoarseMode::SelectBlock => (SnapshotMode::VisualBlock, CursorShape::Block),
3225        };
3226        RenderFrame {
3227            mode,
3228            cursor_row: cursor_row as u32,
3229            cursor_col: cursor_col as u32,
3230            cursor_shape: shape,
3231            viewport_top: self.host.viewport().top_row as u32,
3232            line_count: crate::types::Query::line_count(&self.buffer),
3233        }
3234    }
3235
3236    /// Capture the editor's coarse state into a serde-friendly
3237    /// [`crate::types::EditorSnapshot`].
3238    ///
3239    /// Today's snapshot covers mode, cursor, lines, viewport top.
3240    /// Registers, marks, jump list, undo tree, and full options arrive
3241    /// once phase 5 trait extraction lands the generic
3242    /// `Editor<B: Buffer, H: Host>` constructor — this method's surface
3243    /// stays stable; only the snapshot's internal fields grow.
3244    ///
3245    /// Distinct from the internal `snapshot` used by undo (which
3246    /// returns `(Vec<String>, (usize, usize))`); host-facing
3247    /// persistence goes through this one.
3248    pub fn take_snapshot(&self) -> crate::types::EditorSnapshot {
3249        use crate::types::{EditorSnapshot, SnapshotMode};
3250        let mode = match self.coarse_mode() {
3251            crate::CoarseMode::Normal => SnapshotMode::Normal,
3252            crate::CoarseMode::Insert => SnapshotMode::Insert,
3253            crate::CoarseMode::Select => SnapshotMode::Visual,
3254            crate::CoarseMode::SelectLine => SnapshotMode::VisualLine,
3255            crate::CoarseMode::SelectBlock => SnapshotMode::VisualBlock,
3256        };
3257        let cursor = self.cursor();
3258        let cursor = (cursor.0 as u32, cursor.1 as u32);
3259        let rope = crate::types::Query::rope(&self.buffer);
3260        let lines: Vec<String> = (0..rope.len_lines())
3261            .map(|r| {
3262                let s = rope.line(r).to_string();
3263                if s.ends_with('\n') {
3264                    s[..s.len() - 1].to_string()
3265                } else {
3266                    s
3267                }
3268            })
3269            .collect();
3270        let viewport_top = self.host.viewport().top_row as u32;
3271        let marks = self
3272            .buffer
3273            .marks_cloned()
3274            .into_iter()
3275            .map(|(c, (r, col))| (c, (r as u32, col as u32)))
3276            .collect();
3277        let global_marks = self
3278            .global_marks
3279            .iter()
3280            .map(|(c, &(bid, r, col))| (*c, (bid, r as u32, col as u32)))
3281            .collect();
3282        EditorSnapshot {
3283            version: EditorSnapshot::VERSION,
3284            mode,
3285            cursor,
3286            lines,
3287            viewport_top,
3288            registers: self.registers.lock().unwrap().clone(),
3289            marks,
3290            global_marks,
3291        }
3292    }
3293
3294    /// Restore editor state from an [`EditorSnapshot`]. Returns
3295    /// [`crate::EngineError::SnapshotVersion`] if the snapshot's
3296    /// `version` doesn't match [`EditorSnapshot::VERSION`].
3297    ///
3298    /// Mode is best-effort: `SnapshotMode` only round-trips the
3299    /// status-line summary, not the full FSM state. Visual / Insert
3300    /// mode entry happens through synthetic key dispatch when needed.
3301    pub fn restore_snapshot(
3302        &mut self,
3303        snap: crate::types::EditorSnapshot,
3304    ) -> Result<(), crate::EngineError> {
3305        use crate::types::EditorSnapshot;
3306        if snap.version != EditorSnapshot::VERSION {
3307            return Err(crate::EngineError::SnapshotVersion(
3308                snap.version,
3309                EditorSnapshot::VERSION,
3310            ));
3311        }
3312        let text = snap.lines.join("\n");
3313        self.set_content(&text);
3314        self.jump_cursor(snap.cursor.0 as usize, snap.cursor.1 as usize);
3315        self.host.viewport_mut().top_row = snap.viewport_top as usize;
3316        *self.registers.lock().unwrap() = snap.registers;
3317        self.buffer.set_marks(
3318            snap.marks
3319                .into_iter()
3320                .map(|(c, (r, col))| (c, (r as usize, col as usize)))
3321                .collect(),
3322        );
3323        self.global_marks = snap
3324            .global_marks
3325            .into_iter()
3326            .map(|(c, (bid, r, col))| (c, (bid, r as usize, col as usize)))
3327            .collect();
3328        Ok(())
3329    }
3330
3331    /// Install `text` as the pending yank buffer so the next `p`/`P` pastes
3332    /// it. Linewise is inferred from a trailing newline, matching how `yy`/`dd`
3333    /// shape their payload.
3334    pub fn seed_yank(&mut self, text: String) {
3335        let linewise = text.ends_with('\n');
3336        self.yank_linewise = linewise;
3337        self.registers.lock().unwrap().unnamed = crate::registers::Slot { text, linewise };
3338    }
3339
3340    /// Scroll the viewport down by `rows`. The cursor stays on its
3341    /// absolute line (vim convention) unless the scroll would take it
3342    /// off-screen — in that case it's clamped to the first row still
3343    /// visible.
3344    pub fn scroll_down(&mut self, rows: i16) {
3345        self.scroll_viewport(rows);
3346    }
3347
3348    /// Scroll the viewport up by `rows`. Cursor stays unless it would
3349    /// fall off the bottom of the new viewport, then clamp to the
3350    /// bottom-most visible row.
3351    pub fn scroll_up(&mut self, rows: i16) {
3352        self.scroll_viewport(-rows);
3353    }
3354
3355    /// Scroll the viewport right by `cols` columns. Only the horizontal
3356    /// offset (`top_col`) moves — the cursor is NOT adjusted (matches
3357    /// vim's `zl` behaviour for horizontal scroll without wrap).
3358    pub fn scroll_right(&mut self, cols: i16) {
3359        let vp = self.host.viewport_mut();
3360        let cols_i = cols as isize;
3361        let new_top = (vp.top_col as isize + cols_i).max(0) as usize;
3362        vp.top_col = new_top;
3363    }
3364
3365    /// Scroll the viewport left by `cols` columns. Delegates to
3366    /// `scroll_right` with a negated argument so the floor-at-zero
3367    /// clamp is shared.
3368    pub fn scroll_left(&mut self, cols: i16) {
3369        self.scroll_right(-cols);
3370    }
3371
3372    /// Scroll the viewport so the cursor stays at least `scrolloff`
3373    /// rows from each edge. Replaces the bare
3374    /// `Buffer::ensure_cursor_visible` call at end-of-step so motions
3375    /// don't park the cursor on the very last visible row.
3376    pub fn ensure_cursor_in_scrolloff(&mut self) {
3377        let height = self.viewport_height.load(Ordering::Relaxed) as usize;
3378        if height == 0 {
3379            // 0.0.42 (Patch C-δ.7): viewport math lifted onto engine
3380            // free fns over `B: Query [+ Cursor]` + `&dyn FoldProvider`.
3381            // Disjoint-field borrow split: `self.buffer` (immutable via
3382            // `folds` snapshot + cursor) and `self.host` (mutable
3383            // viewport ref) live on distinct struct fields, so one
3384            // statement satisfies the borrow checker.
3385            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
3386            crate::viewport_math::ensure_cursor_visible(
3387                &self.buffer,
3388                &folds,
3389                self.host.viewport_mut(),
3390            );
3391            return;
3392        }
3393        // Cap margin at (height - 1) / 2 so the upper + lower bands
3394        // can't overlap on tiny windows (margin=5 + height=10 would
3395        // otherwise produce contradictory clamp ranges).
3396        let margin = self.settings.scrolloff.min(height.saturating_sub(1) / 2);
3397        // Screen rows ≠ doc rows only under soft-wrap (a doc row spans many
3398        // screen lines) or folds (a closed fold collapses many doc rows to
3399        // one); doc-row margin math drifts in those cases. Dispatch:
3400        //   • wrap            → the incremental screen-row walk.
3401        //   • folds, no wrap  → the O(height) fold-aware clamp below.
3402        //   • neither         → the fast O(1) doc-row math (every plain j/k/G).
3403        let wrapped = !matches!(self.host.viewport().wrap, hjkl_buffer::Wrap::None);
3404        if wrapped {
3405            self.ensure_scrolloff_vertical(height, margin);
3406            return;
3407        }
3408        if !self.buffer.folds().is_empty() {
3409            self.ensure_scrolloff_folds_nowrap(height, margin);
3410            // Column-side (horizontal) scroll only — keep the fold-aware
3411            // top_row by snapshotting it across `ensure_visible`.
3412            let cursor = buf_cursor_pos(&self.buffer);
3413            let saved_top = self.host.viewport().top_row;
3414            self.host.viewport_mut().ensure_visible(cursor);
3415            self.host.viewport_mut().top_row = saved_top;
3416            return;
3417        }
3418        let cursor_row = buf_cursor_row(&self.buffer);
3419        let last_row = buf_row_count(&self.buffer).saturating_sub(1);
3420        let v = self.host.viewport_mut();
3421        // Top edge: cursor_row should sit at >= top_row + margin.
3422        if cursor_row < v.top_row + margin {
3423            v.top_row = cursor_row.saturating_sub(margin);
3424        }
3425        // Bottom edge: cursor_row should sit at <= top_row + height - 1 - margin.
3426        let max_bottom = height.saturating_sub(1).saturating_sub(margin);
3427        if cursor_row > v.top_row + max_bottom {
3428            v.top_row = cursor_row.saturating_sub(max_bottom);
3429        }
3430        // Clamp top_row so we never scroll past the buffer's bottom.
3431        let max_top = last_row.saturating_sub(height.saturating_sub(1));
3432        if v.top_row > max_top {
3433            v.top_row = max_top;
3434        }
3435        // Column-side scroll (vim default `sidescrolloff = 0`).
3436        let cursor = buf_cursor_pos(&self.buffer);
3437        self.host.viewport_mut().ensure_visible(cursor);
3438    }
3439
3440    /// Fold-aware vertical scrolloff for `Wrap::None`, in **O(height)**.
3441    ///
3442    /// A closed fold collapses its body to one screen row, so the cursor's
3443    /// screen row is the count of *visible* rows above it — not the doc-row
3444    /// delta. Instead of re-walking that count on every candidate `top_row`
3445    /// (the incremental [`Self::ensure_scrolloff_vertical`], O(n²) on a big
3446    /// jump like `G` over a fold-heavy file), compute the valid `top_row`
3447    /// window directly: at most `height-1-margin` visible rows may sit above
3448    /// the cursor (bottom edge) and at least `margin` (top edge). Walk those
3449    /// two bounds up from the cursor via `prev_visible_row`, clamp the current
3450    /// `top_row` into the window, then clamp to `max_top_for_height` so the
3451    /// buffer's bottom never leaves blank rows. Each walk is bounded by
3452    /// `height`, so the whole thing is O(height) regardless of jump distance.
3453    fn ensure_scrolloff_folds_nowrap(&mut self, height: usize, margin: usize) {
3454        let cursor_row = buf_cursor_row(&self.buffer);
3455        let max_csr = height.saturating_sub(1).saturating_sub(margin);
3456        // `top_lo`: the row `max_csr` visible rows above the cursor — `top_row`
3457        // must be >= this to keep the cursor within the bottom margin.
3458        let mut top_lo = cursor_row;
3459        for _ in 0..max_csr {
3460            match self.buffer.prev_visible_row(top_lo) {
3461                Some(p) => top_lo = p,
3462                None => break,
3463            }
3464        }
3465        // `top_hi`: the row `margin` visible rows above the cursor — `top_row`
3466        // must be <= this to keep the cursor below the top margin.
3467        let mut top_hi = cursor_row;
3468        for _ in 0..margin {
3469            match self.buffer.prev_visible_row(top_hi) {
3470                Some(p) => top_hi = p,
3471                None => break,
3472            }
3473        }
3474        // `max_csr >= margin` (margin is capped at (height-1)/2), so
3475        // `top_lo <= top_hi` and the clamp range is well-formed.
3476        let cur = self.host.viewport().top_row;
3477        let mut new_top = cur.clamp(top_lo, top_hi);
3478        let max_top = {
3479            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
3480            crate::viewport_math::max_top_for_height(
3481                &self.buffer,
3482                &folds,
3483                self.host.viewport(),
3484                height,
3485            )
3486        };
3487        if new_top > max_top {
3488            new_top = max_top;
3489        }
3490        self.host.viewport_mut().top_row = new_top;
3491    }
3492
3493    /// Screen-row-aware vertical scrolloff. Walks `top_row` one visible
3494    /// doc row at a time so the cursor's *screen* row stays inside
3495    /// `[margin, height - 1 - margin]`, then clamps `top_row` so the
3496    /// buffer's bottom never leaves blank rows below it.
3497    ///
3498    /// Correct under BOTH soft-wrap (a doc row spans many screen lines)
3499    /// and folds (a closed fold collapses many doc rows to one screen
3500    /// row): [`crate::viewport_math::cursor_screen_row_from`] counts
3501    /// visible/wrapped screen rows, so doc-row arithmetic can't drift the
3502    /// margin around a fold. Horizontal (column) scroll is the caller's
3503    /// job — this only moves `top_row`.
3504    fn ensure_scrolloff_vertical(&mut self, height: usize, margin: usize) {
3505        let cursor_row = buf_cursor_row(&self.buffer);
3506        // Step 1 — cursor above viewport: snap top to cursor row,
3507        // then we'll fix up the margin below.
3508        if cursor_row < self.host.viewport().top_row {
3509            let v = self.host.viewport_mut();
3510            v.top_row = cursor_row;
3511            v.top_col = 0;
3512        }
3513        // Step 2 — push top forward until cursor's screen row is
3514        // within the bottom margin (`csr <= height - 1 - margin`).
3515        // 0.0.33 (Patch C-γ): fold-iteration goes through the
3516        // [`crate::types::FoldProvider`] surface via
3517        // [`crate::buffer_impl::BufferFoldProvider`]. 0.0.34 (Patch
3518        // C-δ.1): `cursor_screen_row` / `max_top_for_height` now take
3519        // a `&Viewport` parameter; the host owns the viewport, so the
3520        // disjoint `(self.host, self.buffer)` borrows split cleanly.
3521        let max_csr = height.saturating_sub(1).saturating_sub(margin);
3522        loop {
3523            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
3524            let top = self.host.viewport().top_row;
3525            let csr = crate::viewport_math::cursor_screen_row_from(
3526                &self.buffer,
3527                &folds,
3528                self.host.viewport(),
3529                top,
3530            )
3531            .unwrap_or(0);
3532            if csr <= max_csr {
3533                break;
3534            }
3535            let row_count = buf_row_count(&self.buffer);
3536            let next = {
3537                let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
3538                <crate::buffer_impl::BufferFoldProvider<'_> as crate::types::FoldProvider>::next_visible_row(&folds, top, row_count)
3539            };
3540            let Some(next) = next else {
3541                break;
3542            };
3543            // Don't walk past the cursor's row.
3544            if next > cursor_row {
3545                self.host.viewport_mut().top_row = cursor_row;
3546                break;
3547            }
3548            self.host.viewport_mut().top_row = next;
3549        }
3550        // Step 3 — pull top backward until cursor's screen row is
3551        // past the top margin (`csr >= margin`).
3552        loop {
3553            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
3554            let top = self.host.viewport().top_row;
3555            let csr = crate::viewport_math::cursor_screen_row_from(
3556                &self.buffer,
3557                &folds,
3558                self.host.viewport(),
3559                top,
3560            )
3561            .unwrap_or(0);
3562            if csr >= margin {
3563                break;
3564            }
3565            let prev = {
3566                let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
3567                <crate::buffer_impl::BufferFoldProvider<'_> as crate::types::FoldProvider>::prev_visible_row(&folds, top)
3568            };
3569            let Some(prev) = prev else {
3570                break;
3571            };
3572            self.host.viewport_mut().top_row = prev;
3573        }
3574        // Step 4 — clamp top so the buffer's bottom doesn't leave
3575        // blank rows below it. `max_top_for_height` walks segments
3576        // backward from the last row until it accumulates `height`
3577        // screen rows.
3578        let max_top = {
3579            let folds = crate::buffer_impl::BufferFoldProvider::new(&self.buffer);
3580            crate::viewport_math::max_top_for_height(
3581                &self.buffer,
3582                &folds,
3583                self.host.viewport(),
3584                height,
3585            )
3586        };
3587        if self.host.viewport().top_row > max_top {
3588            self.host.viewport_mut().top_row = max_top;
3589        }
3590        self.host.viewport_mut().top_col = 0;
3591    }
3592
3593    fn scroll_viewport(&mut self, delta: i16) {
3594        if delta == 0 {
3595            return;
3596        }
3597        // Bump the host viewport's top within bounds.
3598        let total_rows = buf_row_count(&self.buffer) as isize;
3599        let height = self.viewport_height.load(Ordering::Relaxed) as usize;
3600        let cur_top = self.host.viewport().top_row as isize;
3601        let new_top = (cur_top + delta as isize)
3602            .max(0)
3603            .min((total_rows - 1).max(0)) as usize;
3604        self.host.viewport_mut().top_row = new_top;
3605        // Mirror to textarea so its viewport reads (still consumed by
3606        // a couple of helpers) stay accurate.
3607        let _ = cur_top;
3608        if height == 0 {
3609            return;
3610        }
3611        // Apply scrolloff: keep the cursor at least scrolloff rows
3612        // from the visible viewport edges.
3613        let (cursor_row, cursor_col) = buf_cursor_rc(&self.buffer);
3614        let margin = self.settings.scrolloff.min(height / 2);
3615        let min_row = new_top + margin;
3616        let max_row = new_top + height.saturating_sub(1).saturating_sub(margin);
3617        let target_row = cursor_row.clamp(min_row, max_row.max(min_row));
3618        if target_row != cursor_row {
3619            let line_len = buf_line(&self.buffer, target_row)
3620                .map(|l| l.chars().count())
3621                .unwrap_or(0);
3622            let target_col = cursor_col.min(line_len.saturating_sub(1));
3623            buf_set_cursor_rc(&mut self.buffer, target_row, target_col);
3624        }
3625    }
3626
3627    pub fn goto_line(&mut self, line: usize) {
3628        let row = line.saturating_sub(1);
3629        let max = buf_row_count(&self.buffer).saturating_sub(1);
3630        let target = row.min(max);
3631        // If the target row is hidden inside one or more closed folds, open
3632        // every fold that collapses it so the landing line is actually
3633        // visible — a jump to an unseen row is useless. `reveal_row` opens
3634        // all hiding folds (outer + nested) in one pass; `open_fold_at` /
3635        // `FoldOp::OpenAt` can't, because they only act on the first fold
3636        // containing the row and so can never reach a nested inner fold.
3637        self.buffer.reveal_row(target);
3638        buf_set_cursor_rc(&mut self.buffer, target, 0);
3639        // Vim: `:N` / `+N` jump scrolls the viewport too — without this
3640        // the cursor lands off-screen and the user has to scroll
3641        // manually to see it.
3642        self.ensure_cursor_in_scrolloff();
3643    }
3644
3645    /// Scroll so the cursor row lands at the given viewport position:
3646    /// `Center` → middle row, `Top` → first row, `Bottom` → last row.
3647    /// Cursor stays on its absolute line; only the viewport moves.
3648    pub fn scroll_cursor_to(&mut self, pos: CursorScrollTarget) {
3649        let height = self.viewport_height.load(Ordering::Relaxed) as usize;
3650        if height == 0 {
3651            return;
3652        }
3653        let cur_row = buf_cursor_row(&self.buffer);
3654        let cur_top = self.host.viewport().top_row;
3655        // Scrolloff awareness: `zt` lands the cursor at the top edge
3656        // of the viable area (top + margin), `zb` at the bottom edge
3657        // (top + height - 1 - margin). Match the cap used by
3658        // `ensure_cursor_in_scrolloff` so contradictory bounds are
3659        // impossible on tiny viewports.
3660        let margin = self.settings.scrolloff.min(height.saturating_sub(1) / 2);
3661        let new_top = match pos {
3662            CursorScrollTarget::Center => cur_row.saturating_sub(height / 2),
3663            CursorScrollTarget::Top => cur_row.saturating_sub(margin),
3664            CursorScrollTarget::Bottom => {
3665                cur_row.saturating_sub(height.saturating_sub(1).saturating_sub(margin))
3666            }
3667        };
3668        if new_top == cur_top {
3669            return;
3670        }
3671        self.host.viewport_mut().top_row = new_top;
3672    }
3673
3674    /// Jump the cursor to the given 1-based line/column, clamped to the document.
3675    pub fn jump_to(&mut self, line: usize, col: usize) {
3676        let r = line.saturating_sub(1);
3677        let max_row = buf_row_count(&self.buffer).saturating_sub(1);
3678        let r = r.min(max_row);
3679        let line_len = buf_line(&self.buffer, r)
3680            .map(|l| l.chars().count())
3681            .unwrap_or(0);
3682        let c = col.saturating_sub(1).min(line_len);
3683        buf_set_cursor_rc(&mut self.buffer, r, c);
3684    }
3685
3686    // ── Host-agnostic doc-coord mouse primitives (Phase 1 of issue #114) ─────
3687    //
3688    // These primitives operate on document (row, col) coordinates that the HOST
3689    // computes from its own layout knowledge (cell geometry for the TUI host,
3690    // pixel geometry for the future GUI host). The engine has no u16 terminal
3691    // assumption here — it just moves the cursor in doc-space.
3692
3693    /// Set the cursor to the given doc-space `(row, col)`, clamped to the
3694    /// document bounds. Hosts use this for programmatic cursor placement and
3695    /// as the building block for the mouse-click path.
3696    ///
3697    /// `col` may equal `line.chars().count()` (Insert-mode "one past end"
3698    /// position); values beyond that are clamped to `char_count`.
3699    pub fn set_cursor_doc(&mut self, row: usize, col: usize) {
3700        let max_row = buf_row_count(&self.buffer).saturating_sub(1);
3701        let r = row.min(max_row);
3702        let line_len = buf_line(&self.buffer, r)
3703            .map(|l| l.chars().count())
3704            .unwrap_or(0);
3705        let c = col.min(line_len);
3706        buf_set_cursor_rc(&mut self.buffer, r, c);
3707    }
3708
3709    /// Extend an in-progress mouse drag to doc-space `(row, col)`.
3710    ///
3711    /// Moves the live cursor; the Visual anchor stays where
3712    /// [`Editor::mouse_begin_drag`] set it. Call after the host has
3713    /// translated the drag position to doc coordinates.
3714    pub fn mouse_extend_drag_doc(&mut self, row: usize, col: usize) {
3715        self.set_cursor_doc(row, col);
3716    }
3717
3718    pub fn insert_str(&mut self, text: &str) {
3719        let pos = crate::types::Cursor::cursor(&self.buffer);
3720        crate::types::BufferEdit::insert_at(&mut self.buffer, pos, text);
3721        self.push_buffer_content_to_textarea();
3722        self.mark_content_dirty();
3723    }
3724
3725    pub fn accept_completion(&mut self, completion: &str) {
3726        use crate::types::{BufferEdit, Cursor as CursorTrait, Pos};
3727        let cursor_pos = CursorTrait::cursor(&self.buffer);
3728        let cursor_row = cursor_pos.line as usize;
3729        let cursor_col = cursor_pos.col as usize;
3730        let line = buf_line(&self.buffer, cursor_row).unwrap_or_default();
3731        let chars: Vec<char> = line.chars().collect();
3732        let prefix_len = chars[..cursor_col.min(chars.len())]
3733            .iter()
3734            .rev()
3735            .take_while(|c| c.is_alphanumeric() || **c == '_')
3736            .count();
3737        if prefix_len > 0 {
3738            let start = Pos {
3739                line: cursor_row as u32,
3740                col: (cursor_col - prefix_len) as u32,
3741            };
3742            BufferEdit::delete_range(&mut self.buffer, start..cursor_pos);
3743        }
3744        let cursor = CursorTrait::cursor(&self.buffer);
3745        BufferEdit::insert_at(&mut self.buffer, cursor, completion);
3746        self.push_buffer_content_to_textarea();
3747        self.mark_content_dirty();
3748    }
3749
3750    /// Capture the buffer state for undo / redo.  Uses
3751    /// [`Query::content_joined`], which the `Buffer` impl caches as an
3752    /// `Arc<String>` against `dirty_gen` — so when LSP / git / syntax
3753    /// already joined this generation, the snapshot is an `Arc::clone`
3754    /// (one ptr bump). Previously this cloned every line into a
3755    /// `Vec<String>` (162 k allocations on a 162 k-row buffer) and the
3756    /// matching `restore` re-joined them — samply showed it at ~9 % of
3757    /// CPU on a big-paste session.
3758    pub(super) fn snapshot(&self) -> (ropey::Rope, (usize, usize)) {
3759        use crate::types::Query;
3760        let rc = buf_cursor_rc(&self.buffer);
3761        (Query::rope(&self.buffer), rc)
3762    }
3763
3764    // ── Undo / redo (discipline-agnostic, #265) ──────────────────────────────
3765    //
3766    // The rope-level work is generic — every discipline undoes. The only
3767    // discipline-specific part is what state the editor is left in afterwards,
3768    // which goes through `DisciplineState::reset_to_idle` plus a coarse cursor
3769    // clamp, so the engine never names vim.
3770
3771    /// Rope-level undo, then return the discipline to idle.
3772    fn undo_core(&mut self) {
3773        if let Some(entry) = self.buffer.pop_undo_entry() {
3774            let (cur_rope, cur_cursor) = self.snapshot();
3775            self.buffer.push_redo_entry(hjkl_buffer::UndoEntry {
3776                rope: cur_rope,
3777                cursor: cur_cursor,
3778                timestamp: entry.timestamp,
3779            });
3780            self.restore_rope(entry.rope, entry.cursor);
3781        }
3782        self.settle_after_history_jump();
3783    }
3784
3785    /// Rope-level redo, then return the discipline to idle.
3786    fn redo_core(&mut self) {
3787        if let Some(entry) = self.buffer.pop_redo_entry() {
3788            let (cur_rope, cur_cursor) = self.snapshot();
3789            let before = cur_rope.clone();
3790            self.buffer.push_undo_entry(hjkl_buffer::UndoEntry {
3791                rope: cur_rope,
3792                cursor: cur_cursor,
3793                timestamp: entry.timestamp,
3794            });
3795            self.cap_undo();
3796            self.restore_rope(entry.rope, entry.cursor);
3797            // Park the cursor at the START of the reapplied change rather than
3798            // the end-of-insert position stored in the redo snapshot (vim
3799            // parity). Recompute from the first differing character.
3800            let after = crate::types::Query::rope(&self.buffer);
3801            if let Some((row, col)) = first_diff_pos(&before, &after) {
3802                buf_set_cursor_rc(&mut self.buffer, row, col);
3803                self.push_buffer_cursor_to_textarea();
3804            }
3805        }
3806        self.settle_after_history_jump();
3807    }
3808
3809    /// Leave the editor in a known resting state after jumping through history
3810    /// (undo / redo) or after a `:!` filter rewrote the buffer.
3811    ///
3812    /// Asks the installed discipline to put its *mode* back to idle — without
3813    /// discarding an open insert session, which vscode-mode undo depends on —
3814    /// then clamps the cursor to a valid column.
3815    pub(crate) fn settle_after_history_jump(&mut self) {
3816        self.discipline.reset_mode_after_history();
3817        // Undo / redo restore a whole snapshot: the secondary selections were
3818        // computed against a document that no longer exists, and nothing tracked
3819        // them across the rewind. Drop them rather than leave carets pointing at
3820        // text that moved — the same "drop, never guess" rule `selection_shift`
3821        // applies to a single untrackable edit.
3822        self.extra_selections.clear();
3823        // Unconditional clamp: the restored cursor came from a snapshot that may
3824        // have been taken mid-insert and can sit one past the last valid column.
3825        let (row, col) = self.cursor();
3826        let max_col = buf_line_chars(&self.buffer, row).saturating_sub(1);
3827        if col > max_col {
3828            buf_set_cursor_rc(&mut self.buffer, row, max_col);
3829            self.push_buffer_cursor_to_textarea();
3830        }
3831    }
3832
3833    /// Walk one step back through the undo history. Equivalent to the
3834    /// user pressing `u` in normal mode. Drains the most recent undo
3835    /// entry and pushes it onto the redo stack.
3836    pub fn undo(&mut self) {
3837        self.undo_core();
3838    }
3839
3840    /// Walk one step forward through the redo history. Equivalent to
3841    /// `<C-r>` in normal mode.
3842    pub fn redo(&mut self) {
3843        self.redo_core();
3844    }
3845
3846    /// Undo `n` steps. Returns the number of steps actually applied
3847    /// (bounded by undo stack size).
3848    pub fn earlier_by_steps(&mut self, n: usize) -> usize {
3849        let mut count = 0;
3850        for _ in 0..n {
3851            if self.buffer.undo_stack_is_empty() {
3852                break;
3853            }
3854            self.undo_core();
3855            count += 1;
3856        }
3857        count
3858    }
3859
3860    /// Redo `n` steps. Returns the number of steps actually applied
3861    /// (bounded by redo stack size).
3862    pub fn later_by_steps(&mut self, n: usize) -> usize {
3863        let mut count = 0;
3864        for _ in 0..n {
3865            if self.buffer.redo_stack_is_empty() {
3866                break;
3867            }
3868            self.redo_core();
3869            count += 1;
3870        }
3871        count
3872    }
3873
3874    /// Undo back until the next-to-pop entry's timestamp is at or before
3875    /// `target`. Entries whose timestamp is strictly greater than `target`
3876    /// are popped (undone). Returns the number of steps applied.
3877    ///
3878    /// Vim `:earlier Ns` semantics: `target = SystemTime::now() - N seconds`.
3879    pub fn earlier_by_time(&mut self, target: SystemTime) -> usize {
3880        let mut count = 0;
3881        loop {
3882            match self.buffer.peek_undo_timestamp() {
3883                None => break,
3884                Some(ts) => {
3885                    if ts <= target {
3886                        break;
3887                    }
3888                }
3889            }
3890            self.undo_core();
3891            count += 1;
3892        }
3893        count
3894    }
3895
3896    /// Redo forward while the next-to-pop redo entry's timestamp is at
3897    /// or before `target`. Returns the number of steps applied.
3898    ///
3899    /// Vim `:later Ns` semantics: `target = current_state_time + N seconds`.
3900    pub fn later_by_time(&mut self, target: SystemTime) -> usize {
3901        let mut count = 0;
3902        loop {
3903            match self.buffer.peek_redo_timestamp() {
3904                None => break,
3905                Some(ts) => {
3906                    if ts > target {
3907                        break;
3908                    }
3909                }
3910            }
3911            self.redo_core();
3912            count += 1;
3913        }
3914        count
3915    }
3916
3917    /// Snapshot current buffer state onto the undo stack and clear
3918    /// the redo stack. Bounded by `settings.undo_levels` — older
3919    /// entries pruned. Call before any group of buffer mutations the
3920    /// user might want to undo as a single step.
3921    pub fn push_undo(&mut self) {
3922        self.push_undo_at(SystemTime::now());
3923    }
3924
3925    /// Like [`push_undo`] but uses a caller-supplied timestamp. Used by
3926    /// tests that need deterministic time values without `sleep`.
3927    #[doc(hidden)]
3928    pub fn push_undo_at(&mut self, timestamp: SystemTime) {
3929        let (rope, cursor) = self.snapshot();
3930        self.buffer.push_undo_entry(hjkl_buffer::UndoEntry {
3931            rope,
3932            cursor,
3933            timestamp,
3934        });
3935        self.cap_undo();
3936        self.buffer.clear_redo();
3937    }
3938
3939    /// Trim the undo stack down to `settings.undo_levels`, dropping
3940    /// the oldest entries. `undo_levels == 0` is treated as
3941    /// "unlimited" (vim's 0-means-no-undo semantics intentionally
3942    /// skipped — guarding with `> 0` is one line shorter than gating
3943    /// the cap path with an explicit zero-check above the call site).
3944    pub(crate) fn cap_undo(&mut self) {
3945        let cap = self.settings.undo_levels as usize;
3946        self.buffer.cap_undo(cap);
3947    }
3948
3949    /// Test-only accessor for the undo stack length.
3950    #[doc(hidden)]
3951    pub fn undo_stack_len(&self) -> usize {
3952        self.buffer.undo_stack_len()
3953    }
3954
3955    /// Replace the buffer with `lines` joined by `\n` and set the
3956    /// cursor to `cursor`. Used by undo / `:e!` / snapshot restore
3957    /// paths. Marks the editor dirty.
3958    ///
3959    /// Emits a single whole-buffer `ContentEdit` describing the
3960    /// transition so the syntax layer can apply it as an `InputEdit`
3961    /// on the retained tree and run an INCREMENTAL parse — tree-sitter
3962    /// reuses unchanged subtrees and `Tree::changed_ranges` reports
3963    /// just the bytes that differ, which lets the install path walk
3964    /// only the changed rows instead of the full viewport. Big undos
3965    /// that revert a large paste now refresh in ~1ms per affected
3966    /// row instead of a ~30ms full-viewport sync walk.
3967    pub fn restore(&mut self, lines: Vec<String>, cursor: (usize, usize)) {
3968        let text = lines.join("\n");
3969        self.restore_text(&text, cursor);
3970    }
3971
3972    /// Restore the buffer from a `ropey::Rope` snapshot. Used by undo /
3973    /// redo: snapshots are stored as `Rope` (O(1) Arc-clone via
3974    /// `Buffer::rope()`), so this avoids the full-document `to_string`
3975    /// materialization that the old `Arc<String>` snapshot path forced
3976    /// on every undo group boundary.
3977    ///
3978    /// Internally materializes the rope to a `String` for `restore_text`
3979    /// — paying the cost on the restore side instead of the snapshot
3980    /// side trades one ~3 MB build per undo for none-per-snapshot. Undo
3981    /// is user-initiated and rare; snapshots fire on every `i` / `o`.
3982    pub fn restore_rope(&mut self, rope: ropey::Rope, cursor: (usize, usize)) {
3983        let text = rope.to_string();
3984        self.restore_text(&text, cursor);
3985    }
3986
3987    fn restore_text(&mut self, text: &str, cursor: (usize, usize)) {
3988        // Diff the old rope (O(1) Arc-clone) against the incoming text
3989        // to emit a minimal ContentEdit — without it the syntax layer's
3990        // tree.edit() marks the whole document changed and tree-sitter
3991        // cold-parses on every undo.
3992        let old_rope = self.buffer.rope();
3993        let edit = minimal_content_edit_rope(&old_rope, text);
3994
3995        crate::types::BufferEdit::replace_all(&mut self.buffer, text);
3996        buf_set_cursor_rc(&mut self.buffer, cursor.0, cursor.1);
3997
3998        // Bulk replace supersedes any prior queued edits.
3999        self.buffer.clear_pending_content_edits();
4000        self.buffer.push_pending_content_edit(edit);
4001        self.mark_content_dirty();
4002    }
4003
4004    // ─── Range-query helpers for partial-format dispatch (#119) ─────────────
4005
4006    /// Drain the row range set by the most recent auto-indent operation.
4007    ///
4008    /// Returns `Some((top_row, bot_row))` (inclusive) on the first call after
4009    /// an `=` / `==` / `=G` / Visual-`=` operator, then clears the stored
4010    /// value so a subsequent call returns `None`. The host (e.g. `apps/hjkl`)
4011    /// uses this to arm a brief visual flash over the reindented rows.
4012    pub fn take_last_indent_range(&mut self) -> Option<(usize, usize)> {
4013        self.last_indent_range.take()
4014    }
4015
4016    /// Filter rows `top_row..=bot_row` through an external shell command.
4017    ///
4018    /// Spawns `sh -c "<command>"` (or `cmd /C "<command>"` on Windows), pipes
4019    /// the selected lines (joined by `\n`) to stdin, and waits up to
4020    /// `timeout_secs` seconds (default 10) for the process to finish.
4021    ///
4022    /// On success: the rows are replaced with stdout. No trailing-newline trim.
4023    /// On non-zero exit, spawn failure, or timeout: returns `Err(stderr_or_msg)`
4024    /// without mutating the buffer.
4025    ///
4026    /// `top_row` and `bot_row` are clamped to the buffer's valid row range.
4027    pub fn filter_range(
4028        &mut self,
4029        top_row: usize,
4030        bot_row: usize,
4031        command: &str,
4032        timeout_secs: Option<u64>,
4033    ) -> Result<(), String> {
4034        use std::io::Write;
4035        use std::process::{Command, Stdio};
4036        use std::thread;
4037        use std::time::Instant;
4038
4039        let timeout = std::time::Duration::from_secs(timeout_secs.unwrap_or(10));
4040        let rope = crate::types::Query::rope(self.buffer());
4041        let line_count = rope.len_lines();
4042        let top = top_row.min(line_count.saturating_sub(1));
4043        let bot = bot_row.min(line_count.saturating_sub(1));
4044        let (top, bot) = (top.min(bot), top.max(bot));
4045        let input_text = crate::rope_util::rope_row_range_str(&rope, top, bot);
4046        // Materialized for the splice-back after the command succeeds.
4047        let lines = crate::rope_util::rope_to_lines_vec(&rope);
4048
4049        tracing::debug!(
4050            top_row = top,
4051            bot_row = bot,
4052            command = command,
4053            "filter_range: spawning shell command"
4054        );
4055
4056        #[cfg(not(windows))]
4057        let mut child = Command::new("sh")
4058            .args(["-c", command])
4059            .stdin(Stdio::piped())
4060            .stdout(Stdio::piped())
4061            .stderr(Stdio::piped())
4062            .spawn()
4063            .map_err(|e| format!("spawn failed: {e}"))?;
4064
4065        #[cfg(windows)]
4066        let mut child = Command::new("cmd")
4067            .args(["/C", command])
4068            .stdin(Stdio::piped())
4069            .stdout(Stdio::piped())
4070            .stderr(Stdio::piped())
4071            .spawn()
4072            .map_err(|e| format!("spawn failed: {e}"))?;
4073
4074        // Write stdin on a thread to avoid deadlock when output > pipe buffer.
4075        let mut stdin = child.stdin.take().ok_or("no stdin handle")?;
4076        let input_bytes = input_text.into_bytes();
4077        thread::spawn(move || {
4078            let _ = stdin.write_all(&input_bytes);
4079            // stdin drops here, signalling EOF to the child.
4080        });
4081
4082        // Drain stdout/stderr on separate threads so the child's pipes don't
4083        // fill and deadlock the child. Keep `child` here so we can kill it on
4084        // timeout.
4085        let mut stdout_pipe = child.stdout.take().ok_or("no stdout handle")?;
4086        let mut stderr_pipe = child.stderr.take().ok_or("no stderr handle")?;
4087        let stdout_thread = thread::spawn(move || {
4088            let mut buf = Vec::new();
4089            let _ = std::io::Read::read_to_end(&mut stdout_pipe, &mut buf);
4090            buf
4091        });
4092        let stderr_thread = thread::spawn(move || {
4093            let mut buf = Vec::new();
4094            let _ = std::io::Read::read_to_end(&mut stderr_pipe, &mut buf);
4095            buf
4096        });
4097
4098        // Poll try_wait until exit or timeout. On timeout: SIGKILL the child
4099        // (std Child::kill sends SIGKILL on Unix / TerminateProcess on Windows).
4100        // A proper TERM→KILL escalation would need nix/libc; skip for v1.
4101        let start = Instant::now();
4102        let status = loop {
4103            match child.try_wait() {
4104                Ok(Some(status)) => break status,
4105                Ok(None) => {
4106                    if start.elapsed() >= timeout {
4107                        tracing::debug!(command, "filter_range: timeout — killing child");
4108                        let _ = child.kill();
4109                        let _ = child.wait(); // reap so the OS can free resources
4110                        return Err(format!("command timed out after {}s", timeout.as_secs()));
4111                    }
4112                    thread::sleep(std::time::Duration::from_millis(20));
4113                }
4114                Err(e) => return Err(format!("wait failed: {e}")),
4115            }
4116        };
4117
4118        let stdout_bytes = stdout_thread.join().unwrap_or_default();
4119        let stderr_bytes = stderr_thread.join().unwrap_or_default();
4120
4121        if !status.success() {
4122            let stderr = String::from_utf8_lossy(&stderr_bytes).into_owned();
4123            tracing::debug!(
4124                command,
4125                exit_code = ?status.code(),
4126                "filter_range: command exited with non-zero status"
4127            );
4128            return Err(if stderr.is_empty() {
4129                format!("command exited with status {}", status.code().unwrap_or(-1))
4130            } else {
4131                stderr
4132            });
4133        }
4134
4135        let stdout = String::from_utf8_lossy(&stdout_bytes).into_owned();
4136        tracing::debug!(
4137            command,
4138            stdout_bytes = stdout_bytes.len(),
4139            "filter_range: command succeeded, replacing rows"
4140        );
4141
4142        // Replace the row range with the stdout lines.
4143        let mut all_lines = lines;
4144        let new_lines: Vec<String> = stdout.lines().map(|l| l.to_owned()).collect();
4145        // If stdout ended with a newline, stdout.lines() drops the trailing empty
4146        // entry — this preserves vim's "no trailing-newline trim" spec because
4147        // a trailing '\n' from the command means the last replacement line is the
4148        // line BEFORE the newline, not an empty line after it.
4149        let after = all_lines.split_off(bot + 1);
4150        all_lines.truncate(top);
4151        all_lines.extend(new_lines);
4152        all_lines.extend(after);
4153
4154        self.push_undo();
4155        self.restore(all_lines, (top, 0));
4156        // Leave the editor idle after a successful filter (vim parity: Normal).
4157        // Goes through the discipline hook, so the engine does not name vim.
4158        self.discipline.reset_to_idle();
4159
4160        Ok(())
4161    }
4162
4163    // ─── Comment toggle (#187) ───────────────────────────────────────────────
4164
4165    /// Toggle line comments on rows `top_row..=bot_row` (0-based, inclusive).
4166    ///
4167    /// **Algorithm** (vim-commentary parity):
4168    ///
4169    /// 1. Determine the comment marker(s) for the active filetype.
4170    ///    Priority: `settings.commentstring` (`:set commentstring=…`) → per-filetype
4171    ///    default from `hjkl_lang::comment::commentstring_for_lang` → no-op.
4172    /// 2. Scan non-blank lines.  If every non-blank line is already commented →
4173    ///    strip the comment marker from each.  Otherwise → add it to all non-blank
4174    ///    lines.
4175    /// 3. Blank / whitespace-only lines are skipped (no marker added or removed).
4176    /// 4. The marker is inserted AFTER the leading whitespace (indent-preserving).
4177    /// 5. The entire operation is a single undo step.
4178    ///
4179    /// For block-comment languages (HTML, CSS) each line is individually wrapped
4180    /// as `start text end` (per-line block style, not one multi-line block).
4181    ///
4182    /// `top_row` and `bot_row` are clamped to the buffer's valid row range.
4183    pub fn toggle_comment_range(&mut self, top_row: usize, bot_row: usize) {
4184        use hjkl_lang::comment::commentstring_for_lang;
4185
4186        let lang = self.settings.filetype.clone();
4187
4188        // Resolve the comment markers.
4189        // If `settings.commentstring` is set (non-empty) parse `start %s end`
4190        // from it; otherwise fall back to the filetype table.
4191        let (start, end) = if !self.settings.commentstring.is_empty() {
4192            let cs = &self.settings.commentstring;
4193            if let Some(idx) = cs.find("%s") {
4194                let s = cs[..idx].trim_end().to_string();
4195                let e_raw = cs[idx + 2..].trim_start();
4196                let e: Option<String> = if e_raw.is_empty() {
4197                    None
4198                } else {
4199                    Some(e_raw.to_string())
4200                };
4201                (s, e)
4202            } else {
4203                // No %s placeholder — treat the whole string as start marker.
4204                (cs.clone(), None)
4205            }
4206        } else {
4207            match commentstring_for_lang(&lang) {
4208                Some((s, e)) => (s.to_string(), e.map(|v| v.to_string())),
4209                None => return, // no known comment syntax → no-op
4210            }
4211        };
4212
4213        let row_count = buf_row_count(&self.buffer);
4214        let top = top_row.min(row_count.saturating_sub(1));
4215        let bot = bot_row.min(row_count.saturating_sub(1));
4216
4217        // Collect all lines in the range.
4218        let lines: Vec<String> = (top..=bot)
4219            .map(|r| buf_line(&self.buffer, r).unwrap_or_default())
4220            .collect();
4221
4222        // Check whether every non-blank line is already commented.
4223        let all_commented = lines.iter().all(|line| {
4224            let trimmed = line.trim_start();
4225            if trimmed.is_empty() {
4226                return true; // blank lines don't count against "all commented"
4227            }
4228            if let Some(ref end_marker) = end {
4229                // Block style: line starts with start and ends with end.
4230                trimmed.starts_with(start.as_str())
4231                    && line.trim_end().ends_with(end_marker.as_str())
4232            } else {
4233                trimmed.starts_with(start.as_str())
4234            }
4235        });
4236
4237        let mut new_lines: Vec<String> = Vec::with_capacity(lines.len());
4238        for line in &lines {
4239            let trimmed = line.trim_start();
4240            if trimmed.is_empty() {
4241                // Blank line — leave as-is.
4242                new_lines.push(line.clone());
4243                continue;
4244            }
4245            let indent_len = line.len() - trimmed.len();
4246            let indent = &line[..indent_len];
4247
4248            if all_commented {
4249                // Uncomment: strip exactly one occurrence of start (+ optional space).
4250                if let Some(after_start) = trimmed.strip_prefix(start.as_str()) {
4251                    // Strip one leading space after the marker if present.
4252                    let after_space = after_start.strip_prefix(' ').unwrap_or(after_start);
4253                    // For block style also strip the trailing end marker.
4254                    let text = if let Some(ref end_marker) = end {
4255                        after_space
4256                            .trim_end()
4257                            .strip_suffix(end_marker.as_str())
4258                            .map(|s| s.trim_end())
4259                            .unwrap_or(after_space)
4260                    } else {
4261                        after_space
4262                    };
4263                    new_lines.push(format!("{indent}{text}"));
4264                } else {
4265                    new_lines.push(line.clone());
4266                }
4267            } else {
4268                // Comment: insert marker after indent.
4269                let commented = if let Some(ref end_marker) = end {
4270                    format!("{indent}{start} {trimmed} {end_marker}")
4271                } else {
4272                    format!("{indent}{start} {trimmed}")
4273                };
4274                new_lines.push(commented);
4275            }
4276        }
4277
4278        // Replace the row range in the buffer — single undo step.
4279        self.push_undo();
4280        let row_count_after = buf_row_count(&self.buffer);
4281        let all_before: Vec<String> = (0..top)
4282            .map(|r| buf_line(&self.buffer, r).unwrap_or_default())
4283            .collect();
4284        let all_after: Vec<String> = ((bot + 1)..row_count_after)
4285            .map(|r| buf_line(&self.buffer, r).unwrap_or_default())
4286            .collect();
4287        let mut all: Vec<String> = all_before;
4288        all.extend(new_lines);
4289        all.extend(all_after);
4290        self.restore(all, (top, 0));
4291    }
4292
4293    // ─── Phase 6.1: public insert-mode primitives (kryptic-sh/hjkl#87) ────────
4294    //
4295    // Each method is the publicly callable form of one insert-mode action.
4296    // All logic lives in the corresponding `vim::*_bridge` free function;
4297    // these methods are thin delegators so the public surface stays on `Editor`.
4298    //
4299    // Invariants (enforced by the bridge fns):
4300    //   - Buffer mutations go through `mutate_edit` (dirty/undo/change-list).
4301    //   - Navigation keys call `break_undo_group_in_insert` when the FSM did.
4302    //   - `push_buffer_cursor_to_textarea` is called after every mutation
4303    //     (currently a no-op, kept for migration hygiene).
4304}
4305
4306// ── Phase 6.6b: FSM state accessors (for hjkl-vim ownership) ─────────────────
4307//
4308// The FSM (now in hjkl-vim) reads/writes `VimState` fields through public
4309// `Editor` accessors and mutators defined in this block. Each method gets a
4310// one-line `///` rustdoc. Fields mutated as a unit get a combined action method
4311// rather than individual getters + setters (e.g. `accumulate_count_digit`).
4312
4313impl<H: crate::types::Host> Editor<hjkl_buffer::Buffer, H> {
4314    // ── Pending chord ─────────────────────────────────────────────────────────
4315
4316    // ── Abbreviations ─────────────────────────────────────────────────────────
4317
4318    /// Register an abbreviation. If an entry for `lhs` already exists (same
4319    /// mode flags), it is replaced. Inserts at the front so newer definitions
4320    /// take priority (first-match wins in `try_abbrev_expand`).
4321    pub fn add_abbrev(&mut self, lhs: &str, rhs: &str, insert: bool, cmdline: bool, noremap: bool) {
4322        // Remove existing entry with same lhs + overlapping mode flags.
4323        self.abbrevs
4324            .retain(|a| a.lhs != lhs || (a.insert && !insert) || (a.cmdline && !cmdline));
4325        self.abbrevs.insert(
4326            0,
4327            crate::abbrev::Abbrev {
4328                lhs: lhs.to_string(),
4329                rhs: rhs.to_string(),
4330                insert,
4331                cmdline,
4332                noremap,
4333            },
4334        );
4335    }
4336
4337    /// Remove the abbreviation with the given `lhs`. Only removes entries
4338    /// whose mode flags overlap with the requested `insert`/`cmdline` flags.
4339    pub fn remove_abbrev(&mut self, lhs: &str, insert: bool, cmdline: bool) {
4340        self.abbrevs
4341            .retain(|a| a.lhs != lhs || (!insert || !a.insert) && (!cmdline || !a.cmdline));
4342    }
4343
4344    /// Clear all abbreviations matching the given mode flags.
4345    ///
4346    /// `insert=true` removes insert-mode abbrevs; `cmdline=true` removes
4347    /// cmdline-mode abbrevs. Both `true` clears everything.
4348    pub fn clear_abbrevs(&mut self, insert: bool, cmdline: bool) {
4349        self.abbrevs.retain(|a| {
4350            // Keep entries that do NOT match any of the cleared modes.
4351            let cleared = (insert && a.insert) || (cmdline && a.cmdline);
4352            !cleared
4353        });
4354    }
4355
4356    // ── Phase 6.6c: search + jump helpers (public Editor API) ───────────────
4357    //
4358    // `push_search_pattern`, `push_jump`, `record_search_history`, and
4359    // `walk_search_history` are public `Editor` methods so that `hjkl-vim`'s
4360    // search-prompt and normal-mode FSM can call them via the public API.
4361
4362    /// Compile `pattern` into a regex and install it as the active search
4363    /// pattern. Respects `:set ignorecase` / `:set smartcase` and inline
4364    /// `\c`/`\C` overrides. An empty or invalid pattern clears the highlight
4365    /// without raising an error.
4366    pub fn push_search_pattern(&mut self, pattern: &str) {
4367        let compiled = if pattern.is_empty() {
4368            None
4369        } else {
4370            use crate::search::{CaseMode, resolve_case_mode};
4371            let base =
4372                CaseMode::from_options(self.settings().ignore_case, self.settings().smartcase);
4373            let (stripped, mode) = resolve_case_mode(pattern, base);
4374            let src = if mode == CaseMode::Insensitive {
4375                format!("(?i){stripped}")
4376            } else {
4377                stripped
4378            };
4379            regex::Regex::new(&src).ok()
4380        };
4381        let wrap = self.settings().wrapscan;
4382        self.set_search_pattern(compiled);
4383        self.search_state_mut().wrap_around = wrap;
4384    }
4385
4386    /// Record a pre-jump cursor position onto the back jumplist. Called
4387    /// before any "big jump" motion (`gg`/`G`, `%`, `*`/`#`, `n`/`N`,
4388    /// committed `/` or `?`, …). Branching off the history clears the
4389    /// forward half, matching vim's "redo-is-lost" semantics.
4390    pub fn push_jump(&mut self, from: (usize, usize)) {
4391        self.jump_back.push(from);
4392        if self.jump_back.len() > crate::types::JUMPLIST_MAX {
4393            self.jump_back.remove(0);
4394        }
4395        self.jump_fwd.clear();
4396    }
4397
4398    /// Push `pattern` onto the committed search history. Skips if the
4399    /// most recent entry already matches (consecutive dedupe) and trims
4400    /// the oldest entries beyond the history cap.
4401    pub fn record_search_history(&mut self, pattern: &str) {
4402        if pattern.is_empty() {
4403            return;
4404        }
4405        if self.search_history.last().map(String::as_str) == Some(pattern) {
4406            return;
4407        }
4408        self.search_history.push(pattern.to_string());
4409        let len = self.search_history.len();
4410        if len > crate::types::SEARCH_HISTORY_MAX {
4411            self.search_history
4412                .drain(0..len - crate::types::SEARCH_HISTORY_MAX);
4413        }
4414    }
4415
4416    /// Walk the search-prompt history by `dir` steps. `dir = -1` moves
4417    /// toward older entries (Ctrl-P / Up); `dir = 1` toward newer ones
4418    /// (Ctrl-N / Down). Stops at the ends; does nothing if there is no
4419    /// active search prompt.
4420    pub fn walk_search_history(&mut self, dir: isize) {
4421        if self.search_history.is_empty() || self.search_prompt.is_none() {
4422            return;
4423        }
4424        let len = self.search_history.len();
4425        let next_idx = match (self.search_history_cursor, dir) {
4426            (None, -1) => Some(len - 1),
4427            (None, 1) => return,
4428            (Some(i), -1) => i.checked_sub(1),
4429            (Some(i), 1) if i + 1 < len => Some(i + 1),
4430            _ => None,
4431        };
4432        let Some(idx) = next_idx else {
4433            return;
4434        };
4435        self.search_history_cursor = Some(idx);
4436        let text = self.search_history[idx].clone();
4437        if let Some(prompt) = self.search_prompt.as_mut() {
4438            prompt.cursor = text.chars().count();
4439            prompt.text = text.clone();
4440        }
4441        self.push_search_pattern(&text);
4442    }
4443
4444    // The per-step prelude/epilogue (`begin_step`/`end_step` + `StepBookkeeping`)
4445    // moved to `hjkl_vim::step` (#267); the engine no longer owns FSM bookkeeping.
4446
4447    /// Return the character count (code-point count) of line `row`, or `0`
4448    /// when `row` is out of range.
4449    ///
4450    /// A raw buffer read with no vim semantics, so it stays on the engine core
4451    /// while the vim-specific visual/block primitives move to
4452    /// `hjkl_vim::VimEditorExt` (#267).
4453    pub fn line_char_count(&self, row: usize) -> usize {
4454        buf_line_chars(&self.buffer, row)
4455    }
4456}
4457
4458/// First `(row, col)` where two ropes differ, or `None` if identical. Used to
4459/// place the cursor at the start of a redone change (vim parity).
4460fn first_diff_pos(a: &ropey::Rope, b: &ropey::Rope) -> Option<(usize, usize)> {
4461    let rows = a.len_lines().max(b.len_lines());
4462    for r in 0..rows {
4463        let la = if r < a.len_lines() {
4464            hjkl_buffer::rope_line_str(a, r)
4465        } else {
4466            String::new()
4467        };
4468        let lb = if r < b.len_lines() {
4469            hjkl_buffer::rope_line_str(b, r)
4470        } else {
4471            String::new()
4472        };
4473        if la != lb {
4474            let col = la
4475                .chars()
4476                .zip(lb.chars())
4477                .take_while(|(x, y)| x == y)
4478                .count();
4479            return Some((r, col));
4480        }
4481    }
4482    None
4483}
4484
4485/// Visual column of the character at `char_col` in `line`, treating `\t`
4486/// as expansion to the next `tab_width` stop and every other char as
4487/// 1 cell wide. Wide-char support (CJK, emoji) is a separate concern —
4488/// the cursor math elsewhere also assumes single-cell chars.
4489fn visual_col_for_char(line: &str, char_col: usize, tab_width: usize) -> usize {
4490    let mut visual = 0usize;
4491    for (i, ch) in line.chars().enumerate() {
4492        if i >= char_col {
4493            break;
4494        }
4495        if ch == '\t' {
4496            visual += tab_width - (visual % tab_width);
4497        } else {
4498            visual += 1;
4499        }
4500    }
4501    visual
4502}
4503
4504#[cfg(test)]
4505mod shift_syntax_spans_tests {
4506    use super::*;
4507    use crate::types::{ContentEdit, DefaultHost, Options, Style};
4508    use hjkl_buffer::Buffer;
4509
4510    fn ed_with_spans(line_count: usize) -> Editor<Buffer, DefaultHost> {
4511        let text = (0..line_count)
4512            .map(|i| format!("row{i}"))
4513            .collect::<Vec<_>>()
4514            .join("\n");
4515        let buf = Buffer::from_str(&text);
4516        let mut e = Editor::new(buf, DefaultHost::new(), Options::default());
4517        // Synthesize span rows so we can detect which survive a shift.
4518        // Use a distinct fg colour per row so spans are identifiable.
4519        let style = Style::default();
4520        let spans: Vec<Vec<(usize, usize, Style)>> =
4521            (0..line_count).map(|_| vec![(0, 1, style)]).collect();
4522        e.install_syntax_spans(spans);
4523        e
4524    }
4525
4526    fn edit_insert_newline_at(row: u32, col: u32) -> ContentEdit {
4527        // Pressing Enter: zero-width insertion that produces one new row.
4528        ContentEdit {
4529            start_byte: 0,
4530            old_end_byte: 0,
4531            new_end_byte: 1,
4532            start_position: (row, col),
4533            old_end_position: (row, col),
4534            new_end_position: (row + 1, 0),
4535        }
4536    }
4537
4538    fn edit_join_rows(row: u32, col: u32) -> ContentEdit {
4539        // Backspace at start of `row+1`: removes the newline, joining the
4540        // two rows. old_end is on `row+1`, new_end on `row`.
4541        ContentEdit {
4542            start_byte: 0,
4543            old_end_byte: 1,
4544            new_end_byte: 0,
4545            start_position: (row, col),
4546            old_end_position: (row + 1, 0),
4547            new_end_position: (row, col),
4548        }
4549    }
4550
4551    #[test]
4552    fn insert_grows_buffer_spans_in_place() {
4553        let mut e = ed_with_spans(4);
4554        // Newline at row 1 → buffer grew by one row.
4555        e.shift_syntax_spans_for_edits(&[edit_insert_newline_at(1, 1)]);
4556        assert_eq!(
4557            e.buffer_spans().len(),
4558            5,
4559            "row-count grew → spans rows must match"
4560        );
4561        // The empty row should be at index 2 (right after the split point).
4562        assert!(e.buffer_spans()[2].is_empty(), "inserted row sits at oer+1");
4563        // Surrounding rows kept their content.
4564        assert!(!e.buffer_spans()[0].is_empty());
4565        assert!(!e.buffer_spans()[1].is_empty());
4566        assert!(!e.buffer_spans()[3].is_empty());
4567        assert!(!e.buffer_spans()[4].is_empty());
4568    }
4569
4570    #[test]
4571    fn delete_shrinks_buffer_spans_in_place() {
4572        let mut e = ed_with_spans(4);
4573        e.shift_syntax_spans_for_edits(&[edit_join_rows(1, 1)]);
4574        assert_eq!(
4575            e.buffer_spans().len(),
4576            3,
4577            "row-count shrank → spans rows must match"
4578        );
4579    }
4580
4581    #[test]
4582    fn same_row_edit_leaves_rows_untouched() {
4583        let mut e = ed_with_spans(3);
4584        let edit = ContentEdit {
4585            start_byte: 0,
4586            old_end_byte: 0,
4587            new_end_byte: 1,
4588            start_position: (1, 0),
4589            old_end_position: (1, 0),
4590            new_end_position: (1, 1),
4591        };
4592        e.shift_syntax_spans_for_edits(&[edit]);
4593        assert_eq!(e.buffer_spans().len(), 3);
4594        for row in 0..3 {
4595            assert!(
4596                !e.buffer_spans()[row].is_empty(),
4597                "row {row} should still hold its span"
4598            );
4599        }
4600    }
4601
4602    #[test]
4603    fn ordered_edits_apply_against_prior_state() {
4604        let mut e = ed_with_spans(3);
4605        // Two consecutive inserts: each adds a row.
4606        e.shift_syntax_spans_for_edits(&[
4607            edit_insert_newline_at(0, 1),
4608            edit_insert_newline_at(1, 1),
4609        ]);
4610        assert_eq!(e.buffer_spans().len(), 5);
4611    }
4612
4613    /// Build a buffer with `line_count` rows where row `i` has a span at
4614    /// column `i + 1` so the rows are independently identifiable after a
4615    /// shift (otherwise all spans look identical and can't tell which
4616    /// original row's spans landed at which post-shift index).
4617    fn ed_with_distinguishable_spans(line_count: usize) -> Editor<Buffer, DefaultHost> {
4618        let text = (0..line_count)
4619            .map(|i| format!("rowwwwwwwwww{i}"))
4620            .collect::<Vec<_>>()
4621            .join("\n");
4622        let buf = Buffer::from_str(&text);
4623        let mut e = Editor::new(buf, DefaultHost::new(), Options::default());
4624        let style = Style::default();
4625        let spans: Vec<Vec<(usize, usize, Style)>> = (0..line_count)
4626            .map(|i| vec![(i + 1, i + 2, style)])
4627            .collect();
4628        e.install_syntax_spans(spans);
4629        e
4630    }
4631
4632    /// Regression for off-by-one in `shift_syntax_spans_for_edits`.
4633    ///
4634    /// `P` (paste-before) at column 0 of row 0 inserts new lines BEFORE
4635    /// row 0. The pre-paste rows should shift down by N. The fix inserts
4636    /// empty rows at idx `start.row` (not `oer + 1`) when `start.col == 0`.
4637    ///
4638    /// Symptom before the fix: row 0's spans stayed at idx 0 after a
4639    /// 4-row `ggP`, but the file's row 0 was now the pasted content (no
4640    /// spans available yet). Display: pasted row 0 painted with the
4641    /// pre-paste row 0's spans (LUCKILY identical content in many cases)
4642    /// while the *shifted* pre-paste row 0 (now at file row 4) painted
4643    /// with the pre-paste row 1's spans — visible as the WRONG row
4644    /// showing the wrong-row colours.
4645    #[test]
4646    fn shift_for_paste_at_start_of_row_zero() {
4647        let mut e = ed_with_distinguishable_spans(7);
4648        // Snapshot: row i has a span at col (i+1, i+2).
4649        let pre = e.buffer_spans().to_vec();
4650        // P at (0, 0) inserting 4 lines.
4651        let edit = ContentEdit {
4652            start_byte: 0,
4653            old_end_byte: 0,
4654            new_end_byte: 4,
4655            start_position: (0, 0),
4656            old_end_position: (0, 0),
4657            new_end_position: (4, 0),
4658        };
4659        e.shift_syntax_spans_for_edits(&[edit]);
4660        assert_eq!(e.buffer_spans().len(), 11, "row count grew by 4");
4661        // Rows 0..4 are the new pasted lines — should be EMPTY placeholders.
4662        for row in 0..4 {
4663            assert!(
4664                e.buffer_spans()[row].is_empty(),
4665                "row {row} (new paste) must be empty placeholder, got {:?}",
4666                e.buffer_spans()[row]
4667            );
4668        }
4669        // Rows 4..11 are the original rows 0..7 shifted down by 4.
4670        for (orig_row, orig_spans) in pre.iter().enumerate() {
4671            let new_row = orig_row + 4;
4672            assert_eq!(
4673                &e.buffer_spans()[new_row],
4674                orig_spans,
4675                "original row {orig_row} should be at file row {new_row} after \
4676                 paste-before-row-0"
4677            );
4678        }
4679    }
4680
4681    /// Same idea for paste at start of a non-zero row: `2GP` inserts 3
4682    /// lines before row 2.
4683    #[test]
4684    fn shift_for_paste_at_start_of_middle_row() {
4685        let mut e = ed_with_distinguishable_spans(5);
4686        let pre = e.buffer_spans().to_vec();
4687        // Insert 3 lines at (2, 0).
4688        let edit = ContentEdit {
4689            start_byte: 0,
4690            old_end_byte: 0,
4691            new_end_byte: 3,
4692            start_position: (2, 0),
4693            old_end_position: (2, 0),
4694            new_end_position: (5, 0),
4695        };
4696        e.shift_syntax_spans_for_edits(&[edit]);
4697        assert_eq!(e.buffer_spans().len(), 8);
4698        // Rows 0..2 unchanged (before the insertion point).
4699        assert_eq!(e.buffer_spans()[0], pre[0]);
4700        assert_eq!(e.buffer_spans()[1], pre[1]);
4701        // Rows 2..5 are new pasted lines.
4702        for row in 2..5 {
4703            assert!(
4704                e.buffer_spans()[row].is_empty(),
4705                "row {row} must be empty placeholder"
4706            );
4707        }
4708        // Rows 5..8 are originals 2..5 shifted down by 3.
4709        for (orig_row, orig_spans) in pre.iter().enumerate().take(5).skip(2) {
4710            let new_row = orig_row + 3;
4711            assert_eq!(
4712                &e.buffer_spans()[new_row],
4713                orig_spans,
4714                "original row {orig_row} should land at file row {new_row}"
4715            );
4716        }
4717    }
4718
4719    /// Regression: pasting N rows at the beginning of the buffer used to
4720    /// run `Vec::insert(0, ...)` once per row → O(N²) memmove. samply
4721    /// showed this path eating 87 % of paste CPU on a 60 k-row paste.
4722    /// The splice rewrite is O(N).
4723    ///
4724    /// Asserting a hard wall-clock bound is brittle on slow CI, so we
4725    /// pick a budget the old code blows past by >10×: 60 k rows in
4726    /// under 200 ms even on a debug build. Old impl: ~3-5 seconds.
4727    #[test]
4728    fn shift_for_60k_row_paste_at_row_zero_is_under_200ms() {
4729        let mut e = ed_with_distinguishable_spans(8);
4730        let edit = ContentEdit {
4731            start_byte: 0,
4732            old_end_byte: 0,
4733            new_end_byte: 60_000,
4734            start_position: (0, 0),
4735            old_end_position: (0, 0),
4736            new_end_position: (60_000, 0),
4737        };
4738        let t = std::time::Instant::now();
4739        e.shift_syntax_spans_for_edits(&[edit]);
4740        let elapsed = t.elapsed();
4741        assert!(
4742            elapsed.as_millis() < 200,
4743            "60k-row shift took {elapsed:?}; budget is 200 ms (catches \
4744             reintroduction of the O(N²) per-row insert loop)"
4745        );
4746        assert_eq!(e.buffer_spans().len(), 60_008);
4747    }
4748
4749    /// Regression: `push_undo` used to clone every line into a
4750    /// `Vec<String>` (162 k heap allocations on a 162 k-row buffer per
4751    /// snapshot). Now stores an `Arc<String>` shared with
4752    /// `Buffer::content_joined`'s per-dirty_gen cache — a warm snapshot
4753    /// is an `Arc::clone` (one ptr bump).
4754    ///
4755    /// Test: snapshot a 60 k-row buffer 100 times. With the Arc impl
4756    /// this is essentially free (one join then 99 Arc::clones). The
4757    /// old `Vec<String>` impl required 60 k allocations per call =
4758    /// 6 M allocations, easily seconds even on release.
4759    #[test]
4760    fn push_undo_snapshot_arc_clone_is_under_100ms_for_100_snapshots() {
4761        use crate::types::{DefaultHost, Options};
4762        let text = "x\n".repeat(60_000);
4763        let buf = hjkl_buffer::Buffer::from_str(&text);
4764        let mut e = Editor::new(buf, DefaultHost::default(), Options::default());
4765        // Warm the cache: one join, subsequent snapshots Arc::clone it.
4766        e.push_undo();
4767        let t = std::time::Instant::now();
4768        for _ in 0..100 {
4769            e.push_undo();
4770        }
4771        let elapsed = t.elapsed();
4772        assert!(
4773            elapsed.as_millis() < 100,
4774            "100 snapshots of a 60k-row buffer took {elapsed:?}; budget \
4775             100 ms. Likely regressed to per-line cloning."
4776        );
4777    }
4778}
4779
4780#[cfg(test)]
4781mod earlier_later_tests {
4782    use super::*;
4783    use crate::types::{DefaultHost, Options};
4784    use hjkl_buffer::Buffer;
4785    use std::time::{Duration, SystemTime};
4786
4787    fn make_ed(content: &str) -> Editor<Buffer, DefaultHost> {
4788        let buf = Buffer::from_str(content);
4789        Editor::new(buf, DefaultHost::default(), Options::default())
4790    }
4791
4792    // ── step-based ───────────────────────────────────────────────────────────
4793
4794    #[test]
4795    fn earlier_by_steps_n_undoes_n_changes() {
4796        let mut ed = make_ed("hello");
4797        ed.push_undo(); // snap 1
4798        ed.push_undo(); // snap 2
4799        ed.push_undo(); // snap 3
4800        assert_eq!(ed.undo_stack_len(), 3);
4801        let applied = ed.earlier_by_steps(2);
4802        assert_eq!(applied, 2);
4803        assert_eq!(ed.undo_stack_len(), 1);
4804    }
4805
4806    #[test]
4807    fn earlier_by_steps_caps_at_stack_size() {
4808        let mut ed = make_ed("hello");
4809        ed.push_undo(); // snap 1
4810        // Ask for 10 but only 1 available.
4811        let applied = ed.earlier_by_steps(10);
4812        assert_eq!(applied, 1);
4813        assert_eq!(ed.undo_stack_len(), 0);
4814    }
4815
4816    #[test]
4817    fn later_by_steps_n_redoes_n_changes() {
4818        let mut ed = make_ed("hello");
4819        ed.push_undo(); // snap 1
4820        ed.push_undo(); // snap 2
4821        ed.push_undo(); // snap 3
4822        // Undo all 3 so they're on redo stack.
4823        ed.earlier_by_steps(3);
4824        assert_eq!(ed.undo_stack_len(), 0);
4825        let applied = ed.later_by_steps(2);
4826        assert_eq!(applied, 2);
4827        assert_eq!(ed.undo_stack_len(), 2);
4828    }
4829
4830    #[test]
4831    fn later_by_steps_caps_at_redo_stack_size() {
4832        let mut ed = make_ed("hello");
4833        ed.push_undo(); // snap 1
4834        ed.earlier_by_steps(1); // moves to redo
4835        let applied = ed.later_by_steps(99);
4836        assert_eq!(applied, 1);
4837    }
4838
4839    // ── time-based ───────────────────────────────────────────────────────────
4840
4841    fn epoch_plus(secs: u64) -> SystemTime {
4842        SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
4843    }
4844
4845    #[test]
4846    fn earlier_by_time_stops_at_target_boundary() {
4847        let mut ed = make_ed("hello");
4848        // Push 3 entries at t-30s, t-20s, t-10s (relative to epoch).
4849        ed.push_undo_at(epoch_plus(30));
4850        ed.push_undo_at(epoch_plus(40));
4851        ed.push_undo_at(epoch_plus(50));
4852        // Redo stack is empty; undo has 3 entries.
4853        // target = epoch+35 → should undo entries at t=50 and t=40, stop at t=30
4854        let target = epoch_plus(35);
4855        let applied = ed.earlier_by_time(target);
4856        assert_eq!(applied, 2, "should undo t=50 and t=40; stop at t=30");
4857        assert_eq!(ed.undo_stack_len(), 1, "t=30 entry remains");
4858    }
4859
4860    #[test]
4861    fn earlier_by_time_empty_stack_returns_zero() {
4862        let mut ed = make_ed("hello");
4863        let applied = ed.earlier_by_time(epoch_plus(999));
4864        assert_eq!(applied, 0);
4865        assert_eq!(ed.undo_stack_len(), 0);
4866    }
4867
4868    #[test]
4869    fn later_by_time_target_in_future_redoes_all() {
4870        let mut ed = make_ed("hello");
4871        ed.push_undo_at(epoch_plus(10));
4872        ed.push_undo_at(epoch_plus(20));
4873        // Undo both → they move to redo stack with their timestamps preserved.
4874        ed.earlier_by_steps(2);
4875        // target far in future: should redo all.
4876        let applied = ed.later_by_time(epoch_plus(9999));
4877        assert_eq!(applied, 2);
4878        assert_eq!(ed.undo_stack_len(), 2);
4879    }
4880}
4881
4882// ─── modifiable / readonly semantics tests ────────────────────────────────────
4883
4884#[cfg(test)]
4885mod shared_registers_tests {
4886    use super::*;
4887    use crate::types::{DefaultHost, Options};
4888    use hjkl_buffer::Buffer;
4889
4890    #[test]
4891    fn shared_register_bank_visible_across_editors() {
4892        let shared =
4893            std::sync::Arc::new(std::sync::Mutex::new(crate::registers::Registers::default()));
4894        let mut a = Editor::new(Buffer::new(), DefaultHost::default(), Options::default());
4895        a.set_registers_arc(shared.clone());
4896        let mut b = Editor::new(Buffer::new(), DefaultHost::default(), Options::default());
4897        b.set_registers_arc(shared.clone());
4898        // Write to editor A's unnamed register
4899        a.registers_mut().unnamed = crate::registers::Slot {
4900            text: "hello".to_string(),
4901            linewise: false,
4902        };
4903        // Read from editor B — same bank, no copy needed
4904        assert_eq!(b.registers().unnamed.text, "hello");
4905    }
4906}
4907
4908#[cfg(test)]
4909mod scroll_anim_tests {
4910    use super::*;
4911    use crate::types::{DefaultHost, Host, Options};
4912    use hjkl_buffer::Buffer;
4913
4914    fn make_editor_with_content(content: &str) -> Editor<Buffer, DefaultHost> {
4915        let mut buf = Buffer::new();
4916        crate::types::BufferEdit::replace_all(&mut buf, content);
4917        let host = DefaultHost::new();
4918        Editor::new(buf, host, Options::default())
4919    }
4920
4921    #[test]
4922    fn scroll_duration_default_is_zero() {
4923        let buf = Buffer::new();
4924        let host = DefaultHost::new();
4925        let ed = Editor::new(buf, host, Options::default());
4926        assert_eq!(ed.settings().scroll_duration_ms, 0);
4927    }
4928
4929    #[test]
4930    fn take_scroll_anim_hint_false_initially() {
4931        let buf = Buffer::new();
4932        let host = DefaultHost::new();
4933        let mut ed = Editor::new(buf, host, Options::default());
4934        assert!(!ed.take_scroll_anim_hint());
4935    }
4936
4937    #[test]
4938    fn take_scroll_anim_hint_one_shot() {
4939        // Half-page scroll sets the hint; second drain clears it.
4940        let content: String = (0..50).map(|i| format!("line {i}\n")).collect();
4941        let mut ed = make_editor_with_content(&content);
4942        // Set viewport height so scroll actually moves
4943        ed.host_mut().viewport_mut().height = 20;
4944        ed.host_mut().viewport_mut().width = 80;
4945        ed.host_mut().viewport_mut().text_width = 80;
4946        ed.scroll_half_page(crate::types::ScrollDir::Down, 1);
4947        assert!(
4948            ed.take_scroll_anim_hint(),
4949            "hint should be set after half-page"
4950        );
4951        assert!(
4952            !ed.take_scroll_anim_hint(),
4953            "hint should be cleared on second drain"
4954        );
4955    }
4956
4957    #[test]
4958    fn line_scroll_does_not_set_hint() {
4959        let content: String = (0..50).map(|i| format!("line {i}\n")).collect();
4960        let mut ed = make_editor_with_content(&content);
4961        ed.host_mut().viewport_mut().height = 20;
4962        ed.host_mut().viewport_mut().width = 80;
4963        ed.host_mut().viewport_mut().text_width = 80;
4964        ed.scroll_line(crate::types::ScrollDir::Down, 1);
4965        assert!(
4966            !ed.take_scroll_anim_hint(),
4967            "hint must NOT be set for C-e/C-y"
4968        );
4969    }
4970}
4971
4972// ── UndoGranularity unit tests ───────────────────────────────────────────────
4973//
4974// These tests prove the critical invariant: vim (InsertSession) is byte-
4975// identical before and after this feature; Word granularity splits undo at
4976// word boundaries.