Skip to main content

hjkl_engine/
editor.rs

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