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