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