vim_navigation/motion.rs
1//! Read-only Vim cursor and viewport motion.
2//!
3//! This module owns the coordinate types and pure movement vocabulary used by
4//! both direct callers and the crate's optional editable buffer. [`apply`]
5//! borrows a logical line snapshot, clamps the supplied [`Cursor`] to a valid
6//! UTF-8 boundary, applies one completed [`Motion`], and updates [`Viewport`]
7//! so the result remains visible. It never changes the input text.
8//!
9//! # Coordinates
10//!
11//! [`Cursor::byte_column`] is a zero-based UTF-8 byte offset, not a character
12//! index or screen column. [`Viewport::left`] and [`Viewport::width`] are
13//! terminal display cells. A tab advances to the next four-cell tab stop;
14//! wide and combining Unicode characters use their terminal widths. Empty
15//! input and empty lines have the single valid cursor position `(line, 0)`.
16//!
17//! Count parsing, incomplete commands, and character-search repetition belong
18//! to [`crate::command`]. Text mutation and Insert-mode cursor rules belong to
19//! [`crate::editor`]. Search histories, marks, jump lists, terminal keys, and
20//! application resources remain caller-owned.
21//!
22//! # Example
23//!
24//! ```
25//! use vim_navigation::motion::{Cursor, Motion, MotionKind, Viewport, apply};
26//!
27//! let lines = ["\tç"];
28//! let mut viewport = Viewport::new(0, 0, 1, 8, 0);
29//! let cursor = apply(
30//! &lines,
31//! Cursor::new(99, 2), // invalid line and inside the three-byte `ç`
32//! &mut viewport,
33//! Motion::new(MotionKind::LineEnd),
34//! );
35//! assert_eq!(cursor, Cursor::new(0, 1));
36//! ```
37
38mod buffer;
39mod engine;
40mod line;
41#[cfg(test)]
42mod tests;
43
44pub(crate) use engine::reveal_cursor_line;
45pub use engine::{apply, reveal};
46
47/// A zero-based text position whose column is a UTF-8 byte offset.
48///
49/// Construction is deliberately unchecked so adapters can store a cursor
50/// before their next text snapshot is available. [`apply`] and [`reveal`]
51/// clamp an out-of-range line to the final logical line and round a byte inside
52/// a UTF-8 scalar backward to its start. On non-empty lines a byte column at or
53/// beyond the line length clamps to the final scalar; empty lines use column
54/// zero.
55#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
56pub struct Cursor {
57 line: usize,
58 byte_column: usize,
59}
60
61impl Cursor {
62 /// Creates a cursor without consulting any text.
63 ///
64 /// The next call to [`apply`] or [`reveal`] performs the documented
65 /// boundary clamping.
66 #[must_use]
67 pub const fn new(line: usize, byte_column: usize) -> Self {
68 Self { line, byte_column }
69 }
70
71 /// Returns the zero-based line.
72 #[must_use]
73 pub const fn line(self) -> usize {
74 self.line
75 }
76
77 /// Returns the zero-based UTF-8 byte column.
78 #[must_use]
79 pub const fn byte_column(self) -> usize {
80 self.byte_column
81 }
82}
83
84/// A completed Vim movement with its count and optional character argument.
85///
86/// Use [`crate::MotionState`] when counts and character arguments arrive as
87/// separate key events. Constructing a `Motion` directly is useful when an
88/// adapter has already resolved its command language. A target is meaningful
89/// only to character find/till, unmatched-delimiter, and method motions; other
90/// motions safely ignore it. Method motions use target `'M'` for closing braces
91/// (`[M`/`]M`) and otherwise select opening braces (`[m`/`]m`).
92#[derive(Clone, Copy, Debug, Eq, PartialEq)]
93pub struct Motion {
94 kind: MotionKind,
95 count: usize,
96 explicit_count: bool,
97 target: Option<char>,
98 repeated: bool,
99}
100
101impl Motion {
102 /// Creates an uncounted movement template with an effective count of one.
103 #[must_use]
104 pub const fn new(kind: MotionKind) -> Self {
105 Self {
106 kind,
107 count: 1,
108 explicit_count: false,
109 target: None,
110 repeated: false,
111 }
112 }
113
114 /// Returns the operation.
115 #[must_use]
116 pub const fn kind(self) -> MotionKind {
117 self.kind
118 }
119
120 /// Returns the normalized count, which is always at least one.
121 #[must_use]
122 pub const fn count(self) -> usize {
123 self.count
124 }
125
126 /// Reports whether the user supplied a count.
127 ///
128 /// This is semantically distinct from [`Self::count`]: Vim interprets an
129 /// explicit `1G`, `1%`, or `1z` command differently from its uncounted
130 /// form even though both carry the numeric value one.
131 #[must_use]
132 pub const fn has_explicit_count(self) -> bool {
133 self.explicit_count
134 }
135
136 /// Returns the character argument for find, till, delimiter, or method movement.
137 #[must_use]
138 pub const fn target(self) -> Option<char> {
139 self.target
140 }
141
142 /// Attaches a normalized count and records whether it was explicit.
143 ///
144 /// A zero count is normalized to one. Counts produced from decimal input
145 /// should normally come from [`crate::MotionState`], which also saturates
146 /// overflow and applies Vim's counted-command reinterpretations.
147 #[must_use]
148 pub const fn counted(mut self, count: usize, explicit: bool) -> Self {
149 self.count = if count == 0 { 1 } else { count };
150 self.explicit_count = explicit;
151 self
152 }
153
154 /// Attaches a Unicode scalar character or delimiter argument.
155 #[must_use]
156 pub const fn targeting(mut self, target: char) -> Self {
157 self.target = Some(target);
158 self
159 }
160
161 /// Marks a find/till movement as a `;` or `,` repetition.
162 ///
163 /// Repeated till motions have a Vim-specific adjacent-match exception;
164 /// callers should set this through [`crate::MotionState`] rather than
165 /// emulating it by issuing the original motion again.
166 #[must_use]
167 pub const fn repeating(mut self) -> Self {
168 self.repeated = true;
169 self
170 }
171
172 /// Reports whether this movement repeats a prior character search.
173 #[must_use]
174 pub const fn is_repeated(self) -> bool {
175 self.repeated
176 }
177}
178
179/// Vim's standalone cursor and viewport movement vocabulary.
180///
181/// Most variants are handled entirely by [`apply`]. Search and mark variants
182/// are vocabulary signals for adapters because their resources intentionally
183/// remain outside this crate; direct `apply` calls leave the cursor unchanged
184/// for those variants. [`crate::MotionState`] resolves the two character-search
185/// repetition variants to a concrete find/till motion before application.
186#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
187pub enum MotionKind {
188 /// `h` or Left.
189 Left,
190 /// Backspace or Ctrl-H when `'whichwrap'` permits crossing lines.
191 LeftWrap,
192 /// `l` or Right.
193 Right,
194 /// Space when `'whichwrap'` permits crossing lines.
195 RightWrap,
196 /// `k`, Up, or Ctrl-P.
197 Up,
198 /// `j`, Down, Ctrl-J, Ctrl-N, or newline.
199 Down,
200 /// `0` or Home.
201 LineStart,
202 /// `^`.
203 FirstNonBlank,
204 /// `$` or End.
205 LineEnd,
206 /// `g_`.
207 LastNonBlank,
208 /// `g0`.
209 ScreenLineStart,
210 /// `g^`.
211 ScreenFirstNonBlank,
212 /// `g$`.
213 ScreenLineEnd,
214 /// `g<End>`.
215 ScreenLastNonBlank,
216 /// `gm`.
217 ScreenMiddle,
218 /// `gM`.
219 LineMiddle,
220 /// `|`.
221 Column,
222 /// `go`.
223 ByteOffset,
224 /// `w`.
225 WordForward,
226 /// `W`.
227 BigWordForward,
228 /// `e`.
229 WordEndForward,
230 /// `E`.
231 BigWordEndForward,
232 /// `b`.
233 WordBackward,
234 /// `B`.
235 BigWordBackward,
236 /// `ge`.
237 WordEndBackward,
238 /// `gE`.
239 BigWordEndBackward,
240 /// `f{char}`.
241 FindForward,
242 /// `F{char}`.
243 FindBackward,
244 /// `t{char}`.
245 TillForward,
246 /// `T{char}`.
247 TillBackward,
248 /// `;`, resolved by [`crate::MotionState`].
249 RepeatCharacterSearch,
250 /// `,`, resolved by [`crate::MotionState`].
251 ReverseCharacterSearch,
252 /// `-`.
253 PreviousLineFirstNonBlank,
254 /// `+` or Enter.
255 NextLineFirstNonBlank,
256 /// `_`.
257 CountedLineFirstNonBlank,
258 /// `gg` or Ctrl-Home.
259 BufferTop,
260 /// `G`.
261 BufferBottom,
262 /// Ctrl-End.
263 BufferBottomEnd,
264 /// `{count}%`.
265 BufferPercentage,
266 /// `H`.
267 WindowTop,
268 /// `M`.
269 WindowMiddle,
270 /// `L`.
271 WindowBottom,
272 /// `(`.
273 SentenceBackward,
274 /// `)`.
275 SentenceForward,
276 /// `{`.
277 ParagraphBackward,
278 /// `}`.
279 ParagraphForward,
280 /// `[[`.
281 SectionStartBackward,
282 /// `]]`.
283 SectionStartForward,
284 /// `[]`.
285 SectionEndBackward,
286 /// `][`.
287 SectionEndForward,
288 /// `%` without a count.
289 MatchingPair,
290 /// `g%`.
291 MatchingPairBackward,
292 /// `[(` or `[{`; the delimiter is stored in [`Motion::target`].
293 UnmatchedOpenBackward,
294 /// `])` or `]}`; the delimiter is stored in [`Motion::target`].
295 UnmatchedCloseForward,
296 /// `[m` or `[M`.
297 MethodBackward,
298 /// `]m` or `]M`.
299 MethodForward,
300 /// `[#`.
301 PreprocessorBackward,
302 /// `]#`.
303 PreprocessorForward,
304 /// `[*` or `[/`.
305 CommentBackward,
306 /// `]*` or `]/`.
307 CommentForward,
308 /// `[c` in diff text.
309 DiffChangeBackward,
310 /// `]c` in diff text.
311 DiffChangeForward,
312 /// `n`, applied by the caller's retained search state.
313 SearchNext,
314 /// `N`, applied by the caller's retained search state.
315 SearchPrevious,
316 /// `*`, applied by the caller's retained search state.
317 SearchWordForward,
318 /// `#`, applied by the caller's retained search state.
319 SearchWordBackward,
320 /// `g*`, applied by the caller's retained search state.
321 SearchPartialWordForward,
322 /// `g#`, applied by the caller's retained search state.
323 SearchPartialWordBackward,
324 /// `['`, applied by the caller's resource-aware mark store.
325 PreviousMarkLine,
326 /// `` [` ``, applied by the caller's resource-aware mark store.
327 PreviousMarkExact,
328 /// `]'`, applied by the caller's resource-aware mark store.
329 NextMarkLine,
330 /// `` ]` ``, applied by the caller's resource-aware mark store.
331 NextMarkExact,
332 /// Ctrl-D.
333 HalfPageDown,
334 /// Ctrl-U.
335 HalfPageUp,
336 /// Ctrl-F or PageDown.
337 PageDown,
338 /// Ctrl-B or PageUp.
339 PageUp,
340 /// Ctrl-E.
341 ScrollLineDown,
342 /// Ctrl-Y.
343 ScrollLineUp,
344 /// `zt`.
345 CursorToWindowTop,
346 /// `z<CR>`.
347 CursorToWindowTopFirstNonBlank,
348 /// `zz`.
349 CursorToWindowMiddle,
350 /// `z.`.
351 CursorToWindowMiddleFirstNonBlank,
352 /// `zb`.
353 CursorToWindowBottom,
354 /// `z-`.
355 CursorToWindowBottomFirstNonBlank,
356 /// `z+`.
357 NextWindowTop,
358 /// `z^`.
359 PreviousWindowBottom,
360 /// `zh`.
361 ScrollColumnLeft,
362 /// `zl`.
363 ScrollColumnRight,
364 /// `zH`.
365 ScrollHalfScreenLeft,
366 /// `zL`.
367 ScrollHalfScreenRight,
368 /// `zs`.
369 CursorToWindowLeft,
370 /// `ze`.
371 CursorToWindowRight,
372}
373
374/// The visible part of a text pane, including any rendered gutter columns.
375///
376/// `top` is a zero-based logical line. `left`, `width`, `gutter`, and the
377/// retained desired column are terminal display cells, not UTF-8 byte columns.
378/// The viewport does not own wrapping or rendered text: callers supply the
379/// same logical line snapshot to [`apply`] that they display.
380#[derive(Clone, Copy, Debug, Eq, PartialEq)]
381pub struct Viewport {
382 top: usize,
383 left: usize,
384 height: usize,
385 width: usize,
386 gutter: usize,
387 desired_column: Option<usize>,
388}
389
390impl Viewport {
391 /// Creates a viewport in terminal display cells.
392 ///
393 /// Zero `height` or `width` is normalized to one so reveal calculations
394 /// remain total. `top` and `left` may initially be beyond the supplied
395 /// text; motion application clamps or adjusts them as needed.
396 #[must_use]
397 pub fn new(top: usize, left: usize, height: usize, width: usize, gutter: usize) -> Self {
398 Self {
399 top,
400 left,
401 height: height.max(1),
402 width: width.max(1),
403 gutter,
404 desired_column: None,
405 }
406 }
407
408 /// Restores the desired display column retained by vertical motions.
409 ///
410 /// `None` derives the first desired column from the current cursor. After
411 /// each motion, [`apply`] stores the column needed for a later `j` or `k`;
412 /// callers preserving a viewport between calls normally do not need to set
413 /// this themselves.
414 #[must_use]
415 pub fn with_desired_column(mut self, desired_column: Option<usize>) -> Self {
416 self.desired_column = desired_column;
417 self
418 }
419
420 /// Returns the zero-based first visible logical line.
421 #[must_use]
422 pub const fn top(&self) -> usize {
423 self.top
424 }
425
426 /// Returns the first visible terminal column, including the gutter.
427 #[must_use]
428 pub const fn left(&self) -> usize {
429 self.left
430 }
431
432 /// Returns the viewport height in logical lines (always at least one).
433 #[must_use]
434 pub const fn height(&self) -> usize {
435 self.height
436 }
437
438 /// Returns the viewport width in terminal display cells (always at least one).
439 #[must_use]
440 pub const fn width(&self) -> usize {
441 self.width
442 }
443
444 /// Returns the rendered gutter width in terminal display cells.
445 #[must_use]
446 pub const fn gutter(&self) -> usize {
447 self.gutter
448 }
449
450 /// Returns the retained source-text display column used by vertical motions.
451 #[must_use]
452 pub const fn desired_column(&self) -> Option<usize> {
453 self.desired_column
454 }
455}