Skip to main content

escriba_command/
ex.rs

1//! The ex-command NAME GRAMMAR — vim's abbreviations, resolved in one place.
2//!
3//! `:wq` is not a command name. It is a *spelling* of one, and vim has a
4//! whole grammar of them: every ex command has a full name, a minimum prefix
5//! that selects it, and an optional `!`. `:w`, `:wr`, `:writ`, `:write` are
6//! one command; `:q`, `:qu`, `:quit` are another; `:qa` and `:quita` are a
7//! third, and the reason `:qu` is not the third is that `quitall`'s minimum
8//! is five characters, not one.
9//!
10//! The runtime used to carry that knowledge as three arms —
11//! `"w" => "save", "q" => "quit", "u" => "undo"` — and every other spelling
12//! fell through to a registry lookup that could not possibly hold it. `:wq`
13//! reported "command not found" while both halves of it worked.
14//!
15//! So the grammar is a TABLE, not a chain of ifs, and the table is the only
16//! thing that knows how a typed word becomes a registered command. Two
17//! properties follow, and both are asserted rather than asserted-to:
18//!
19//! - **Every valid abbreviation resolves.** For each verb, every prefix from
20//!   its minimum to its full spelling selects it (`abbreviations_all_resolve`).
21//! - **No abbreviation is ambiguous.** No typed word is a valid abbreviation
22//!   of two verbs (`no_abbreviation_is_ambiguous`) — which is a property of
23//!   the *minimums*, and the reason vim gives `quitall` a five-character one.
24//!
25//! A word the grammar does not know is passed through UNCHANGED to the
26//! registry, so `:noh`, `:picker.files` and every plugin-registered command
27//! still dispatch. The grammar covers the vim vocabulary; it does not fence
28//! the command namespace.
29
30/// One ex command's spelling rule.
31///
32/// `plain` and `forced` are separate registered command names rather than one
33/// name plus a bang argument. A command body receives `&[String]` and nothing
34/// else, so a bang passed as an argument is a convention every body has to
35/// remember to read — and the one that forgets quits without asking. Two
36/// names cannot be misread, and both show up in `--commands` saying what they
37/// do. Verbs for which `!` changes nothing (writing has no force semantics
38/// here — escriba has no read-only flag to override) point both fields at the
39/// same command, which is the honest encoding of "the bang is accepted and
40/// means nothing".
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct ExVerb {
43    /// The full spelling, as `:help ex-cmd-index` writes it.
44    pub full: &'static str,
45    /// The fewest characters that select it. `full[..min]` is what vim
46    /// prints in square-bracket notation: `:q[uit]` is `("quit", 1)`.
47    pub min: usize,
48    /// The registered command the plain form dispatches to.
49    pub plain: &'static str,
50    /// The registered command the `!` form dispatches to.
51    pub forced: &'static str,
52}
53
54impl ExVerb {
55    /// Does `word` spell this verb? Prefix of the full name, at least `min`
56    /// characters long — vim's rule exactly.
57    #[must_use]
58    pub fn spelled_by(&self, word: &str) -> bool {
59        word.len() >= self.min && self.full.len() >= word.len() && self.full.starts_with(word)
60    }
61
62    /// The command name for this verb, banged or not.
63    #[must_use]
64    pub const fn command(&self, bang: bool) -> &'static str {
65        if bang { self.forced } else { self.plain }
66    }
67}
68
69/// The vim write/quit family plus the two verbs the old three-arm table
70/// carried, with vim's own minimum prefixes.
71///
72/// Deliberately NOT the whole ex vocabulary: a verb belongs here once escriba
73/// has something for it to dispatch to. An entry naming a command that is not
74/// registered would report "declared but not implemented yet" — announced,
75/// per [`crate::CommandError::Unhandled`], but still a promise the editor
76/// cannot keep.
77pub const VERBS: &[ExVerb] = &[
78    // ── write ────────────────────────────────────────────────────────
79    ExVerb { full: "write", min: 1, plain: "save", forced: "save" },
80    ExVerb { full: "wall", min: 2, plain: "buffer.write-all", forced: "buffer.write-all" },
81    // ── write-and-quit ───────────────────────────────────────────────
82    ExVerb { full: "wq", min: 2, plain: "write-quit", forced: "write-quit" },
83    ExVerb { full: "wqall", min: 3, plain: "write-quit-all", forced: "write-quit-all" },
84    // `:x` differs from `:wq` by ONE thing and it is the thing that matters
85    // to anything watching the file: it writes only when the buffer is
86    // modified, so `:x` on an untouched file leaves the mtime alone and a
87    // watching build does not rebuild.
88    ExVerb { full: "xit", min: 1, plain: "exit-write", forced: "exit-write" },
89    ExVerb { full: "xall", min: 2, plain: "write-quit-all", forced: "write-quit-all" },
90    ExVerb { full: "exit", min: 3, plain: "exit-write", forced: "exit-write" },
91    // ── quit ─────────────────────────────────────────────────────────
92    ExVerb { full: "quit", min: 1, plain: "quit", forced: "quit!" },
93    ExVerb { full: "qall", min: 2, plain: "quit-all", forced: "quit-all!" },
94    ExVerb { full: "quitall", min: 5, plain: "quit-all", forced: "quit-all!" },
95    // ── the two the old table carried ────────────────────────────────
96    ExVerb { full: "undo", min: 1, plain: "undo", forced: "undo" },
97    ExVerb { full: "redo", min: 3, plain: "redo", forced: "redo" },
98];
99
100/// The verb `word` spells, if any. `word` carries no `!` and no arguments.
101#[must_use]
102pub fn resolve(word: &str) -> Option<&'static ExVerb> {
103    VERBS.iter().find(|v| v.spelled_by(word))
104}
105
106/// A parsed ex line: which command to run, and with what.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct Invocation {
109    /// The registered command name to dispatch.
110    pub command: String,
111    /// Everything after the command word.
112    pub args: Vec<String>,
113}
114
115/// Parse a command line into the command to dispatch and its arguments.
116///
117/// `None` for an empty line — `:` then `<CR>` does nothing, as in vim, rather
118/// than dispatching the empty name and reporting it missing.
119///
120/// A word the grammar knows resolves through [`VERBS`]; anything else is
121/// passed through with its `!` intact, so what the operator typed is what the
122/// "not found" report names. Silently stripping a bang off an unknown word
123/// would turn `:Ghost!` into a report about `:Ghost`, which is a report about
124/// a different thing than the one that failed.
125#[must_use]
126pub fn parse(line: &str) -> Option<Invocation> {
127    let line = line.trim();
128    let line = line.strip_prefix(':').unwrap_or(line);
129    let mut parts = line.split_whitespace();
130    let word = parts.next()?;
131    let args: Vec<String> = parts.map(str::to_string).collect();
132    let (head, bang) = word
133        .strip_suffix('!')
134        .map_or((word, false), |stripped| (stripped, true));
135    let command = resolve(head).map_or_else(|| word.to_string(), |v| v.command(bang).to_string());
136    Some(Invocation { command, args })
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    /// Every abbreviation vim would accept reaches its verb. This is the
144    /// all-variants proof: it walks the table rather than sampling it, so a
145    /// verb added with a wrong `min` fails here rather than in an operator's
146    /// hands.
147    #[test]
148    fn abbreviations_all_resolve() {
149        for v in VERBS {
150            for len in v.min..=v.full.len() {
151                let word = &v.full[..len];
152                assert_eq!(
153                    resolve(word),
154                    Some(v),
155                    "`:{word}` must resolve to `{}`",
156                    v.full,
157                );
158            }
159        }
160    }
161
162    /// No typed word spells two verbs. Ambiguity here is invisible in normal
163    /// use — [`resolve`] takes the first match, so the SECOND verb simply
164    /// becomes unreachable at that spelling, which nothing else would notice.
165    #[test]
166    fn no_abbreviation_is_ambiguous() {
167        for v in VERBS {
168            for len in v.min..=v.full.len() {
169                let word = &v.full[..len];
170                let hits: Vec<&str> = VERBS
171                    .iter()
172                    .filter(|c| c.spelled_by(word))
173                    .map(|c| c.full)
174                    .collect();
175                assert_eq!(hits.len(), 1, "`:{word}` is ambiguous: {hits:?}");
176            }
177        }
178    }
179
180    /// A shorter-than-minimum prefix resolves to nothing rather than to the
181    /// wrong thing. `:q` must never be `:qall`.
182    #[test]
183    fn below_the_minimum_selects_nothing() {
184        for v in VERBS {
185            for len in 1..v.min {
186                let word = &v.full[..len];
187                let hit = resolve(word);
188                assert!(
189                    hit.is_none_or(|h| h.full != v.full),
190                    "`:{word}` is below `{}`'s minimum and must not select it",
191                    v.full,
192                );
193            }
194        }
195    }
196
197    #[test]
198    fn the_write_quit_family_reaches_its_commands() {
199        for (typed, expect) in [
200            ("w", "save"),
201            ("write", "save"),
202            ("wq", "write-quit"),
203            ("wq!", "write-quit"),
204            ("wqa", "write-quit-all"),
205            ("wqall", "write-quit-all"),
206            ("x", "exit-write"),
207            ("xit", "exit-write"),
208            ("xa", "write-quit-all"),
209            ("exi", "exit-write"),
210            ("exit", "exit-write"),
211            ("wa", "buffer.write-all"),
212            ("q", "quit"),
213            ("q!", "quit!"),
214            ("quit", "quit"),
215            ("qa", "quit-all"),
216            ("qa!", "quit-all!"),
217            ("quita", "quit-all"),
218            ("quitall", "quit-all"),
219            ("u", "undo"),
220            ("red", "redo"),
221        ] {
222            assert_eq!(
223                parse(typed).map(|i| i.command),
224                Some(expect.to_string()),
225                "`:{typed}`",
226            );
227        }
228    }
229
230    #[test]
231    fn a_leading_colon_and_surrounding_space_are_not_part_of_the_name() {
232        assert_eq!(parse(":wq").map(|i| i.command), Some("write-quit".into()));
233        assert_eq!(parse("  wq  ").map(|i| i.command), Some("write-quit".into()));
234    }
235
236    #[test]
237    fn an_empty_line_dispatches_nothing() {
238        assert_eq!(parse(""), None);
239        assert_eq!(parse("   "), None);
240        assert_eq!(parse(":"), None);
241    }
242
243    #[test]
244    fn an_unknown_word_passes_through_with_its_bang() {
245        // Registry names must survive the grammar untouched…
246        assert_eq!(parse("noh").map(|i| i.command), Some("noh".into()));
247        assert_eq!(
248            parse("picker.files").map(|i| i.command),
249            Some("picker.files".into()),
250        );
251        // …and an unknown bang is reported as the operator typed it.
252        assert_eq!(parse("Ghost!").map(|i| i.command), Some("Ghost!".into()));
253    }
254
255    #[test]
256    fn arguments_survive_the_verb() {
257        let i = parse("w  foo.txt  bar").expect("a verb with arguments parses");
258        assert_eq!(i.command, "save");
259        assert_eq!(i.args, vec!["foo.txt".to_string(), "bar".to_string()]);
260    }
261}