Skip to main content

vim_navigation/
command.rs

1//! Normal-mode command resolution independent of key bindings.
2//!
3//! [`MotionState`] owns only state that is required to turn a motion template
4//! into a completed [`Motion`]: a saturating decimal count, a pending `f`/`F`/
5//! `t`/`T` character argument, and the last completed character search used by
6//! `;` and `,`. It does not own terminal events, multi-key mapping timeouts,
7//! search queries, marks, jump lists, buffers, cursors, or viewports.
8//!
9//! A caller normally feeds count digits to [`MotionState::push_count_digit`],
10//! passes a bound motion to [`MotionState::finish`], and, after
11//! [`MotionResolution::AwaitingTarget`], routes the next eligible character to
12//! [`MotionState::accept_target`]. Mode/focus changes should call
13//! [`MotionState::reset_pending`] so an incomplete command cannot leak into a
14//! different input context. The last completed character search intentionally
15//! survives that reset.
16//!
17//! # Example
18//!
19//! ```
20//! use vim_navigation::command::{MotionResolution, MotionState};
21//! use vim_navigation::motion::{Motion, MotionKind};
22//!
23//! let mut state = MotionState::new();
24//! assert!(state.push_count_digit('3'));
25//! let MotionResolution::Ready(motion) =
26//!     state.finish(Motion::new(MotionKind::Right))
27//! else {
28//!     panic!("a non-targeted motion is immediately ready");
29//! };
30//! assert_eq!(motion.count(), 3);
31//! ```
32
33use crate::motion::FULL_PERCENT;
34use crate::{CountSource, Motion, MotionKind};
35
36/// The result of submitting a motion template to [`MotionState`].
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
38pub enum MotionResolution {
39    /// A complete motion is ready for [`crate::motion::apply`] or a caller adapter.
40    Ready(Motion),
41    /// A find or till motion is stored internally and awaits one character.
42    AwaitingTarget,
43    /// `;` or `,` was requested before any character search was completed.
44    ///
45    /// The pending decimal count, if any, has already been consumed.
46    Unavailable,
47}
48
49/// Normal-mode state shared across configurable key adapters.
50///
51/// This type owns the Vim semantics of decimal counts, `%` and `G` count
52/// reinterpretation, find/till character arguments, and `;`/`,` repetition.
53/// Terminal key events and application-specific bindings remain adapter
54/// concerns. The state has no I/O and no caller-controlled panic path.
55#[derive(Debug, Default)]
56pub struct MotionState {
57    count: Option<usize>,
58    awaiting_target: Option<Motion>,
59    last_character_search: Option<Motion>,
60}
61
62impl MotionState {
63    /// Creates empty Normal-mode command state with no repeatable search.
64    #[must_use]
65    pub const fn new() -> Self {
66        Self {
67            count: None,
68            awaiting_target: None,
69            last_character_search: None,
70        }
71    }
72
73    /// Reports whether a non-zero decimal count has started.
74    ///
75    /// A leading `0` is deliberately not a count; callers can bind it to
76    /// [`MotionKind::LineStart`].
77    #[must_use]
78    pub const fn has_count(&self) -> bool {
79        self.count.is_some()
80    }
81
82    /// Adds an ASCII digit to the pending count with saturating arithmetic.
83    ///
84    /// Returns `false` for non-digits and for a leading zero, which lets an
85    /// adapter interpret that key as Vim's `0` motion instead. Once the parsed
86    /// value reaches [`usize::MAX`], further digits keep it at that value.
87    pub fn push_count_digit(&mut self, digit: char) -> bool {
88        let Some(value) = digit.to_digit(10) else {
89            return false;
90        };
91        if value == 0 && self.count.is_none() {
92            return false;
93        }
94        // Vim counts are conceptually unbounded decimal input. Saturation keeps
95        // pathological input deterministic without overflow or a parse error.
96        self.count = Some(
97            self.count
98                .unwrap_or(0)
99                .saturating_mul(10)
100                .saturating_add(value as usize),
101        );
102        true
103    }
104
105    /// Takes a pending count for a non-motion command such as jump history.
106    ///
107    /// This does not cancel a pending character-argument motion or forget the
108    /// last completed character search.
109    pub fn take_count(&mut self) -> Option<usize> {
110        self.count.take()
111    }
112
113    /// Reports whether a find or till target character is pending.
114    #[must_use]
115    pub const fn is_awaiting_target(&self) -> bool {
116        self.awaiting_target.is_some()
117    }
118
119    /// Completes a motion template using the current count and repeat state.
120    ///
121    /// The pending count is always consumed. Vim-specific reinterpretations
122    /// happen here: counted `%` becomes a clamped buffer percentage, and
123    /// counted `G`/`gg` selects the supplied one-based line. Find/till motions
124    /// without a target return [`MotionResolution::AwaitingTarget`]; those with
125    /// a target immediately become the source for `;` and `,` repetition.
126    ///
127    /// While a target is pending, the caller must use [`Self::accept_target`]
128    /// or [`Self::reset_pending`] before submitting an unrelated command.
129    pub fn finish(&mut self, motion: Motion) -> MotionResolution {
130        let count = self.count.take();
131        let source = if count.is_some() {
132            CountSource::Explicit
133        } else {
134            CountSource::Implicit
135        };
136        let mut motion = motion.counted(count.unwrap_or(1), source);
137        // `%` changes meaning in Vim when prefixed by a count: it becomes an
138        // absolute percentage rather than delimiter matching.
139        if motion.kind() == MotionKind::MatchingPair && motion.has_explicit_count() {
140            motion = Motion::new(MotionKind::BufferPercentage)
141                .counted(motion.count().min(FULL_PERCENT), CountSource::Explicit);
142        }
143        // A count before either `gg` or `G` is a one-based absolute line.
144        if matches!(
145            motion.kind(),
146            MotionKind::BufferTop | MotionKind::BufferBottom
147        ) && motion.has_explicit_count()
148        {
149            motion =
150                Motion::new(MotionKind::BufferTop).counted(motion.count(), CountSource::Explicit);
151        }
152        if matches!(
153            motion.kind(),
154            MotionKind::FindForward
155                | MotionKind::FindBackward
156                | MotionKind::TillForward
157                | MotionKind::TillBackward
158        ) {
159            if motion.target().is_none() {
160                self.awaiting_target = Some(motion);
161                return MotionResolution::AwaitingTarget;
162            }
163            self.last_character_search = Some(motion);
164        }
165        if matches!(
166            motion.kind(),
167            MotionKind::RepeatCharacterSearch | MotionKind::ReverseCharacterSearch
168        ) {
169            let Some(mut repeated) = self.last_character_search else {
170                return MotionResolution::Unavailable;
171            };
172            if motion.kind() == MotionKind::ReverseCharacterSearch {
173                let Some(target) = repeated.target() else {
174                    return MotionResolution::Unavailable;
175                };
176                let source = if motion.has_explicit_count() {
177                    CountSource::Explicit
178                } else {
179                    CountSource::Implicit
180                };
181                repeated = Motion::new(reverse_character_search(repeated.kind()))
182                    .counted(motion.count(), source)
183                    .targeting(target);
184            } else {
185                let source = if motion.has_explicit_count() {
186                    CountSource::Explicit
187                } else {
188                    CountSource::Implicit
189                };
190                repeated = repeated.counted(motion.count(), source);
191            }
192            return MotionResolution::Ready(repeated.repeating());
193        }
194        MotionResolution::Ready(motion)
195    }
196
197    /// Supplies the character argument for a pending find or till motion.
198    ///
199    /// Returns `None` when no motion is waiting. Any Unicode scalar is accepted;
200    /// whether it exists in the current line is decided when the motion is
201    /// applied. A completed motion becomes the source for `;` and `,`.
202    pub fn accept_target(&mut self, target: char) -> Option<Motion> {
203        let motion = self.awaiting_target.take()?.targeting(target);
204        self.last_character_search = Some(motion);
205        Some(motion)
206    }
207
208    /// Cancels only the pending count and character argument.
209    ///
210    /// The last completed character search remains available to `;` and `,`,
211    /// matching Vim when an unrelated or cancelled command follows it.
212    pub fn reset_pending(&mut self) {
213        self.count = None;
214        self.awaiting_target = None;
215    }
216}
217
218fn reverse_character_search(kind: MotionKind) -> MotionKind {
219    match kind {
220        MotionKind::FindForward => MotionKind::FindBackward,
221        MotionKind::FindBackward => MotionKind::FindForward,
222        MotionKind::TillForward => MotionKind::TillBackward,
223        MotionKind::TillBackward => MotionKind::TillForward,
224        _ => kind,
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::{MotionResolution, MotionState};
231    use crate::{CountSource, Motion, MotionKind};
232
233    #[test]
234    fn a_pre_targeted_search_becomes_the_repeat_source() {
235        let mut state = MotionState::new();
236        let search = Motion::new(MotionKind::FindForward).targeting('界');
237        assert_eq!(state.finish(search), MotionResolution::Ready(search));
238        assert_eq!(
239            state.finish(Motion::new(MotionKind::RepeatCharacterSearch)),
240            MotionResolution::Ready(search.repeating())
241        );
242        assert_eq!(
243            state.finish(Motion::new(MotionKind::ReverseCharacterSearch)),
244            MotionResolution::Ready(
245                Motion::new(MotionKind::FindBackward)
246                    .targeting('界')
247                    .repeating()
248            )
249        );
250    }
251
252    #[test]
253    fn counts_saturate_and_zero_remains_a_motion_without_a_prefix() {
254        let mut state = MotionState::new();
255        assert!(!state.push_count_digit('0'));
256        assert!(state.push_count_digit('1'));
257        assert!(state.push_count_digit('2'));
258        assert_eq!(
259            state.finish(Motion::new(MotionKind::WordForward)),
260            MotionResolution::Ready(
261                Motion::new(MotionKind::WordForward).counted(12, CountSource::Explicit)
262            )
263        );
264        for _ in 0..usize::BITS {
265            assert!(state.push_count_digit('9'));
266        }
267        let MotionResolution::Ready(motion) = state.finish(Motion::new(MotionKind::Right)) else {
268            panic!("counted motion should be ready");
269        };
270        assert_eq!(motion.count(), usize::MAX);
271    }
272
273    #[test]
274    fn character_targets_repeat_and_survive_pending_resets() {
275        let mut state = MotionState::new();
276        assert_eq!(
277            state.finish(Motion::new(MotionKind::TillForward)),
278            MotionResolution::AwaitingTarget
279        );
280        assert_eq!(
281            state.accept_target('x'),
282            Some(Motion::new(MotionKind::TillForward).targeting('x'))
283        );
284        assert!(state.push_count_digit('2'));
285        let MotionResolution::Ready(repeated) =
286            state.finish(Motion::new(MotionKind::RepeatCharacterSearch))
287        else {
288            panic!("repeat should use the last character search");
289        };
290        assert_eq!(repeated.kind(), MotionKind::TillForward);
291        assert_eq!(repeated.count(), 2);
292        assert!(repeated.is_repeated());
293
294        state.reset_pending();
295        let MotionResolution::Ready(reversed) =
296            state.finish(Motion::new(MotionKind::ReverseCharacterSearch))
297        else {
298            panic!("reverse repeat should survive pending resets");
299        };
300        assert_eq!(reversed.kind(), MotionKind::TillBackward);
301        assert_eq!(reversed.target(), Some('x'));
302    }
303
304    #[test]
305    fn counted_percent_and_g_use_vim_interpretations() {
306        let mut state = MotionState::new();
307        assert!(state.push_count_digit('5'));
308        assert_eq!(
309            state.finish(Motion::new(MotionKind::MatchingPair)),
310            MotionResolution::Ready(
311                Motion::new(MotionKind::BufferPercentage).counted(5, CountSource::Explicit)
312            )
313        );
314        assert!(state.push_count_digit('4'));
315        assert_eq!(
316            state.finish(Motion::new(MotionKind::BufferBottom)),
317            MotionResolution::Ready(
318                Motion::new(MotionKind::BufferTop).counted(4, CountSource::Explicit)
319            )
320        );
321    }
322}