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 + a text OBJECT composes over its extent, not over a
86 // range ending at the cursor. `dgn` deletes the match wherever it
87 // is; a motion-shaped composition would delete up to it instead.
88 (
89 OpState::Awaiting {
90 op,
91 count: op_count,
92 },
93 Action::TextObject(object),
94 ) => (
95 OpState::Resting,
96 vec![(
97 Action::ApplyOperatorObject { op: *op, object },
98 op_count.saturating_mul(count).max(1),
99 )],
100 ),
101
102 // Awaiting + `/` or `?`: open the prompt and STAY ARMED. This arm
103 // is the whole fix — it used to fall into the catch-all below,
104 // which disarmed the operator and dropped the key.
105 (
106 OpState::Awaiting {
107 op,
108 count: op_count,
109 },
110 Action::SearchOpen(dir),
111 ) => (
112 OpState::AwaitingSearch {
113 op: *op,
114 count: *op_count,
115 },
116 vec![(Action::SearchOpen(dir), 1)],
117 ),
118
119 // Prompt editing passes through untouched while the operator waits.
120 (
121 OpState::AwaitingSearch { .. },
122 a
123 @ (Action::InsertChar(_) | Action::PromptBackspace | Action::PromptHistory { .. }),
124 ) => (*state, vec![(a, 1)]),
125
126 // `<CR>` resolves the operand. Emitted as ONE action rather than
127 // "commit, then operate": committing MOVES the cursor, which would
128 // destroy the operator's start point before the operator ran.
129 (
130 OpState::AwaitingSearch {
131 op,
132 count: op_count,
133 },
134 Action::SubmitCommand,
135 ) => (
136 OpState::Resting,
137 vec![(Action::SearchSubmitOperated { op: *op }, *op_count)],
138 ),
139
140 // Esc disarms both the prompt and the operator.
141 (OpState::AwaitingSearch { .. }, Action::ChangeMode(m)) => {
142 (OpState::Resting, vec![(Action::ChangeMode(m), 1)])
143 }
144
145 // Any other key while a search operand is being typed disarms the
146 // operator but still runs the key — dropping it silently is what
147 // made `d/` feel broken.
148 (OpState::AwaitingSearch { .. }, other) => (OpState::Resting, vec![(other, count)]),
149
150 // Awaiting + anything-not-a-motion cancels the operator and drops
151 // the key (vim: `d` then a non-motion does nothing). Covers Esc
152 // (ChangeMode), operator-doubling `dd` (linewise — deferred), and
153 // any other key.
154 (OpState::Awaiting { .. }, _) => (OpState::Resting, vec![]),
155 }
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162 use escriba_core::{Mode, Motion};
163 use zenmai::Machine;
164
165 #[test]
166 fn operator_then_motion_composes_apply_operator() {
167 // `d` arms (count 1), `w` composes `dw` once.
168 let (s, fx) =
169 OperatorPending::step(&OpState::Resting, (Action::Operator(Operator::Delete), 1));
170 assert_eq!(
171 s,
172 OpState::Awaiting {
173 op: Operator::Delete,
174 count: 1
175 }
176 );
177 assert!(fx.is_empty(), "the operator key runs nothing, it waits");
178
179 let (s, fx) = OperatorPending::step(&s, (Action::Move(Motion::WordStartNext), 1));
180 assert_eq!(s, OpState::Resting);
181 assert_eq!(
182 fx,
183 vec![(
184 Action::ApplyOperator {
185 op: Operator::Delete,
186 motion: Motion::WordStartNext
187 },
188 1
189 )]
190 );
191 }
192
193 #[test]
194 fn operator_count_multiplies_the_motion() {
195 // `3dw` = delete 3 words: the operator's count (3) flows to the
196 // composed motion as the repetition count.
197 let (s, _) =
198 OperatorPending::step(&OpState::Resting, (Action::Operator(Operator::Delete), 3));
199 assert_eq!(
200 s,
201 OpState::Awaiting {
202 op: Operator::Delete,
203 count: 3
204 }
205 );
206 let (_, fx) = OperatorPending::step(&s, (Action::Move(Motion::WordStartNext), 1));
207 assert_eq!(
208 fx,
209 vec![(
210 Action::ApplyOperator {
211 op: Operator::Delete,
212 motion: Motion::WordStartNext
213 },
214 3
215 )]
216 );
217 }
218
219 #[test]
220 fn operator_and_motion_counts_multiply() {
221 // `3d2w` = delete 3×2 = 6 words.
222 let (s, _) =
223 OperatorPending::step(&OpState::Resting, (Action::Operator(Operator::Delete), 3));
224 let (_, fx) = OperatorPending::step(&s, (Action::Move(Motion::WordStartNext), 2));
225 assert_eq!(fx[0].1, 6, "operator count × motion count");
226 }
227
228 #[test]
229 fn bare_motion_passes_through_carrying_its_count() {
230 // `5j` is not an operated motion — it passes through with count 5.
231 let (s, fx) = OperatorPending::step(&OpState::Resting, (Action::Move(Motion::Down), 5));
232 assert_eq!(s, OpState::Resting);
233 assert_eq!(fx, vec![(Action::Move(Motion::Down), 5)]);
234 }
235
236 #[test]
237 fn esc_cancels_a_pending_operator_and_drops_the_key() {
238 let (s, fx) = OperatorPending::step(
239 &OpState::Awaiting {
240 op: Operator::Change,
241 count: 1,
242 },
243 (Action::ChangeMode(Mode::Normal), 1),
244 );
245 assert_eq!(s, OpState::Resting, "Esc cancels the operator");
246 assert!(fx.is_empty(), "the cancel key is dropped");
247 }
248
249 #[test]
250 fn pending_never_disturbs_operator_state() {
251 // A stray Pending while awaiting keeps the operator armed (a multi-key
252 // motion like `gg` builds in the runtime's sequence buffer first).
253 let (s, fx) = OperatorPending::step(
254 &OpState::Awaiting {
255 op: Operator::Yank,
256 count: 1,
257 },
258 (Action::Pending, 1),
259 );
260 assert_eq!(
261 s,
262 OpState::Awaiting {
263 op: Operator::Yank,
264 count: 1
265 }
266 );
267 assert!(fx.is_empty());
268 }
269
270 #[test]
271 fn inert_on_a_doubled_operator_dd_deferred() {
272 // `dd` (linewise) is deferred — a second operator cancels for now.
273 let (s, fx) = OperatorPending::step(
274 &OpState::Awaiting {
275 op: Operator::Delete,
276 count: 1,
277 },
278 (Action::Operator(Operator::Delete), 1),
279 );
280 assert_eq!(s, OpState::Resting);
281 assert!(fx.is_empty());
282 }
283}