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