hjkl_engine/cursor_move.rs
1//! Cursor moves that carry their own `curswant` semantics — phase 1 of
2//! `docs/backlog.md`.
3//!
4//! Today, moving the cursor and maintaining `sticky_col` (vim's `curswant`)
5//! are two separate actions, and ~186 call sites do only the first. [`Move`]
6//! makes "what does this do to `curswant`?" a required argument of moving
7//! rather than a follow-up call that can be forgotten: a new motion must name
8//! a variant to compile.
9//!
10//! This module adds the API only. It is implemented over the existing
11//! primitives so behaviour is bit-identical, and nothing is migrated onto it
12//! yet — phases 2–4 do that, phase 5 then seals the raw primitives
13//! (`buf_set_cursor_rc`, `View::set_cursor`) behind it.
14
15use crate::Editor;
16use crate::buf_helpers::{buf_line, buf_line_chars};
17use hjkl_buffer::visual_col_to_char_col;
18
19/// How a cursor move relates to `sticky_col` (vim's `curswant`) — the column
20/// `j` / `k` aim at.
21///
22/// Vim's rule has exactly two halves, and every variant here encodes one of
23/// them (or, for [`Move::Raw`], deliberately opts out):
24///
25/// - **vertical** motions READ `curswant`, clamp to the target row's length,
26/// and leave `curswant` alone, so a run of `j` through short lines returns
27/// to the original column on the far side;
28/// - **everything else** that moves the cursor SETS `curswant` to the column
29/// it landed on, so the next `j` aims there.
30///
31/// Pick by asking what the move *is*, not by what is convenient: the whole
32/// point of the enum is that the answer gets recorded at the call site.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum Move {
35 /// `j` / `k` and their screen-line equivalents (`<C-e>` / `<C-y>`).
36 ///
37 /// READS `sticky_col`, clamps the landing column to `row`'s length, and
38 /// leaves `sticky_col` holding the *un-clamped* want — that is what lets
39 /// the column survive a short line and reappear on the next long one.
40 /// Bootstraps `sticky_col` from the current column when nothing has set
41 /// it yet.
42 Vertical { row: usize },
43
44 /// An explicit jump to a position: a search hit, `gg` / `G`, a mark, a
45 /// mouse click, a picker `<CR>`, `]d`, a jumplist entry.
46 ///
47 /// SETS `sticky_col` to `col`. Vim resets `curswant` on every explicit
48 /// jump, so the next `j` aims at the landed column rather than at
49 /// wherever the cursor sat beforehand — the bug fixed in `c022a3a4`.
50 Jump { row: usize, col: usize },
51
52 /// A move within the current row: `h`, `l`, `w`, `b`, `e`, `f` / `t`,
53 /// `0`, `^`, `$`.
54 ///
55 /// SETS `sticky_col` to `col`, same half of the rule as [`Move::Jump`];
56 /// the separate variant exists so horizontal call sites cannot silently
57 /// pass the wrong row.
58 Horizontal { col: usize },
59
60 /// Place the cursor without touching `sticky_col` at all.
61 ///
62 /// This is the *conspicuous* variant on purpose. It is not the default
63 /// landing zone for a site whose semantics are unclear — a mechanical
64 /// migration that picked `Raw` everywhere would compile, pass, and
65 /// preserve the entire bug class. It is legitimate only where some other
66 /// code owns `curswant` for the duration, i.e.:
67 ///
68 /// - the clamped write inside a vertical motion itself
69 /// ([`Move::Vertical`]'s internal write, which must preserve the
70 /// un-clamped want it just stored);
71 /// - restoring a position saved earlier in the same operation (operator
72 /// bodies that park the cursor, run an edit, then put it back), where
73 /// the cursor is semantically where it already was;
74 /// - host-side state restores — viewport sync, snapshot replay — where
75 /// the host's own sticky tracking is authoritative.
76 ///
77 /// Any other use wants [`Move::Jump`]. Each `Raw` should carry a one-line
78 /// reason at its call site, and it stays greppable for review.
79 Raw { row: usize, col: usize },
80}
81
82impl<H: crate::types::Host> Editor<hjkl_buffer::View, H> {
83 /// Move the cursor, applying the `curswant` rule the [`Move`] variant
84 /// names. See [`Move`] for which variant a given motion is.
85 pub fn move_cursor(&mut self, m: Move) {
86 match m {
87 Move::Vertical { row } => {
88 // Bootstrap from the current column on the very first vertical
89 // motion, exactly as `apply_sticky_col` does.
90 let (current_row, current_col) = self.cursor();
91 let want = self
92 .sticky_col()
93 .unwrap_or_else(|| self.cursor_want(current_row, current_col));
94 // Record the un-clamped want first so the next vertical motion
95 // still sees it even though this one may clamp short.
96 self.set_sticky_col(Some(want));
97 // Clamp to the last char on non-empty rows — vim normal mode
98 // never parks one past end of line; empty rows collapse to 0.
99 let line = buf_line(&self.buffer, row).unwrap_or_default();
100 let char_col = visual_col_to_char_col(&line, want, self.settings().tabstop);
101 let max_col = buf_line_chars(&self.buffer, row).saturating_sub(1);
102 // Quiet write: `jump_cursor` would overwrite the want stored
103 // above with the clamped column.
104 self.set_cursor_quiet(row, char_col.min(max_col));
105 }
106 Move::Jump { row, col } => self.jump_cursor(row, col),
107 Move::Horizontal { col } => {
108 let row = self.cursor().0;
109 self.jump_cursor(row, col);
110 }
111 Move::Raw { row, col } => self.set_cursor_quiet(row, col),
112 }
113 }
114}
115
116#[cfg(test)]
117mod tests {
118 use super::Move;
119 use crate::Editor;
120 use crate::types::{DefaultHost, Options};
121 use hjkl_buffer::View;
122
123 fn editor(text: &str) -> Editor<View, DefaultHost> {
124 Editor::new(View::from_str(text), DefaultHost::new(), Options::default())
125 }
126
127 /// `Vertical` reads `sticky_col`, clamps to the row, and leaves the
128 /// un-clamped want in place so a later long row can restore it.
129 #[test]
130 fn vertical_clamps_but_preserves_the_unclamped_want() {
131 // row 0 is long, row 1 is short, row 2 is long again.
132 let mut e = editor("abcdefghij\nab\nabcdefghij");
133 e.move_cursor(Move::Horizontal { col: 7 });
134 assert_eq!(e.cursor(), (0, 7));
135 assert_eq!(e.sticky_col(), Some(7));
136
137 // Down onto the short row: the cursor clamps to its last char...
138 e.move_cursor(Move::Vertical { row: 1 });
139 assert_eq!(e.cursor(), (1, 1));
140 // ...but the want survives un-clamped.
141 assert_eq!(e.sticky_col(), Some(7));
142
143 // Down again onto a long row: the original column comes back.
144 e.move_cursor(Move::Vertical { row: 2 });
145 assert_eq!(e.cursor(), (2, 7));
146 assert_eq!(e.sticky_col(), Some(7));
147 }
148
149 /// An empty row collapses to column 0 and still keeps the want.
150 #[test]
151 fn vertical_over_an_empty_row_collapses_to_col_zero() {
152 let mut e = editor("abcdef\n\nabcdef");
153 e.move_cursor(Move::Horizontal { col: 4 });
154 e.move_cursor(Move::Vertical { row: 1 });
155 assert_eq!(e.cursor(), (1, 0));
156 assert_eq!(e.sticky_col(), Some(4));
157 e.move_cursor(Move::Vertical { row: 2 });
158 assert_eq!(e.cursor(), (2, 4));
159 }
160
161 /// With no `sticky_col` yet, `Vertical` bootstraps from the current column.
162 #[test]
163 fn vertical_bootstraps_the_want_from_the_current_column() {
164 let mut e = editor("abcdef\nabcdef");
165 e.move_cursor(Move::Raw { row: 0, col: 3 });
166 assert_eq!(e.sticky_col(), None);
167 e.move_cursor(Move::Vertical { row: 1 });
168 assert_eq!(e.cursor(), (1, 3));
169 assert_eq!(e.sticky_col(), Some(3));
170 }
171
172 /// `Jump` sets the want to the column it landed on — the search-hit /
173 /// `gg` / mark rule, and the fix `c022a3a4` made structural.
174 #[test]
175 fn jump_sets_the_want_to_the_landed_column() {
176 let mut e = editor("abcdefghij\nabcdefghij");
177 e.move_cursor(Move::Horizontal { col: 9 });
178 assert_eq!(e.sticky_col(), Some(9));
179
180 e.move_cursor(Move::Jump { row: 1, col: 2 });
181 assert_eq!(e.cursor(), (1, 2));
182 assert_eq!(e.sticky_col(), Some(2), "a jump resets curswant");
183 }
184
185 /// `Horizontal` keeps the row and sets the want to the new column.
186 #[test]
187 fn horizontal_keeps_the_row_and_sets_the_want() {
188 let mut e = editor("abcdefghij\nabcdefghij");
189 e.move_cursor(Move::Jump { row: 1, col: 8 });
190 e.move_cursor(Move::Horizontal { col: 3 });
191 assert_eq!(e.cursor(), (1, 3));
192 assert_eq!(e.sticky_col(), Some(3));
193 }
194
195 /// `Raw` moves the cursor and leaves `sticky_col` exactly as it was —
196 /// including leaving it `None`.
197 #[test]
198 fn raw_leaves_the_want_untouched() {
199 let mut e = editor("abcdefghij\nabcdefghij");
200 e.move_cursor(Move::Horizontal { col: 6 });
201 assert_eq!(e.sticky_col(), Some(6));
202
203 e.move_cursor(Move::Raw { row: 1, col: 1 });
204 assert_eq!(e.cursor(), (1, 1));
205 assert_eq!(e.sticky_col(), Some(6), "Raw must not disturb curswant");
206
207 // And a `Raw` before anything has set a want leaves it unset.
208 let mut fresh = editor("abcdefghij");
209 fresh.move_cursor(Move::Raw { row: 0, col: 4 });
210 assert_eq!(fresh.cursor(), (0, 4));
211 assert_eq!(fresh.sticky_col(), None);
212 }
213
214 #[test]
215 fn vertical_bootstraps_display_want_from_the_current_column() {
216 let mut e = editor("\tabcdef\n\txyz");
217 e.move_cursor(Move::Raw { row: 0, col: 2 });
218 assert_eq!(e.sticky_col(), None);
219
220 e.move_cursor(Move::Vertical { row: 1 });
221 assert_eq!(e.cursor(), (1, 2));
222 assert_eq!(e.sticky_col(), Some(5));
223 }
224
225 /// Display columns are converted back to character columns before clamping,
226 /// so tabs do not make the cursor land too far right.
227 #[test]
228 fn vertical_converts_display_want_to_a_character_column() {
229 let mut e = editor("\tabcdef\n\txyz");
230 e.move_cursor(Move::Horizontal { col: 2 });
231 assert_eq!(e.sticky_col(), Some(5));
232
233 e.move_cursor(Move::Vertical { row: 1 });
234 assert_eq!(e.cursor(), (1, 2));
235 assert_eq!(e.sticky_col(), Some(5));
236 }
237
238 /// `Vertical` reproduces `apply_sticky_col`'s vertical branch exactly —
239 /// the property phases 2–4 rely on when they swap call sites over.
240 #[test]
241 fn vertical_matches_the_apply_sticky_col_clamp() {
242 for (want, row, expected) in [(7usize, 1usize, 1usize), (0, 1, 0), (1, 1, 1), (99, 0, 9)] {
243 let mut e = editor("abcdefghij\nab");
244 e.move_cursor(Move::Horizontal { col: 0 });
245 e.set_sticky_col(Some(want));
246 e.move_cursor(Move::Vertical { row });
247 assert_eq!(e.cursor(), (row, expected), "want {want} onto row {row}");
248 assert_eq!(e.sticky_col(), Some(want), "want {want} must survive");
249 }
250 }
251
252 /// `Vertical` onto a line containing double-width chars must land on the
253 /// char whose PAINTED cells contain the wanted column, not on the Nth
254 /// char. Oracle: neovim 0.12.4, buffer `abcdefgh` / `ab世界cd`, `j` from
255 /// each byte column of row 0 (1-based cols → 0-based here):
256 ///
257 /// ```text
258 /// col 1 -> bytecol 1 (a) col 5 -> bytecol 6 (界)
259 /// col 2 -> bytecol 2 (b) col 6 -> bytecol 6 (界)
260 /// col 3 -> bytecol 3 (世) col 7 -> bytecol 9 (c)
261 /// col 4 -> bytecol 3 (世) col 8 -> bytecol 10 (d)
262 /// ```
263 #[test]
264 fn vertical_onto_wide_chars_matches_nvim() {
265 // 0-based (want, char index on `ab世界cd`)
266 for (want, expected) in [
267 (0usize, 0usize), // a
268 (1, 1), // b
269 (2, 2), // 世, leading cell
270 (3, 2), // 世, trailing cell
271 (4, 3), // 界, leading cell
272 (5, 3), // 界, trailing cell
273 (6, 4), // c
274 (7, 5), // d
275 ] {
276 let mut e = editor("abcdefgh\nab世界cd");
277 e.move_cursor(Move::Horizontal { col: want });
278 assert_eq!(e.sticky_col(), Some(want));
279 e.move_cursor(Move::Vertical { row: 1 });
280 assert_eq!(e.cursor(), (1, expected), "want {want} onto the wide row");
281 }
282 }
283
284 /// The other direction: leaving a wide line carries the char's LEADING
285 /// visual cell as `curswant`. nvim, `ab世界cd` / `abcdefgh`: with the
286 /// cursor on `界` (bytecol 6) `getcurpos()[4]` is 5 and `j` lands on
287 /// bytecol 5 of the ASCII row — 0-based column 4.
288 #[test]
289 fn vertical_off_a_wide_line_uses_the_leading_cell() {
290 for (start_char, expected_ascii) in [(2usize, 2usize), (3, 4), (4, 6), (5, 7)] {
291 let mut e = editor("ab世界cd\nabcdefgh");
292 e.move_cursor(Move::Horizontal { col: start_char });
293 e.move_cursor(Move::Vertical { row: 1 });
294 assert_eq!(
295 e.cursor(),
296 (1, expected_ascii),
297 "from wide char {start_char}"
298 );
299 }
300 }
301
302 /// A combining mark is never a landing site. nvim, `abcdefgh` /
303 /// `ae\u{301}b`: `j` from col 3 (0-based 2) lands on bytecol 5 — the `b`,
304 /// char index 3 — skipping the mark at char index 2.
305 #[test]
306 fn vertical_onto_a_combining_mark_lands_on_the_next_char() {
307 let mut e = editor("abcdefgh\nae\u{301}b");
308 e.move_cursor(Move::Horizontal { col: 2 });
309 e.move_cursor(Move::Vertical { row: 1 });
310 assert_eq!(e.cursor(), (1, 3));
311 }
312}