Skip to main content

escriba_command/
lib.rs

1//! `escriba-command` — command registry + palette.
2
3extern crate self as escriba_command;
4
5use std::collections::HashMap;
6
7use escriba_core::BufferId;
8use escriba_madoguchi::cap::{Buffers, Cursor, Syntax};
9use escriba_madoguchi::{BufferView, Native, Negai, Outcome, Snapshot, View, caps, erase};
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12use thiserror::Error;
13
14#[derive(Debug, Error)]
15pub enum CommandError {
16    #[error("command not found: {0}")]
17    NotFound(String),
18    /// A registered command whose action symbol nothing implements yet.
19    ///
20    /// Distinct from [`NotFound`](Self::NotFound), and the distinction is the
21    /// point: `NotFound` means the operator typed a name that does not exist,
22    /// while `Unhandled` means the editor ADVERTISED a binding — it is in
23    /// `--commands`, it is in the keymap, `--list-rc` counts it — and then did
24    /// nothing. The second is the more misleading of the two and used to be
25    /// the silent one.
26    #[error("action `{0}` is declared but not implemented yet")]
27    Unhandled(String),
28    #[error("command failed: {0}")]
29    Failed(String),
30    /// An alias chain that never reaches a body.
31    ///
32    /// Aliases resolve THROUGH the registry, so `A -> B -> A` would spin
33    /// forever. Bounded fuel turns that into a typed report naming the chain
34    /// the operator wrote, instead of a hung editor.
35    #[error("alias cycle resolving `{0}`")]
36    AliasCycle(String),
37    // NOTE: there was a `Buffer(#[from] BufferError)` variant here. The M2
38    // port made it dead: a command no longer performs I/O, so it cannot
39    // produce a buffer error. Save/undo/redo failures now surface from the
40    // interpreter, which is the thing that actually touches the filesystem.
41}
42
43pub type Result<T> = std::result::Result<T, CommandError>;
44
45/// A command body.
46///
47/// Reads through the counter, returns slips. There is no `&mut` in this
48/// signature, which is the point: a command cannot reach editor state, so it
49/// cannot corrupt it. It replaces `fn(&mut EditContext, &[String])`, whose
50/// `&mut BufferSet` was simultaneously too much power and too little reach —
51/// the runtime still had to special-case `:noh` because `EditContext` could
52/// not see `SearchState`.
53pub type CommandFn = fn(&dyn Snapshot, &[String]) -> Outcome;
54
55/// How a command executes when invoked.
56///
57/// - [`Handler::Native`] wraps a compiled-in Rust `fn` — the
58///   built-in command set (`save`, `quit`, …).
59/// - [`Handler::Action`] carries a dotted action symbol
60///   (e.g. `"buffer.write-all"`, `"picker.files"`) authored via a
61///   Tatara-Lisp `(defcmd …)` form and resolved at run time by
62///   [`run_action`]. This is what lets `defcmd` register a real,
63///   invokable command without a compiled handler.
64///
65/// A future `Lisp(Thunk)` variant will carry a `tatara-lisp-eval`
66/// closure for fully-programmable commands — the imperative tier of
67/// the two-tier programmability model. Keeping the handler an enum
68/// (not a bare `fn`) is what makes that extension a one-variant add.
69#[derive(Debug, Clone)]
70pub enum Handler {
71    /// Compiled-in Rust handler.
72    Native(CommandFn),
73    /// Dotted action symbol resolved at run time (Lisp `defcmd`).
74    Action(String),
75}
76
77#[derive(Debug, Clone)]
78pub struct Command {
79    pub name: String,
80    pub description: String,
81    pub handler: Handler,
82}
83
84impl Command {
85    /// A built-in command backed by a compiled-in Rust `fn`.
86    pub fn native(
87        name: impl Into<String>,
88        description: impl Into<String>,
89        handler: CommandFn,
90    ) -> Self {
91        Self {
92            name: name.into(),
93            description: description.into(),
94            handler: Handler::Native(handler),
95        }
96    }
97
98    /// A Lisp-authored command whose behavior is a dotted action
99    /// symbol resolved at run time. Mirrors `(defcmd :name … :action
100    /// "buffer.write-all")`.
101    pub fn action(
102        name: impl Into<String>,
103        description: impl Into<String>,
104        action: impl Into<String>,
105    ) -> Self {
106        Self {
107            name: name.into(),
108            description: description.into(),
109            handler: Handler::Action(action.into()),
110        }
111    }
112}
113
114#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
115pub struct CommandSpec {
116    pub name: String,
117    pub description: String,
118    #[serde(default)]
119    pub args: Vec<CommandArgSpec>,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
123pub struct CommandArgSpec {
124    pub name: String,
125    pub description: String,
126    #[serde(default)]
127    pub required: bool,
128    #[serde(default, skip_serializing_if = "Vec::is_empty")]
129    pub variants: Vec<String>,
130}
131
132#[derive(Debug, Default, Clone)]
133pub struct CommandRegistry {
134    commands: HashMap<String, Command>,
135}
136
137impl CommandRegistry {
138    #[must_use]
139    pub fn new() -> Self {
140        Self::default()
141    }
142
143    #[must_use]
144    pub fn default_set() -> Self {
145        let mut r = Self::new();
146        r.register(Command::native(
147            "save",
148            "Write the active buffer to disk",
149            erase::<Save>(),
150        ));
151        r.register(Command::native("quit", "Exit the editor", erase::<Quit>()));
152        // Named for the ACTION SYMBOLS the shipped keybindings use, so
153        // `<leader>bn` resolves instead of reporting "declared but not
154        // implemented yet". These are the first three entries to leave the
155        // INERT inventory in escriba/tests/action_resolution.rs.
156        r.register(Command::native(
157            "buffer.next",
158            "Go to the next buffer",
159            erase::<BufferNext>(),
160        ));
161        r.register(Command::native(
162            "buffer.prev",
163            "Go to the previous buffer",
164            erase::<BufferPrev>(),
165        ));
166        r.register(Command::native(
167            "buffer.delete",
168            "Close the active buffer",
169            erase::<BufferDelete>(),
170        ));
171        r.register(Command::native(
172            "picker.buffers",
173            "Pick an open buffer",
174            erase::<OpenPicker<false>>(),
175        ));
176        r.register(Command::native(
177            "picker.commands",
178            "Pick a command",
179            erase::<OpenPicker<true>>(),
180        ));
181        r.register(Command::native(
182            "picker.help",
183            "Search every keybinding",
184            erase::<HelpPicker>(),
185        ));
186        r.register(Command::native(
187            "picker.grep",
188            "Search the project for a pattern",
189            erase::<GrepPicker>(),
190        ));
191        r.register(Command::native(
192            "picker.files",
193            "Pick a file under the working directory",
194            erase::<WalkPicker<false>>(),
195        ));
196        r.register(Command::native(
197            "picker.project",
198            "Pick a project root",
199            erase::<WalkPicker<true>>(),
200        ));
201        r.register(Command::native(
202            "todo.next",
203            "Go to the next TODO/FIXME marker",
204            erase::<TodoWalk<true>>(),
205        ));
206        r.register(Command::native(
207            "todo.prev",
208            "Go to the previous TODO/FIXME marker",
209            erase::<TodoWalk<false>>(),
210        ));
211        for name in ["comment.toggle-line", "comment.toggle-block"] {
212            r.register(Command::native(
213                name,
214                "Toggle the comment on the current line",
215                erase::<CommentToggle>(),
216            ));
217        }
218        for alias in ["noh", "nohl", "nohlsearch"] {
219            r.register(Command::action(
220                alias,
221                "Stop highlighting matches, keep the pattern",
222                "search.clear-highlight",
223            ));
224        }
225        r.register(Command::native(
226            "undo",
227            "Undo the last change",
228            erase::<Undo>(),
229        ));
230        r.register(Command::native(
231            "redo",
232            "Redo the last undone change",
233            erase::<Redo>(),
234        ));
235        r.register(Command::native(
236            "buffer-info",
237            "Print the active buffer summary",
238            erase::<Info>(),
239        ));
240        r
241    }
242
243    pub fn register(&mut self, command: Command) {
244        self.commands.insert(command.name.clone(), command);
245    }
246
247    /// Is `name` registered? Lets the apply layer report
248    /// override-vs-new without exposing the inner map.
249    #[must_use]
250    pub fn contains(&self, name: &str) -> bool {
251        self.commands.contains_key(name)
252    }
253
254    /// Number of registered commands.
255    #[must_use]
256    pub fn len(&self) -> usize {
257        self.commands.len()
258    }
259
260    /// True when no commands are registered.
261    #[must_use]
262    pub fn is_empty(&self) -> bool {
263        self.commands.is_empty()
264    }
265
266    /// Dispatch `name`.
267    ///
268    /// `Err` means the registry could not dispatch at all — Phase 0's two
269    /// failures, kept distinct because they mean different things to the
270    /// operator. `Ok(outcome)` means a body ran and reported for itself.
271    pub fn run(&self, name: &str, snap: &dyn Snapshot, args: &[String]) -> Result<Outcome> {
272        self.run_bounded(name, snap, args, ALIAS_FUEL)
273    }
274
275    /// One resolution path, bounded.
276    ///
277    /// An action symbol resolves against the BUILT-IN table first, then
278    /// against the registry itself. That second step is the whole point: a
279    /// `(defcmd :name "CommentToggle" :action "comment.toggle-line")` alias
280    /// used to die as `Unhandled` even though `comment.toggle-line` was a
281    /// registered native sitting in the same map — two dispatch tables that
282    /// had to agree, and did not. Every one of the 41 catalog aliases was
283    /// dead for exactly this reason.
284    ///
285    /// Resolving through the registry admits cycles, so the chain runs on
286    /// fuel and exhaustion is a typed `AliasCycle`.
287    fn run_bounded(
288        &self,
289        name: &str,
290        snap: &dyn Snapshot,
291        args: &[String],
292        fuel: u8,
293    ) -> Result<Outcome> {
294        let Some(fuel) = fuel.checked_sub(1) else {
295            return Err(CommandError::AliasCycle(name.to_string()));
296        };
297        let cmd = self
298            .commands
299            .get(name)
300            .ok_or_else(|| CommandError::NotFound(name.to_string()))?;
301        match &cmd.handler {
302            Handler::Native(f) => Ok(f(snap, args)),
303            Handler::Action(sym) => match builtin_action(sym) {
304                Some(f) => Ok(f(snap, args)),
305                // Not a built-in — but the symbol may name a registered
306                // command. `sym != name` keeps a self-referential alias from
307                // burning the whole budget before reporting.
308                None if sym != name && self.commands.contains_key(sym.as_str()) => {
309                    self.run_bounded(sym, snap, args, fuel)
310                }
311                None => Err(CommandError::Unhandled(sym.to_string())),
312            },
313        }
314    }
315
316    #[must_use]
317    pub fn names(&self) -> Vec<&str> {
318        let mut v: Vec<&str> = self.commands.keys().map(String::as_str).collect();
319        v.sort_unstable();
320        v
321    }
322
323    #[must_use]
324    pub fn specs(&self) -> Vec<CommandSpec> {
325        let mut out: Vec<CommandSpec> = self
326            .commands
327            .values()
328            .map(|c| CommandSpec {
329                name: c.name.to_string(),
330                description: c.description.to_string(),
331                args: Vec::new(),
332            })
333            .collect();
334        out.sort_by(|a, b| a.name.cmp(&b.name));
335        out
336    }
337}
338
339/// How many alias hops a chain may take before it is called a cycle.
340///
341/// Small on purpose: a legitimate chain is an alias naming a native, which
342/// is two hops. Anything deeper is a configuration mistake worth reporting.
343const ALIAS_FUEL: u8 = 8;
344
345/// The dotted action symbols escriba implements natively.
346///
347/// Returns `None` for anything else so the caller can try the registry —
348/// this used to return `Err(Unhandled)` directly, which is what made the
349/// built-in table the ONLY table and killed every catalog alias.
350fn builtin_action(sym: &str) -> Option<CommandFn> {
351    Some(match sym {
352        "buffer.save" | "buffer.write" => erase::<Save>(),
353        "buffer.write-all" => erase::<WriteAll>(),
354        "buffer.undo" => erase::<Undo>(),
355        "buffer.redo" => erase::<Redo>(),
356        "buffer.info" => erase::<Info>(),
357        "editor.quit" => erase::<Quit>(),
358        "search.clear-highlight" => erase::<Noh>(),
359        // The not-yet-implemented namespace. The shipped keybindings that
360        // land here are enumerated by `escriba/tests/action_resolution.rs`,
361        // which asserts SET EQUALITY — so the count is READ from there rather
362        // than restated. It said 85 while the real figure had ratcheted to
363        // 78; a duplicated number is a number that rots.
364        // Inert and ANNOUNCED; see CommandError::Unhandled.
365        _ => return None,
366    })
367}
368
369/// The active buffer, or the outcome to return when there isn't one.
370///
371/// "No buffer" is a DECLINE, not a failure: it is a legitimate state (boot,
372/// every `--no-defaults` run) and the operator did nothing wrong.
373fn active_or_decline(b: &escriba_madoguchi::snapshot::Buffers<'_>) -> Result2<BufferId> {
374    b.active()
375        .map(BufferView::id)
376        .ok_or_else(|| Outcome::declined("no active buffer"))
377}
378
379type Result2<T> = std::result::Result<T, Outcome>;
380
381/// Save every modified, path-backed buffer.
382///
383/// Best-effort BY CONSTRUCTION: one slip per buffer, applied independently,
384/// so one buffer's permission error cannot abort the rest. Scratch buffers
385/// have no path and are skipped.
386struct WriteAll;
387impl Native for WriteAll {
388    type Reads = caps!(Buffers);
389    fn run(v: &View<'_, Self::Reads>, _args: &[String]) -> Outcome {
390        let b = v.buffers();
391        let slips: Vec<Negai> = b
392            .ids()
393            .into_iter()
394            .filter(|id| {
395                b.get(*id)
396                    .is_some_and(|x| x.is_modified() && x.path().is_some())
397            })
398            .map(|buffer| Negai::Save { buffer })
399            .collect();
400        if slips.is_empty() {
401            return Outcome::declined("no modified files");
402        }
403        Outcome::did(slips)
404    }
405}
406
407struct Save;
408impl Native for Save {
409    type Reads = caps!(Buffers);
410    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
411        match active_or_decline(&v.buffers()) {
412            Ok(buffer) => Outcome::did(vec![Negai::Save { buffer }]),
413            Err(o) => o,
414        }
415    }
416}
417
418struct Undo;
419impl Native for Undo {
420    type Reads = caps!(Buffers);
421    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
422        match active_or_decline(&v.buffers()) {
423            Ok(buffer) => Outcome::did(vec![Negai::Undo { buffer }]),
424            Err(o) => o,
425        }
426    }
427}
428
429struct Redo;
430impl Native for Redo {
431    type Reads = caps!(Buffers);
432    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
433        match active_or_decline(&v.buffers()) {
434            Ok(buffer) => Outcome::did(vec![Negai::Redo { buffer }]),
435            Err(o) => o,
436        }
437    }
438}
439
440/// Report the active buffer's shape.
441///
442/// This used to `eprintln!`. From a TUI holding the alternate screen that
443/// writes straight through the ratatui frame and corrupts it — a latent bug
444/// the port removed for free, because a command's only way to say something
445/// is now `Negai::Message`, which lands on the status line.
446struct Info;
447impl Native for Info {
448    type Reads = caps!(Buffers);
449    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
450        let b = v.buffers();
451        let Some(buf) = b.active() else {
452            return Outcome::declined("no active buffer");
453        };
454        let mut m = String::with_capacity(48);
455        m.push_str("buffer ");
456        m.push_str(&buf.id().0.to_string());
457        m.push_str(" — ");
458        m.push_str(&buf.line_count().to_string());
459        m.push_str(" line(s)");
460        if buf.is_modified() {
461            m.push_str(" [modified]");
462        }
463        Outcome::did(vec![Negai::Message(m)])
464    }
465}
466
467/// Quit reads NOTHING.
468///
469/// Worth pausing on: under the old `EditContext` this function was handed
470/// `&mut BufferSet` and `&mut ModalState` in order to set one bool. Its
471/// capability set is now literally empty, and the type system enforces that
472/// — `caps!()` proves no membership, so every accessor on its view is
473/// unbuildable.
474/// `buffer.next` / `buffer.prev` — walk the buffer list.
475/// `picker.buffers` / `picker.commands` — open a picker over a source.
476///
477/// Reads `caps!()`: the handler does not build the item list. It cannot —
478/// a picker needs `&mut` across many keypresses and a handler holds a
479/// read-only `Snapshot`. So the slip NAMES the source and the interpreter
480/// populates it, which keeps the one-writer seam intact while the widget
481/// still gets the mutable state it needs.
482struct OpenPicker<const COMMANDS: bool>;
483impl<const COMMANDS: bool> Native for OpenPicker<COMMANDS> {
484    type Reads = caps!();
485    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
486        Outcome::did(vec![Negai::OpenPicker(if COMMANDS {
487            escriba_madoguchi::PickerSource::Commands
488        } else {
489            escriba_madoguchi::PickerSource::Buffers
490        })])
491    }
492}
493
494/// `picker.help` — the searchable keymap.
495struct HelpPicker;
496impl Native for HelpPicker {
497    type Reads = caps!();
498    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
499        Outcome::did(vec![Negai::OpenPicker(
500            escriba_madoguchi::PickerSource::Help,
501        )])
502    }
503}
504
505/// `picker.grep` — matches for a pattern across the project.
506///
507/// The pattern is the command's ARGUMENT (`:picker.grep fn main`). Declining
508/// with no argument rather than opening an empty picker: an overlay with
509/// nothing in it and no way to say why is worse than a message.
510struct GrepPicker;
511impl Native for GrepPicker {
512    type Reads = caps!();
513    fn run(_v: &View<'_, Self::Reads>, args: &[String]) -> Outcome {
514        let pattern = args.join(" ");
515        if pattern.is_empty() {
516            return Outcome::declined("grep: give a pattern — `:picker.grep <pattern>`");
517        }
518        Outcome::did(vec![Negai::GrepProject { pattern }])
519    }
520}
521
522/// `picker.files` / `picker.project` — the bounded-walk sources.
523struct WalkPicker<const PROJECT: bool>;
524impl<const PROJECT: bool> Native for WalkPicker<PROJECT> {
525    type Reads = caps!();
526    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
527        Outcome::did(vec![Negai::OpenPicker(if PROJECT {
528            escriba_madoguchi::PickerSource::Project
529        } else {
530            escriba_madoguchi::PickerSource::Files
531        })])
532    }
533}
534
535struct BufferNext;
536impl Native for BufferNext {
537    type Reads = caps!();
538    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
539        Outcome::did(vec![Negai::CycleBuffer { forward: true }])
540    }
541}
542
543struct BufferPrev;
544impl Native for BufferPrev {
545    type Reads = caps!();
546    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
547        Outcome::did(vec![Negai::CycleBuffer { forward: false }])
548    }
549}
550
551/// `buffer.delete` — close the active buffer.
552///
553/// Reads `Buffers` only to name WHICH buffer; whether a modified buffer may
554/// close, and what becomes active afterwards, are the interpreter's policy.
555struct BufferDelete;
556impl Native for BufferDelete {
557    type Reads = caps!(Buffers);
558    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
559        match active_or_decline(&v.buffers()) {
560            Ok(buffer) => Outcome::did(vec![Negai::CloseBuffer(buffer)]),
561            Err(o) => o,
562        }
563    }
564}
565
566/// `comment.toggle-line` / `comment.toggle-block` — the first commands to
567/// need TWO capabilities, and the first consumer of `:commentstring`.
568///
569/// Toggle, not comment: if the line is already commented it is uncommented.
570/// A one-way "comment" verb makes the same keystroke mean two things
571/// depending on state, which is how you end up with `//// x`.
572struct CommentToggle;
573impl Native for CommentToggle {
574    type Reads = caps!(Buffers, Cursor, Syntax);
575    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
576        let Some(ft) = v.syntax().filetype() else {
577            return Outcome::declined("no filetype for this buffer");
578        };
579        let Some(comment) = ft.comment.as_ref() else {
580            let mut m = String::from("no comment syntax for ");
581            m.push_str(&ft.name);
582            return Outcome::declined(m);
583        };
584        let b = v.buffers();
585        let Some(buf) = b.active() else {
586            return Outcome::declined("no active buffer");
587        };
588        let line_no = v.cursor().position().line;
589        let Some(line) = buf.line(line_no) else {
590            return Outcome::declined("cursor past the end of the buffer");
591        };
592        // An empty line has nothing to comment, and commenting it would
593        // leave a bare marker the next toggle cannot recognise as content.
594        if line.trim().is_empty() {
595            return Outcome::declined("nothing on this line");
596        }
597
598        // Indentation is preserved: a comment marker inserted before the
599        // indent would destroy the alignment the code is relying on.
600        let indent_len = line.len() - line.trim_start().len();
601        let (indent, body) = line.split_at(indent_len);
602        let toggled = match comment.strip(body) {
603            Some(uncommented) => uncommented.to_string(),
604            None => comment.wrap(body),
605        };
606        let mut text = String::with_capacity(indent.len() + toggled.len());
607        text.push_str(indent);
608        text.push_str(&toggled);
609
610        Outcome::did(vec![Negai::Edit {
611            buffer: buf.id(),
612            edit: escriba_core::Edit {
613                range: escriba_core::Range::new(
614                    escriba_core::Position::new(line_no, 0),
615                    escriba_core::Position::new(
616                        line_no,
617                        u32::try_from(line.chars().count()).unwrap_or(u32::MAX),
618                    ),
619                ),
620                kind: escriba_core::EditKind::Replace { text },
621            },
622        }])
623    }
624}
625
626/// `todo.next` / `todo.prev` — walk the marker list.
627///
628/// Scans on every invocation rather than relying on a cached list. The scan
629/// is pure text and costs nothing at keyboard cadence, and re-scanning means
630/// the list is always fresh — the freshness machinery then guards the window
631/// BETWEEN a publish and a walk, which is where a stale list would otherwise
632/// slip through.
633///
634/// This is also the shape every later producer takes: the command COMPUTES
635/// (it has the text through `Buffers`) and asks the interpreter to publish.
636/// Nothing here touches the registry.
637struct TodoWalk<const FORWARD: bool>;
638impl<const FORWARD: bool> Native for TodoWalk<FORWARD> {
639    type Reads = caps!(Buffers);
640    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
641        let b = v.buffers();
642        let Some(buf) = b.active() else {
643            return Outcome::declined("no active buffer");
644        };
645        let findings = escriba_shirube::scan_markers(buf.id(), &buf.text());
646        if findings.is_empty() {
647            return Outcome::declined("no TODO markers in this buffer");
648        }
649        Outcome::did(vec![
650            Negai::PublishFindings {
651                list: "todo".to_string(),
652                findings,
653            },
654            Negai::WalkList {
655                list: "todo".to_string(),
656                forward: FORWARD,
657            },
658        ])
659    }
660}
661
662struct Quit;
663impl Native for Quit {
664    type Reads = caps!();
665    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
666        Outcome::did(vec![Negai::Quit])
667    }
668}
669
670/// `:noh` — the command that proves the seam, and it also reads nothing.
671///
672/// It lived as a hard-coded branch inside `EditorState::run_command`,
673/// bypassing the registry entirely, because the old `EditContext` exposed
674/// buffers and modal state and could not reach `SearchState`. It is now an
675/// ordinary command asking for an ordinary slip, and it turns out not to
676/// need a view at all — it does not READ the search, it asks to change it.
677struct Noh;
678impl Native for Noh {
679    type Reads = caps!();
680    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
681        Outcome::did(vec![Negai::ClearSearchHighlight])
682    }
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688    use escriba_core::BufferId;
689    use escriba_madoguchi::{FakeBuffer, FakeSnapshot, Verdict};
690
691    /// A snapshot holding one dirty, path-backed buffer.
692    fn dirty_file() -> FakeSnapshot {
693        let mut s = FakeSnapshot::default();
694        s.buffers = vec![FakeBuffer::new(1, "dirty").at("/tmp/x.txt").dirty()];
695        s.active = Some(BufferId(1));
696        s
697    }
698
699    #[test]
700    fn default_set_is_populated() {
701        let r = CommandRegistry::default_set();
702        let names = r.names();
703        assert!(names.contains(&"save"));
704        assert!(names.contains(&"quit"));
705    }
706
707    #[test]
708    fn specs_are_sorted() {
709        let r = CommandRegistry::default_set();
710        let specs = r.specs();
711        assert!(specs.windows(2).all(|w| w[0].name <= w[1].name));
712    }
713
714    #[test]
715    fn not_found_errors() {
716        // Phase 0's first failure: a name nobody registered. Still an Err,
717        // because the runtime tells a typo apart from an unbuilt capability.
718        let r = CommandRegistry::new();
719        let err = r.run("nope", &FakeSnapshot::default(), &[]).unwrap_err();
720        assert!(matches!(err, CommandError::NotFound(_)));
721    }
722
723    #[test]
724    fn a_command_asks_rather_than_acts() {
725        // The whole point of the port. `write-all` used to reach into
726        // `&mut BufferSet` and call `.save()`. It now RETURNS a request per
727        // modified path-backed buffer and touches nothing — which is also
728        // why it is best-effort by construction: the interpreter applies
729        // each slip independently, so one permission error cannot abort the
730        // rest.
731        let mut r = CommandRegistry::new();
732        r.register(Command::action(
733            "w-all",
734            "Write every modified buffer",
735            "buffer.write-all",
736        ));
737        let out = r
738            .run("w-all", &dirty_file(), &[])
739            .expect("registered command dispatches");
740        assert_eq!(
741            out.slips,
742            vec![Negai::Save {
743                buffer: BufferId(1)
744            }]
745        );
746        assert_eq!(out.verdict, Verdict::Did);
747    }
748
749    #[test]
750    fn nothing_to_save_declines_rather_than_claiming_success() {
751        // Three verdicts, not two. A scratch buffer has no path, so there is
752        // genuinely nothing to write — and saying "Did" would be the same
753        // silent lie Phase 0 removed.
754        let mut r = CommandRegistry::new();
755        r.register(Command::action("w-all", "Write all", "buffer.write-all"));
756        let out = r
757            .run("w-all", &FakeSnapshot::with_buffer("scratch"), &[])
758            .expect("dispatches");
759        assert!(out.slips.is_empty());
760        assert_eq!(out.verdict, Verdict::Declined("no modified files".into()));
761    }
762
763    #[test]
764    fn no_active_buffer_declines_rather_than_failing() {
765        // Boot, and every `--no-defaults` run, reach commands with no
766        // buffer. The operator did nothing wrong, so it is not an error.
767        let mut r = CommandRegistry::new();
768        r.register(Command::action("w", "Save", "buffer.save"));
769        let out = r
770            .run("w", &FakeSnapshot::default(), &[])
771            .expect("dispatches");
772        assert_eq!(out.verdict, Verdict::Declined("no active buffer".into()));
773        assert!(out.slips.is_empty(), "a decline asks for nothing");
774    }
775
776    #[test]
777    fn unknown_action_symbol_is_reported_not_silent() {
778        // This test used to assert the DEFECT — it called `.expect()` on the
779        // Ok, pinning `_ => Ok(())`, under which a dead keybinding and a
780        // working one were indistinguishable at every layer.
781        //
782        // Inert is still correct: `picker.files` genuinely has not landed.
783        // SILENT was never correct. It must be `Unhandled`, not `NotFound`:
784        // the command IS registered, which is what made the silence
785        // misleading in the first place.
786        let mut r = CommandRegistry::new();
787        r.register(Command::action("pick", "Pick a file", "picker.files"));
788        let err = r
789            .run("pick", &FakeSnapshot::default(), &[])
790            .expect_err("an unimplemented action must report, not report success");
791        assert!(
792            matches!(&err, CommandError::Unhandled(s) if s == "picker.files"),
793            "expected Unhandled(picker.files), got {err:?}",
794        );
795        assert!(r.contains("pick"), "the command survives its own failure");
796    }
797
798    #[test]
799    fn action_naming_a_command_is_inert_not_recursive() {
800        // `:action` takes action SYMBOLS, not command names: `run_action`
801        // resolves dotted symbols and does NOT recurse into the registry.
802        // Recursion would let a handler reach anything by naming it, which
803        // is the ceiling madoguchi exists to remove.
804        //
805        // What changed with the port: the non-recursion is now REPORTED
806        // rather than looking like a successful save.
807        let mut r = CommandRegistry::new();
808        r.register(Command::action("alias", "aliases save by name", "save"));
809        let err = r
810            .run("alias", &dirty_file(), &[])
811            .expect_err("a command-name alias resolves nothing, and says so");
812        assert!(
813            matches!(&err, CommandError::Unhandled(s) if s == "save"),
814            "expected Unhandled(save), got {err:?}",
815        );
816    }
817
818    #[test]
819    fn quit_is_a_request_not_a_flag_poke() {
820        // Was `*ctx.quit_requested = true` — a command reaching into a
821        // borrowed flag. Quit is now a request like any other, and the
822        // interpreter decides, because the interpreter is the thing that
823        // knows about unsaved buffers.
824        let mut r = CommandRegistry::new();
825        r.register(Command::action("bye", "Quit", "editor.quit"));
826        let out = r
827            .run("bye", &FakeSnapshot::default(), &[])
828            .expect("dispatches");
829        assert_eq!(out.slips, vec![Negai::Quit]);
830    }
831
832    #[test]
833    fn buffer_info_speaks_through_a_slip_not_stderr() {
834        // It used to `eprintln!`, which from a TUI holding the alternate
835        // screen writes straight through the ratatui frame and corrupts it.
836        // A command's only way to say anything is now Negai::Message.
837        let mut r = CommandRegistry::new();
838        r.register(Command::action("info", "Buffer info", "buffer.info"));
839        let out = r.run("info", &dirty_file(), &[]).expect("dispatches");
840        let Some(Negai::Message(m)) = out.slips.first() else {
841            panic!("expected a Message slip, got {:?}", out.slips);
842        };
843        assert!(m.contains("buffer 1"), "{m}");
844        assert!(m.contains("[modified]"), "{m}");
845    }
846}