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