Skip to main content

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::ApplyOperatorObject { .. }
229            | Self::SubmitCommand => TextEffect::Mutates,
230
231            Self::Move(_)
232            | Self::Operator(_)
233            | Self::ChangeMode(_)
234            | Self::Save
235            | Self::Quit
236            | Self::SearchOpen(_)
237            | Self::SearchRepeat { .. }
238            | Self::SearchWord { .. }
239            | Self::ClearSearchHighlight
240            | Self::JumpBack
241            | Self::JumpForward
242            | Self::PromptCaret { .. }
243            | Self::PromptHistory { .. }
244            | Self::SearchPreviewStep { .. }
245            | Self::Pending => TextEffect::Preserves,
246        }
247    }
248}
249
250/// What an action does to search HIGHLIGHTING.
251///
252/// vim leaves `hlsearch` lit until `:nohlsearch`, which is why nearly every
253/// published vimrc remaps something to `:noh` — the highlight has done its job
254/// the moment you start editing, and leaving it on turns the buffer into
255/// confetti. escriba clears it on the first action that is plainly not part of
256/// searching.
257///
258/// Clearing SUPPRESSES without forgetting: the pattern survives, so `n` still
259/// works and re-lights.
260#[derive(Clone, Copy, Debug, PartialEq, Eq)]
261pub enum HighlightEffect {
262    /// Search highlighting stays as it is.
263    Keep,
264    /// Stop drawing highlights (the pattern is retained).
265    Clear,
266}
267
268impl Action {
269    /// Classify this action's effect on search highlighting.
270    ///
271    /// **Total over `Action` — no wildcard arm.** "We forgot to clear on the
272    /// new command" becomes unconstructible rather than remembered: adding a
273    /// variant forces the decision here.
274    #[must_use]
275    pub const fn highlight_effect(&self) -> HighlightEffect {
276        match self {
277            // Everything that IS searching, or that is operating the prompt.
278            Self::SearchOpen(_)
279            | Self::SearchRepeat { .. }
280            | Self::SearchWord { .. }
281            | Self::SearchSubmitOperated { .. }
282            | Self::ClearSearchHighlight
283            | Self::TextObject(_)
284            | Self::SearchPreviewStep { .. }
285            | Self::PromptHistory { .. }
286            | Self::PromptBackspace
287            | Self::PromptCaret { .. }
288            | Self::SearchPreviewStep { .. }
289            | Self::PromptDelete
290            | Self::PromptDeleteWord
291            | Self::PromptClearToStart
292            | Self::InsertChar(_)
293            | Self::SubmitCommand
294            | Self::Pending
295            // A jump is how you USE the matches; extinguishing them mid-walk
296            // would defeat the purpose.
297            | Self::JumpBack
298            | Self::JumpForward
299            // Arming an operator is not yet a move — `d` then `n` must still
300            // see its matches.
301            | Self::Operator(_)
302            | Self::Save
303            | Self::Quit => HighlightEffect::Keep,
304
305            // A search MOTION is searching, not moving on — `n` must not
306            // extinguish the matches it is walking. Every other motion is a
307            // departure.
308            //
309            // The `_` here is deliberate and is the SAFE direction, unlike
310            // `text_effect`'s: a motion nobody has classified yet is "moving
311            // on", which at worst clears a highlight early. The opposite
312            // default would leave stale confetti on screen.
313            Self::Move(m) => match m {
314                Motion::SearchNext | Motion::SearchPrev => HighlightEffect::Keep,
315                _ => HighlightEffect::Clear,
316            },
317
318            // Moving on, or changing the text: the search is over.
319            Self::ApplyOperator { .. }
320            | Self::ApplyOperatorObject { .. }
321            | Self::RepeatLastChange
322            | Self::Edit(_)
323            | Self::ChangeMode(_)
324            | Self::Command { .. }
325            | Self::Undo
326            | Self::Redo => HighlightEffect::Clear,
327        }
328    }
329}