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