Skip to main content

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::{char_col_to_visual_col, 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    ///   (`hjkl_vim::vim::motion::apply_sticky_col`), 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 current_line = buf_line(&self.buffer, current_row).unwrap_or_default();
92                let want = self.sticky_col().unwrap_or_else(|| {
93                    char_col_to_visual_col(&current_line, current_col, self.settings().tabstop)
94                });
95                // Record the un-clamped want first so the next vertical motion
96                // still sees it even though this one may clamp short.
97                self.set_sticky_col(Some(want));
98                // Clamp to the last char on non-empty rows — vim normal mode
99                // never parks one past end of line; empty rows collapse to 0.
100                let line = buf_line(&self.buffer, row).unwrap_or_default();
101                let char_col = visual_col_to_char_col(&line, want, self.settings().tabstop);
102                let max_col = buf_line_chars(&self.buffer, row).saturating_sub(1);
103                // Quiet write: `jump_cursor` would overwrite the want stored
104                // above with the clamped column.
105                self.set_cursor_quiet(row, char_col.min(max_col));
106            }
107            Move::Jump { row, col } => self.jump_cursor(row, col),
108            Move::Horizontal { col } => {
109                let row = self.cursor().0;
110                self.jump_cursor(row, col);
111            }
112            Move::Raw { row, col } => self.set_cursor_quiet(row, col),
113        }
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::Move;
120    use crate::Editor;
121    use crate::types::{DefaultHost, Options};
122    use hjkl_buffer::View;
123
124    fn editor(text: &str) -> Editor<View, DefaultHost> {
125        Editor::new(View::from_str(text), DefaultHost::new(), Options::default())
126    }
127
128    /// `Vertical` reads `sticky_col`, clamps to the row, and leaves the
129    /// un-clamped want in place so a later long row can restore it.
130    #[test]
131    fn vertical_clamps_but_preserves_the_unclamped_want() {
132        // row 0 is long, row 1 is short, row 2 is long again.
133        let mut e = editor("abcdefghij\nab\nabcdefghij");
134        e.move_cursor(Move::Horizontal { col: 7 });
135        assert_eq!(e.cursor(), (0, 7));
136        assert_eq!(e.sticky_col(), Some(7));
137
138        // Down onto the short row: the cursor clamps to its last char...
139        e.move_cursor(Move::Vertical { row: 1 });
140        assert_eq!(e.cursor(), (1, 1));
141        // ...but the want survives un-clamped.
142        assert_eq!(e.sticky_col(), Some(7));
143
144        // Down again onto a long row: the original column comes back.
145        e.move_cursor(Move::Vertical { row: 2 });
146        assert_eq!(e.cursor(), (2, 7));
147        assert_eq!(e.sticky_col(), Some(7));
148    }
149
150    /// An empty row collapses to column 0 and still keeps the want.
151    #[test]
152    fn vertical_over_an_empty_row_collapses_to_col_zero() {
153        let mut e = editor("abcdef\n\nabcdef");
154        e.move_cursor(Move::Horizontal { col: 4 });
155        e.move_cursor(Move::Vertical { row: 1 });
156        assert_eq!(e.cursor(), (1, 0));
157        assert_eq!(e.sticky_col(), Some(4));
158        e.move_cursor(Move::Vertical { row: 2 });
159        assert_eq!(e.cursor(), (2, 4));
160    }
161
162    /// With no `sticky_col` yet, `Vertical` bootstraps from the current column.
163    #[test]
164    fn vertical_bootstraps_the_want_from_the_current_column() {
165        let mut e = editor("abcdef\nabcdef");
166        e.move_cursor(Move::Raw { row: 0, col: 3 });
167        assert_eq!(e.sticky_col(), None);
168        e.move_cursor(Move::Vertical { row: 1 });
169        assert_eq!(e.cursor(), (1, 3));
170        assert_eq!(e.sticky_col(), Some(3));
171    }
172
173    /// `Jump` sets the want to the column it landed on — the search-hit /
174    /// `gg` / mark rule, and the fix `c022a3a4` made structural.
175    #[test]
176    fn jump_sets_the_want_to_the_landed_column() {
177        let mut e = editor("abcdefghij\nabcdefghij");
178        e.move_cursor(Move::Horizontal { col: 9 });
179        assert_eq!(e.sticky_col(), Some(9));
180
181        e.move_cursor(Move::Jump { row: 1, col: 2 });
182        assert_eq!(e.cursor(), (1, 2));
183        assert_eq!(e.sticky_col(), Some(2), "a jump resets curswant");
184    }
185
186    /// `Horizontal` keeps the row and sets the want to the new column.
187    #[test]
188    fn horizontal_keeps_the_row_and_sets_the_want() {
189        let mut e = editor("abcdefghij\nabcdefghij");
190        e.move_cursor(Move::Jump { row: 1, col: 8 });
191        e.move_cursor(Move::Horizontal { col: 3 });
192        assert_eq!(e.cursor(), (1, 3));
193        assert_eq!(e.sticky_col(), Some(3));
194    }
195
196    /// `Raw` moves the cursor and leaves `sticky_col` exactly as it was —
197    /// including leaving it `None`.
198    #[test]
199    fn raw_leaves_the_want_untouched() {
200        let mut e = editor("abcdefghij\nabcdefghij");
201        e.move_cursor(Move::Horizontal { col: 6 });
202        assert_eq!(e.sticky_col(), Some(6));
203
204        e.move_cursor(Move::Raw { row: 1, col: 1 });
205        assert_eq!(e.cursor(), (1, 1));
206        assert_eq!(e.sticky_col(), Some(6), "Raw must not disturb curswant");
207
208        // And a `Raw` before anything has set a want leaves it unset.
209        let mut fresh = editor("abcdefghij");
210        fresh.move_cursor(Move::Raw { row: 0, col: 4 });
211        assert_eq!(fresh.cursor(), (0, 4));
212        assert_eq!(fresh.sticky_col(), None);
213    }
214
215    #[test]
216    fn vertical_bootstraps_display_want_from_the_current_column() {
217        let mut e = editor("\tabcdef\n\txyz");
218        e.move_cursor(Move::Raw { row: 0, col: 2 });
219        assert_eq!(e.sticky_col(), None);
220
221        e.move_cursor(Move::Vertical { row: 1 });
222        assert_eq!(e.cursor(), (1, 2));
223        assert_eq!(e.sticky_col(), Some(5));
224    }
225
226    /// Display columns are converted back to character columns before clamping,
227    /// so tabs do not make the cursor land too far right.
228    #[test]
229    fn vertical_converts_display_want_to_a_character_column() {
230        let mut e = editor("\tabcdef\n\txyz");
231        e.move_cursor(Move::Horizontal { col: 2 });
232        assert_eq!(e.sticky_col(), Some(5));
233
234        e.move_cursor(Move::Vertical { row: 1 });
235        assert_eq!(e.cursor(), (1, 2));
236        assert_eq!(e.sticky_col(), Some(5));
237    }
238
239    /// `Vertical` reproduces `apply_sticky_col`'s vertical branch exactly —
240    /// the property phases 2–4 rely on when they swap call sites over.
241    #[test]
242    fn vertical_matches_the_apply_sticky_col_clamp() {
243        for (want, row, expected) in [(7usize, 1usize, 1usize), (0, 1, 0), (1, 1, 1), (99, 0, 9)] {
244            let mut e = editor("abcdefghij\nab");
245            e.move_cursor(Move::Horizontal { col: 0 });
246            e.set_sticky_col(Some(want));
247            e.move_cursor(Move::Vertical { row });
248            assert_eq!(e.cursor(), (row, expected), "want {want} onto row {row}");
249            assert_eq!(e.sticky_col(), Some(want), "want {want} must survive");
250        }
251    }
252}