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