escriba_runtime/operator_pending.rs
1//! The operator-pending FSM — vim's `{count}{operator}{count}{motion}`
2//! key composition.
3//!
4//! After the `d`/`c`/`y` key ([`Action::Operator`]) the editor *waits* for a
5//! motion; the next motion key composes into an [`Action::ApplyOperator`] the
6//! runtime executes (the engine built in `apply_operator`). This is a pure
7//! `(State, Event) -> (State, effects)` machine, so it **stands on the fleet
8//! `zenmai` primitive** (the same Mealy-machine-with-effects abstraction
9//! `bolso-core` and `gaveta-client-core::Escort` use) rather than re-rolling a
10//! bespoke `Option<Operator>` + scattered `if let`s in the dispatch path.
11//!
12//! **Counts compose here, not in a naive repeat loop.** The `Event` and
13//! `Effect` are `(Action, count)`: the machine consumes the resolved action +
14//! its count off the keymap, and emits the action(s) the runtime should run +
15//! *how many times*. A bare motion (`5j`) passes through carrying its count; an
16//! operated motion multiplies the two counts (`3d2w` = delete `3 × 2 = 6`
17//! words), because vim's operator count and motion count multiply.
18
19use escriba_core::{Action, Operator};
20
21/// Operator-pending state. `Resting` = normal; `Awaiting { op, count }` = an
22/// operator key was pressed (with `count`, default 1) and the next motion will
23/// be operated over.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub enum OpState {
26 #[default]
27 Resting,
28 Awaiting {
29 op: Operator,
30 count: u32,
31 },
32 /// `d/` — an operator is armed AND a search prompt is open.
33 ///
34 /// Without this state the prompt's own keys (the typed pattern, Backspace,
35 /// history) hit the "anything else cancels" arm and the operator
36 /// evaporated on the very first character, so `d/foo<CR>` silently did
37 /// nothing. The operator has to survive an arbitrary number of keystrokes
38 /// here, which is exactly why it needs a state rather than a guard.
39 AwaitingSearch {
40 op: Operator,
41 count: u32,
42 },
43}
44
45/// The zenmai machine. A ZST marker; the reducer is [`Self::step`]. The
46/// `(Action, u32)` event/effect pair is the action and its repetition count.
47pub struct OperatorPending;
48
49impl zenmai::Machine for OperatorPending {
50 type State = OpState;
51 /// The resolved action and its count (from the keymap's `CountedAction`).
52 type Event = (Action, u32);
53 /// The action the runtime should execute and how many times. Empty = the
54 /// key was consumed (an operator began, or a pending operator was cancelled).
55 type Effect = (Action, u32);
56
57 fn step(state: &OpState, event: (Action, u32)) -> (OpState, Vec<(Action, u32)>) {
58 let (action, count) = event;
59 match (state, action) {
60 // A stray `Pending` (mid-sequence key) never disturbs operator
61 // state and runs nothing — the runtime's own sequence buffer owns it.
62 (s, Action::Pending) => (*s, vec![]),
63
64 // Resting: an operator key arms the machine (capturing its count);
65 // everything else passes straight through carrying its own count.
66 (OpState::Resting, Action::Operator(op)) => (OpState::Awaiting { op, count }, vec![]),
67 (OpState::Resting, other) => (OpState::Resting, vec![(other, count)]),
68
69 // Awaiting a motion: the motion composes into ApplyOperator, applied
70 // `op_count × motion_count` times (the two vim counts multiply).
71 (
72 OpState::Awaiting {
73 op,
74 count: op_count,
75 },
76 Action::Move(motion),
77 ) => (
78 OpState::Resting,
79 vec![(
80 Action::ApplyOperator { op: *op, motion },
81 op_count.saturating_mul(count).max(1),
82 )],
83 ),
84
85 // Awaiting + `/` or `?`: open the prompt and STAY ARMED. This arm
86 // is the whole fix — it used to fall into the catch-all below,
87 // which disarmed the operator and dropped the key.
88 (
89 OpState::Awaiting {
90 op,
91 count: op_count,
92 },
93 Action::SearchOpen(dir),
94 ) => (
95 OpState::AwaitingSearch {
96 op: *op,
97 count: *op_count,
98 },
99 vec![(Action::SearchOpen(dir), 1)],
100 ),
101
102 // Prompt editing passes through untouched while the operator waits.
103 (
104 OpState::AwaitingSearch { .. },
105 a
106 @ (Action::InsertChar(_) | Action::PromptBackspace | Action::PromptHistory { .. }),
107 ) => (*state, vec![(a, 1)]),
108
109 // `<CR>` resolves the operand. Emitted as ONE action rather than
110 // "commit, then operate": committing MOVES the cursor, which would
111 // destroy the operator's start point before the operator ran.
112 (
113 OpState::AwaitingSearch {
114 op,
115 count: op_count,
116 },
117 Action::SubmitCommand,
118 ) => (
119 OpState::Resting,
120 vec![(Action::SearchSubmitOperated { op: *op }, *op_count)],
121 ),
122
123 // Esc disarms both the prompt and the operator.
124 (OpState::AwaitingSearch { .. }, Action::ChangeMode(m)) => {
125 (OpState::Resting, vec![(Action::ChangeMode(m), 1)])
126 }
127
128 // Any other key while a search operand is being typed disarms the
129 // operator but still runs the key — dropping it silently is what
130 // made `d/` feel broken.
131 (OpState::AwaitingSearch { .. }, other) => (OpState::Resting, vec![(other, count)]),
132
133 // Awaiting + anything-not-a-motion cancels the operator and drops
134 // the key (vim: `d` then a non-motion does nothing). Covers Esc
135 // (ChangeMode), operator-doubling `dd` (linewise — deferred), and
136 // any other key.
137 (OpState::Awaiting { .. }, _) => (OpState::Resting, vec![]),
138 }
139 }
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145 use escriba_core::{Mode, Motion};
146 use zenmai::Machine;
147
148 #[test]
149 fn operator_then_motion_composes_apply_operator() {
150 // `d` arms (count 1), `w` composes `dw` once.
151 let (s, fx) =
152 OperatorPending::step(&OpState::Resting, (Action::Operator(Operator::Delete), 1));
153 assert_eq!(
154 s,
155 OpState::Awaiting {
156 op: Operator::Delete,
157 count: 1
158 }
159 );
160 assert!(fx.is_empty(), "the operator key runs nothing, it waits");
161
162 let (s, fx) = OperatorPending::step(&s, (Action::Move(Motion::WordStartNext), 1));
163 assert_eq!(s, OpState::Resting);
164 assert_eq!(
165 fx,
166 vec![(
167 Action::ApplyOperator {
168 op: Operator::Delete,
169 motion: Motion::WordStartNext
170 },
171 1
172 )]
173 );
174 }
175
176 #[test]
177 fn operator_count_multiplies_the_motion() {
178 // `3dw` = delete 3 words: the operator's count (3) flows to the
179 // composed motion as the repetition count.
180 let (s, _) =
181 OperatorPending::step(&OpState::Resting, (Action::Operator(Operator::Delete), 3));
182 assert_eq!(
183 s,
184 OpState::Awaiting {
185 op: Operator::Delete,
186 count: 3
187 }
188 );
189 let (_, fx) = OperatorPending::step(&s, (Action::Move(Motion::WordStartNext), 1));
190 assert_eq!(
191 fx,
192 vec![(
193 Action::ApplyOperator {
194 op: Operator::Delete,
195 motion: Motion::WordStartNext
196 },
197 3
198 )]
199 );
200 }
201
202 #[test]
203 fn operator_and_motion_counts_multiply() {
204 // `3d2w` = delete 3×2 = 6 words.
205 let (s, _) =
206 OperatorPending::step(&OpState::Resting, (Action::Operator(Operator::Delete), 3));
207 let (_, fx) = OperatorPending::step(&s, (Action::Move(Motion::WordStartNext), 2));
208 assert_eq!(fx[0].1, 6, "operator count × motion count");
209 }
210
211 #[test]
212 fn bare_motion_passes_through_carrying_its_count() {
213 // `5j` is not an operated motion — it passes through with count 5.
214 let (s, fx) = OperatorPending::step(&OpState::Resting, (Action::Move(Motion::Down), 5));
215 assert_eq!(s, OpState::Resting);
216 assert_eq!(fx, vec![(Action::Move(Motion::Down), 5)]);
217 }
218
219 #[test]
220 fn esc_cancels_a_pending_operator_and_drops_the_key() {
221 let (s, fx) = OperatorPending::step(
222 &OpState::Awaiting {
223 op: Operator::Change,
224 count: 1,
225 },
226 (Action::ChangeMode(Mode::Normal), 1),
227 );
228 assert_eq!(s, OpState::Resting, "Esc cancels the operator");
229 assert!(fx.is_empty(), "the cancel key is dropped");
230 }
231
232 #[test]
233 fn pending_never_disturbs_operator_state() {
234 // A stray Pending while awaiting keeps the operator armed (a multi-key
235 // motion like `gg` builds in the runtime's sequence buffer first).
236 let (s, fx) = OperatorPending::step(
237 &OpState::Awaiting {
238 op: Operator::Yank,
239 count: 1,
240 },
241 (Action::Pending, 1),
242 );
243 assert_eq!(
244 s,
245 OpState::Awaiting {
246 op: Operator::Yank,
247 count: 1
248 }
249 );
250 assert!(fx.is_empty());
251 }
252
253 #[test]
254 fn inert_on_a_doubled_operator_dd_deferred() {
255 // `dd` (linewise) is deferred — a second operator cancels for now.
256 let (s, fx) = OperatorPending::step(
257 &OpState::Awaiting {
258 op: Operator::Delete,
259 count: 1,
260 },
261 (Action::Operator(Operator::Delete), 1),
262 );
263 assert_eq!(s, OpState::Resting);
264 assert!(fx.is_empty());
265 }
266}