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 /// `<Del>` — delete the character AT the prompt caret.
134 PromptDelete,
135 /// `<C-w>` — delete the word before the prompt caret.
136 PromptDeleteWord,
137 /// `<C-u>` — delete from the prompt caret back to the start.
138 PromptClearToStart,
139 /// Up/Down inside a prompt — walk search history.
140 ///
141 /// `back = true` is older. Stepping forward past the newest entry restores
142 /// the text that was being typed when browsing began, so arrowing through
143 /// history and back never destroys a half-typed pattern.
144 PromptHistory {
145 back: bool,
146 },
147 /// No-op — used when a key sequence is pending but not yet complete.
148 Pending,
149}
150
151/// An [`Action`] with an optional repetition count (vim's `5dd`, `10k`).
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
153pub struct CountedAction {
154 pub count: u32,
155 pub action: Action,
156}
157
158impl CountedAction {
159 #[must_use]
160 pub fn once(action: Action) -> Self {
161 Self { count: 1, action }
162 }
163
164 #[must_use]
165 pub fn repeated(count: u32, action: Action) -> Self {
166 Self {
167 count: count.max(1),
168 action,
169 }
170 }
171}
172
173/// Whether an action can change buffer TEXT.
174///
175/// This exists so that anything cached against the buffer's contents — today
176/// the search-match set, tomorrow anything else derived from it — is
177/// invalidated by construction rather than by remembering to. Search
178/// highlights were stale after every edit precisely because that invalidation
179/// was a thing to remember: `SearchState::refresh` existed and had zero
180/// callers, so inserting four characters repainted the highlight four columns
181/// off.
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub enum TextEffect {
184 /// May edit the active buffer. Derived state must be recomputed.
185 Mutates,
186 /// Cannot edit the active buffer.
187 Preserves,
188}
189
190impl Action {
191 /// Classify this action's effect on buffer text.
192 ///
193 /// **Total over `Action` — no wildcard arm.** A new variant fails to
194 /// compile here rather than silently defaulting to "preserves", which is
195 /// the direction that produces a stale-cache bug rather than a slow one.
196 ///
197 /// Deliberately CONSERVATIVE where a variant's reach is open-ended:
198 /// `Command`/`SubmitCommand` can run an ex-command that edits, and the
199 /// keymap's `PromptBackspace` doubles as the buffer Backspace outside a
200 /// prompt. Over-reporting costs one extra scan; under-reporting paints
201 /// the wrong columns, so the asymmetry decides the doubtful cases.
202 #[must_use]
203 pub const fn text_effect(&self) -> TextEffect {
204 match self {
205 Self::Edit(_)
206 | Self::InsertChar(_)
207 | Self::ApplyOperator { .. }
208 | Self::ApplyOperatorObject { .. }
209 | Self::Undo
210 | Self::Redo
211 | Self::PromptBackspace
212 | Self::PromptDelete
213 | Self::PromptDeleteWord
214 | Self::PromptClearToStart
215 | Self::TextObject(_)
216 | Self::Command { .. }
217 | Self::SearchSubmitOperated { .. }
218 | Self::RepeatLastChange
219 | Self::ApplyOperatorObject { .. }
220 | Self::SubmitCommand => TextEffect::Mutates,
221
222 Self::Move(_)
223 | Self::Operator(_)
224 | Self::ChangeMode(_)
225 | Self::Save
226 | Self::Quit
227 | Self::SearchOpen(_)
228 | Self::SearchRepeat { .. }
229 | Self::SearchWord { .. }
230 | Self::ClearSearchHighlight
231 | Self::JumpBack
232 | Self::JumpForward
233 | Self::PromptCaret { .. }
234 | Self::PromptHistory { .. }
235 | Self::Pending => TextEffect::Preserves,
236 }
237 }
238}
239
240/// What an action does to search HIGHLIGHTING.
241///
242/// vim leaves `hlsearch` lit until `:nohlsearch`, which is why nearly every
243/// published vimrc remaps something to `:noh` — the highlight has done its job
244/// the moment you start editing, and leaving it on turns the buffer into
245/// confetti. escriba clears it on the first action that is plainly not part of
246/// searching.
247///
248/// Clearing SUPPRESSES without forgetting: the pattern survives, so `n` still
249/// works and re-lights.
250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
251pub enum HighlightEffect {
252 /// Search highlighting stays as it is.
253 Keep,
254 /// Stop drawing highlights (the pattern is retained).
255 Clear,
256}
257
258impl Action {
259 /// Classify this action's effect on search highlighting.
260 ///
261 /// **Total over `Action` — no wildcard arm.** "We forgot to clear on the
262 /// new command" becomes unconstructible rather than remembered: adding a
263 /// variant forces the decision here.
264 #[must_use]
265 pub const fn highlight_effect(&self) -> HighlightEffect {
266 match self {
267 // Everything that IS searching, or that is operating the prompt.
268 Self::SearchOpen(_)
269 | Self::SearchRepeat { .. }
270 | Self::SearchWord { .. }
271 | Self::SearchSubmitOperated { .. }
272 | Self::ClearSearchHighlight
273 | Self::TextObject(_)
274 | Self::PromptHistory { .. }
275 | Self::PromptBackspace
276 | Self::PromptCaret { .. }
277 | Self::PromptDelete
278 | Self::PromptDeleteWord
279 | Self::PromptClearToStart
280 | Self::InsertChar(_)
281 | Self::SubmitCommand
282 | Self::Pending
283 // A jump is how you USE the matches; extinguishing them mid-walk
284 // would defeat the purpose.
285 | Self::JumpBack
286 | Self::JumpForward
287 // Arming an operator is not yet a move — `d` then `n` must still
288 // see its matches.
289 | Self::Operator(_)
290 | Self::Save
291 | Self::Quit => HighlightEffect::Keep,
292
293 // A search MOTION is searching, not moving on — `n` must not
294 // extinguish the matches it is walking. Every other motion is a
295 // departure.
296 //
297 // The `_` here is deliberate and is the SAFE direction, unlike
298 // `text_effect`'s: a motion nobody has classified yet is "moving
299 // on", which at worst clears a highlight early. The opposite
300 // default would leave stale confetti on screen.
301 Self::Move(m) => match m {
302 Motion::SearchNext | Motion::SearchPrev => HighlightEffect::Keep,
303 _ => HighlightEffect::Clear,
304 },
305
306 // Moving on, or changing the text: the search is over.
307 Self::ApplyOperator { .. }
308 | Self::ApplyOperatorObject { .. }
309 | Self::RepeatLastChange
310 | Self::Edit(_)
311 | Self::ChangeMode(_)
312 | Self::Command { .. }
313 | Self::Undo
314 | Self::Redo => HighlightEffect::Clear,
315 }
316 }
317}