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