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