escriba_core/action.rs
1use escriba_search::Direction as SearchDirection;
2use schemars::JsonSchema;
3use serde::{Deserialize, Serialize};
4
5use crate::edit::Edit;
6use crate::mode::Mode;
7use crate::motion::TextObject;
8use crate::motion::{Motion, Operator};
9
10/// A fully-resolved editor action — what the keymap emits, what the buffer
11/// consumes.
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
13pub enum Action {
14 /// Move every cursor by `motion`.
15 Move(Motion),
16 /// Begin an operator (the `d`/`c`/`y` key). The editor enters
17 /// operator-pending: the next motion composes into an [`Action::ApplyOperator`].
18 /// Resolved by the operator-pending FSM, never executed directly.
19 Operator(Operator),
20 /// Apply a pending operator over a motion (delete-word, yank-line, etc.).
21 ApplyOperator {
22 op: Operator,
23 motion: Motion,
24 },
25 /// Apply a primitive edit at each cursor.
26 Edit(Edit),
27 /// Enter the given mode.
28 ChangeMode(Mode),
29 /// Run a named command (via the command registry).
30 Command {
31 name: String,
32 args: Vec<String>,
33 },
34 /// Insert a character at each caret. Separate from Edit so the keymap
35 /// can stay ignorant of rope details.
36 InsertChar(char),
37 /// Submit a minibuffer / command-mode line (e.g. `:w`, `:q`).
38 SubmitCommand,
39 /// Undo / redo one change.
40 Undo,
41 Redo,
42 /// Save the current buffer.
43 Save,
44 /// Quit the editor.
45 Quit,
46 // ── search (vim `/`, `?`, `n`, `N`, `*`, `#`) ──────────────────────
47 /// Open the search prompt in `direction` (the `/` and `?` keys).
48 ///
49 /// The prompt reuses `Mode::Command` rather than adding a mode variant:
50 /// vim's `/` IS the command-line with a different prompt character, and
51 /// this module's own doc states new modes are layered through pending
52 /// state, not new variants. `SearchState`'s typed `Option<Prompt>` is what
53 /// disambiguates a `<CR>` that submits a search from one that submits an
54 /// ex-command — a discriminator that cannot be forgotten, unlike a bool.
55 SearchOpen(SearchDirection),
56 /// `n` (`reverse = false`) / `N` (`reverse = true`) — jump to the next
57 /// match, relative to the direction the search was committed with, so `N`
58 /// after a `?` search moves forward.
59 SearchRepeat {
60 reverse: bool,
61 },
62 /// `*` (`reverse = false`) / `#` (`reverse = true`) — search the whole word
63 /// under the cursor. Literal, not regex: the word may contain `.` or `[`
64 /// and the user means those characters.
65 SearchWord {
66 reverse: bool,
67 },
68 /// `:noh` — stop highlighting matches while keeping the pattern, so `n`
69 /// still works. Distinct from cancelling a search.
70 ClearSearchHighlight,
71
72 /// `d/foo<CR>` — commit the open search prompt and apply `op` from the
73 /// prompt's ORIGIN to wherever the search lands.
74 ///
75 /// Emitted only by the operator-pending machine; no keymap produces it.
76 /// It exists because committing a search MOVES the cursor, and the
77 /// operator needs the pre-move position as its start point. Carrying the
78 /// operator through the commit makes "operate over a search" one atomic
79 /// action instead of two steps racing to own the cursor.
80 SearchSubmitOperated {
81 op: Operator,
82 },
83
84 /// `gn` / `gN` — the next/previous match AS AN OBJECT.
85 ///
86 /// Not a motion. A motion resolves to a POINT and an operator acts over
87 /// `[cursor, point)`; `gn` names an EXTENT that need not start at the
88 /// cursor, so `dgn` deletes the whole match wherever it is. That
89 /// distinction is why this is its own action rather than a `Motion`
90 /// variant — folding it into `Motion` would silently give
91 /// `[cursor, match.start)`, which deletes the text BEFORE the match.
92 TextObject(TextObject),
93
94 /// `{operator}gn` — apply `op` over a text object's extent.
95 ///
96 /// Emitted only by the operator-pending machine.
97 ApplyOperatorObject {
98 op: Operator,
99 object: TextObject,
100 },
101
102 /// `.` — repeat the last text change.
103 ///
104 /// Vim's most-used key, and the half that makes `cgn` a workflow rather
105 /// than a curiosity: `cgn` changes the next match, then `.` changes the
106 /// one after it, giving a per-instance confirmable rename with no
107 /// multi-cursor machinery.
108 RepeatLastChange,
109
110 /// `<C-o>` — walk back to where the last far jump was taken from.
111 ///
112 /// Lives beside the search actions because search is what made it
113 /// necessary — committing a `/` used to be a one-way door — but it is not
114 /// a search action: `G`, `gg`, `%` and tag jumps are the other consumers.
115 JumpBack,
116 /// `<C-i>` — walk forward again after [`Action::JumpBack`].
117 JumpForward,
118 /// Backspace inside a command-line or search prompt.
119 ///
120 /// Key::Backspace was previously bound in NO mode, so the minibuffer could
121 /// be typed into but never corrected — a typo meant Esc and start again.
122 /// One action serves both prompts; the runtime routes it by whether a
123 /// search prompt is open.
124 PromptBackspace,
125
126 /// Move the caret inside an open prompt (`←` `→` `Home` `End`).
127 ///
128 /// The prompt was append-only until this existed, so a typo in the middle
129 /// of a pattern could only be fixed by deleting back to it.
130 PromptCaret {
131 to: escriba_search::CaretMove,
132 },
133 /// `<C-g>` / `<C-t>` — step the search PREVIEW to the next/previous
134 /// match without committing.
135 ///
136 /// Distinct from `n` in the one way that matters: this is still
137 /// cancellable. Escape returns to where the search started, which `n`
138 /// after a commit cannot do.
139 SearchPreviewStep {
140 forward: bool,
141 },
142 /// `<Del>` — delete the character AT the prompt caret.
143 PromptDelete,
144 /// `<C-w>` — delete the word before the prompt caret.
145 PromptDeleteWord,
146 /// `<C-u>` — delete from the prompt caret back to the start.
147 PromptClearToStart,
148 /// Up/Down inside a prompt — walk search history.
149 ///
150 /// `back = true` is older. Stepping forward past the newest entry restores
151 /// the text that was being typed when browsing began, so arrowing through
152 /// history and back never destroys a half-typed pattern.
153 PromptHistory {
154 back: bool,
155 },
156 /// No-op — used when a key sequence is pending but not yet complete.
157 Pending,
158}
159
160/// An [`Action`] with an optional repetition count (vim's `5dd`, `10k`).
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
162pub struct CountedAction {
163 pub count: u32,
164 pub action: Action,
165}
166
167impl CountedAction {
168 #[must_use]
169 pub fn once(action: Action) -> Self {
170 Self { count: 1, action }
171 }
172
173 #[must_use]
174 pub fn repeated(count: u32, action: Action) -> Self {
175 Self {
176 count: count.max(1),
177 action,
178 }
179 }
180}
181
182/// Whether an action can change buffer TEXT.
183///
184/// This exists so that anything cached against the buffer's contents — today
185/// the search-match set, tomorrow anything else derived from it — is
186/// invalidated by construction rather than by remembering to. Search
187/// highlights were stale after every edit precisely because that invalidation
188/// was a thing to remember: `SearchState::refresh` existed and had zero
189/// callers, so inserting four characters repainted the highlight four columns
190/// off.
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
192pub enum TextEffect {
193 /// May edit the active buffer. Derived state must be recomputed.
194 Mutates,
195 /// Cannot edit the active buffer.
196 Preserves,
197}
198
199impl Action {
200 /// Classify this action's effect on buffer text.
201 ///
202 /// **Total over `Action` — no wildcard arm.** A new variant fails to
203 /// compile here rather than silently defaulting to "preserves", which is
204 /// the direction that produces a stale-cache bug rather than a slow one.
205 ///
206 /// Deliberately CONSERVATIVE where a variant's reach is open-ended:
207 /// `Command`/`SubmitCommand` can run an ex-command that edits, and the
208 /// keymap's `PromptBackspace` doubles as the buffer Backspace outside a
209 /// prompt. Over-reporting costs one extra scan; under-reporting paints
210 /// the wrong columns, so the asymmetry decides the doubtful cases.
211 #[must_use]
212 pub const fn text_effect(&self) -> TextEffect {
213 match self {
214 Self::Edit(_)
215 | Self::InsertChar(_)
216 | Self::ApplyOperator { .. }
217 | Self::ApplyOperatorObject { .. }
218 | Self::Undo
219 | Self::Redo
220 | Self::PromptBackspace
221 | Self::PromptDelete
222 | Self::PromptDeleteWord
223 | Self::PromptClearToStart
224 | Self::TextObject(_)
225 | Self::Command { .. }
226 | Self::SearchSubmitOperated { .. }
227 | Self::RepeatLastChange
228 | Self::SubmitCommand => TextEffect::Mutates,
229
230 Self::Move(_)
231 | Self::Operator(_)
232 | Self::ChangeMode(_)
233 | Self::Save
234 | Self::Quit
235 | Self::SearchOpen(_)
236 | Self::SearchRepeat { .. }
237 | Self::SearchWord { .. }
238 | Self::ClearSearchHighlight
239 | Self::JumpBack
240 | Self::JumpForward
241 | Self::PromptCaret { .. }
242 | Self::PromptHistory { .. }
243 | Self::SearchPreviewStep { .. }
244 | Self::Pending => TextEffect::Preserves,
245 }
246 }
247}
248
249/// What an action does to search HIGHLIGHTING.
250///
251/// vim leaves `hlsearch` lit until `:nohlsearch`, which is why nearly every
252/// published vimrc remaps something to `:noh` — the highlight has done its job
253/// the moment you start editing, and leaving it on turns the buffer into
254/// confetti. escriba clears it on the first action that is plainly not part of
255/// searching.
256///
257/// Clearing SUPPRESSES without forgetting: the pattern survives, so `n` still
258/// works and re-lights.
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
260pub enum HighlightEffect {
261 /// Search highlighting stays as it is.
262 Keep,
263 /// Stop drawing highlights (the pattern is retained).
264 Clear,
265}
266
267impl Action {
268 /// Classify this action's effect on search highlighting.
269 ///
270 /// **Total over `Action` — no wildcard arm.** "We forgot to clear on the
271 /// new command" becomes unconstructible rather than remembered: adding a
272 /// variant forces the decision here.
273 #[must_use]
274 pub const fn highlight_effect(&self) -> HighlightEffect {
275 match self {
276 // Everything that IS searching, or that is operating the prompt.
277 Self::SearchOpen(_)
278 | Self::SearchRepeat { .. }
279 | Self::SearchWord { .. }
280 | Self::SearchSubmitOperated { .. }
281 | Self::ClearSearchHighlight
282 | Self::TextObject(_)
283 | Self::SearchPreviewStep { .. }
284 | Self::PromptHistory { .. }
285 | Self::PromptBackspace
286 | Self::PromptCaret { .. }
287 | Self::PromptDelete
288 | Self::PromptDeleteWord
289 | Self::PromptClearToStart
290 | Self::InsertChar(_)
291 | Self::SubmitCommand
292 | Self::Pending
293 // A jump is how you USE the matches; extinguishing them mid-walk
294 // would defeat the purpose.
295 | Self::JumpBack
296 | Self::JumpForward
297 // Arming an operator is not yet a move — `d` then `n` must still
298 // see its matches.
299 | Self::Operator(_)
300 | Self::Save
301 | Self::Quit => HighlightEffect::Keep,
302
303 // A search MOTION is searching, not moving on — `n` must not
304 // extinguish the matches it is walking. Every other motion is a
305 // departure.
306 //
307 // The `_` here is deliberate and is the SAFE direction, unlike
308 // `text_effect`'s: a motion nobody has classified yet is "moving
309 // on", which at worst clears a highlight early. The opposite
310 // default would leave stale confetti on screen.
311 // Entering Insert begins editing, so the search is over. Every
312 // OTHER mode change is navigation or a CANCEL — and a cancel must
313 // not erase the committed pattern's highlights. Both
314 // `SearchState::cancel` and the runtime's own `ChangeMode` arm
315 // promise that in writing ("cancelling a new search must not erase
316 // the old highlights"), and a blanket `Clear` here landed on top of
317 // the cancel it had just performed: `/foo<CR>` then `/bar<Esc>`
318 // silently extinguished `foo`.
319 //
320 // Total over `Mode`, so a new mode must decide.
321 Self::ChangeMode(m) => match m {
322 Mode::Insert => HighlightEffect::Clear,
323 Mode::Normal | Mode::Visual | Mode::VisualLine | Mode::Command => {
324 HighlightEffect::Keep
325 }
326 },
327
328 Self::Move(m) => match m {
329 Motion::SearchNext | Motion::SearchPrev => HighlightEffect::Keep,
330 _ => HighlightEffect::Clear,
331 },
332
333 // Moving on, or changing the text: the search is over.
334 Self::ApplyOperator { .. }
335 | Self::ApplyOperatorObject { .. }
336 | Self::RepeatLastChange
337 | Self::Edit(_)
338 | Self::Command { .. }
339 | Self::Undo
340 | Self::Redo => HighlightEffect::Clear,
341 }
342 }
343}
344
345impl Action {
346 /// Does this action edit or navigate an OPEN PROMPT, rather than doing
347 /// something to the buffer?
348 ///
349 /// The operator-pending machine needs this: during `d/foo` the operator
350 /// must survive every keystroke that is part of composing the pattern, and
351 /// disarm on anything that is not.
352 ///
353 /// **Total over `Action` — no wildcard arm**, and that totality is the
354 /// whole point. The machine originally listed the prompt actions inline;
355 /// when `PromptCaret`, `PromptDelete`, `PromptDeleteWord`,
356 /// `PromptClearToStart` and `SearchPreviewStep` were added later, none was
357 /// added to that list, so pressing `←` or `<C-g>` midway through `d/foo`
358 /// silently disarmed the operator — reintroducing exactly the defect the
359 /// `AwaitingSearch` state had been created to fix. A new prompt action now
360 /// cannot be added without deciding here.
361 #[must_use]
362 pub const fn edits_prompt(&self) -> bool {
363 match self {
364 Self::InsertChar(_)
365 | Self::PromptBackspace
366 | Self::PromptHistory { .. }
367 | Self::PromptCaret { .. }
368 | Self::PromptDelete
369 | Self::PromptDeleteWord
370 | Self::PromptClearToStart
371 | Self::SearchPreviewStep { .. } => true,
372
373 Self::Move(_)
374 | Self::Operator(_)
375 | Self::ApplyOperator { .. }
376 | Self::ApplyOperatorObject { .. }
377 | Self::TextObject(_)
378 | Self::Edit(_)
379 | Self::ChangeMode(_)
380 | Self::Command { .. }
381 | Self::SubmitCommand
382 | Self::Undo
383 | Self::Redo
384 | Self::Save
385 | Self::Quit
386 | Self::SearchOpen(_)
387 | Self::SearchRepeat { .. }
388 | Self::SearchWord { .. }
389 | Self::SearchSubmitOperated { .. }
390 | Self::ClearSearchHighlight
391 | Self::RepeatLastChange
392 | Self::JumpBack
393 | Self::JumpForward
394 | Self::Pending => false,
395 }
396 }
397}