Skip to main content

escriba_command/
lib.rs

1//! `escriba-command` — command registry + palette.
2
3extern crate self as escriba_command;
4
5pub mod ex;
6
7use std::collections::HashMap;
8
9use escriba_core::BufferId;
10use escriba_madoguchi::cap::{Buffers, Cursor, Syntax};
11use escriba_madoguchi::{BufferView, Native, Negai, Outcome, Snapshot, View, caps, erase};
12use schemars::JsonSchema;
13use serde::{Deserialize, Serialize};
14use thiserror::Error;
15
16#[derive(Debug, Error)]
17pub enum CommandError {
18    #[error("command not found: {0}")]
19    NotFound(String),
20    /// A registered command whose action symbol nothing implements yet.
21    ///
22    /// Distinct from [`NotFound`](Self::NotFound), and the distinction is the
23    /// point: `NotFound` means the operator typed a name that does not exist,
24    /// while `Unhandled` means the editor ADVERTISED a binding — it is in
25    /// `--commands`, it is in the keymap, `--list-rc` counts it — and then did
26    /// nothing. The second is the more misleading of the two and used to be
27    /// the silent one.
28    #[error("action `{0}` is declared but not implemented yet")]
29    Unhandled(String),
30    #[error("command failed: {0}")]
31    Failed(String),
32    /// An alias chain that never reaches a body.
33    ///
34    /// Aliases resolve THROUGH the registry, so `A -> B -> A` would spin
35    /// forever. Bounded fuel turns that into a typed report naming the chain
36    /// the operator wrote, instead of a hung editor.
37    #[error("alias cycle resolving `{0}`")]
38    AliasCycle(String),
39    // NOTE: there was a `Buffer(#[from] BufferError)` variant here. The M2
40    // port made it dead: a command no longer performs I/O, so it cannot
41    // produce a buffer error. Save/undo/redo failures now surface from the
42    // interpreter, which is the thing that actually touches the filesystem.
43}
44
45pub type Result<T> = std::result::Result<T, CommandError>;
46
47/// A command body.
48///
49/// Reads through the counter, returns slips. There is no `&mut` in this
50/// signature, which is the point: a command cannot reach editor state, so it
51/// cannot corrupt it. It replaces `fn(&mut EditContext, &[String])`, whose
52/// `&mut BufferSet` was simultaneously too much power and too little reach —
53/// the runtime still had to special-case `:noh` because `EditContext` could
54/// not see `SearchState`.
55pub type CommandFn = fn(&dyn Snapshot, &[String]) -> Outcome;
56
57/// How a command executes when invoked.
58///
59/// - [`Handler::Native`] wraps a compiled-in Rust `fn` — the
60///   built-in command set (`save`, `quit`, …).
61/// - [`Handler::Action`] carries a dotted action symbol
62///   (e.g. `"buffer.write-all"`, `"picker.files"`) authored via a
63///   Tatara-Lisp `(defcmd …)` form and resolved at run time by
64///   [`run_action`]. This is what lets `defcmd` register a real,
65///   invokable command without a compiled handler.
66///
67/// A future `Lisp(Thunk)` variant will carry a `tatara-lisp-eval`
68/// closure for fully-programmable commands — the imperative tier of
69/// the two-tier programmability model. Keeping the handler an enum
70/// (not a bare `fn`) is what makes that extension a one-variant add.
71#[derive(Debug, Clone)]
72pub enum Handler {
73    /// Compiled-in Rust handler.
74    Native(CommandFn),
75    /// Dotted action symbol resolved at run time (Lisp `defcmd`).
76    Action(String),
77}
78
79#[derive(Debug, Clone)]
80pub struct Command {
81    pub name: String,
82    pub description: String,
83    pub handler: Handler,
84}
85
86impl Command {
87    /// A built-in command backed by a compiled-in Rust `fn`.
88    pub fn native(
89        name: impl Into<String>,
90        description: impl Into<String>,
91        handler: CommandFn,
92    ) -> Self {
93        Self {
94            name: name.into(),
95            description: description.into(),
96            handler: Handler::Native(handler),
97        }
98    }
99
100    /// A Lisp-authored command whose behavior is a dotted action
101    /// symbol resolved at run time. Mirrors `(defcmd :name … :action
102    /// "buffer.write-all")`.
103    pub fn action(
104        name: impl Into<String>,
105        description: impl Into<String>,
106        action: impl Into<String>,
107    ) -> Self {
108        Self {
109            name: name.into(),
110            description: description.into(),
111            handler: Handler::Action(action.into()),
112        }
113    }
114}
115
116#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
117pub struct CommandSpec {
118    pub name: String,
119    pub description: String,
120    #[serde(default)]
121    pub args: Vec<CommandArgSpec>,
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
125pub struct CommandArgSpec {
126    pub name: String,
127    pub description: String,
128    #[serde(default)]
129    pub required: bool,
130    #[serde(default, skip_serializing_if = "Vec::is_empty")]
131    pub variants: Vec<String>,
132}
133
134#[derive(Debug, Default, Clone)]
135pub struct CommandRegistry {
136    commands: HashMap<String, Command>,
137}
138
139impl CommandRegistry {
140    #[must_use]
141    pub fn new() -> Self {
142        Self::default()
143    }
144
145    #[must_use]
146    pub fn default_set() -> Self {
147        let mut r = Self::new();
148        r.register(Command::native(
149            "save",
150            "Write the active buffer to disk",
151            erase::<Save>(),
152        ));
153        // ── the write/quit family ────────────────────────────────────────
154        //
155        // One registered command per DISTINCT BEHAVIOUR; the many spellings
156        // an operator can type (`:x`, `:wqa`, `:quita`, …) are the ex
157        // grammar's business, not the registry's. See [`ex::VERBS`].
158        r.register(Command::native(
159            "quit",
160            "Exit the editor, unless a buffer is modified",
161            erase::<QuitChecked<false>>(),
162        ));
163        r.register(Command::native(
164            "quit!",
165            "Exit the editor, discarding unsaved changes",
166            erase::<Quit>(),
167        ));
168        r.register(Command::native(
169            "quit-all",
170            "Exit the editor, unless any buffer is modified",
171            erase::<QuitChecked<true>>(),
172        ));
173        r.register(Command::native(
174            "quit-all!",
175            "Exit the editor, discarding every unsaved change",
176            erase::<Quit>(),
177        ));
178        r.register(Command::native(
179            "write-quit",
180            "Write the active buffer, then exit",
181            erase::<WriteQuit>(),
182        ));
183        r.register(Command::native(
184            "write-quit-all",
185            "Write every modified buffer, then exit",
186            erase::<WriteQuitAll>(),
187        ));
188        r.register(Command::native(
189            "exit-write",
190            "Write the active buffer if modified, then exit",
191            erase::<ExitWrite>(),
192        ));
193        r.register(Command::native(
194            "buffer.write-all",
195            "Write every modified buffer",
196            erase::<WriteAll>(),
197        ));
198        // Named for the ACTION SYMBOLS the shipped keybindings use, so
199        // `<leader>bn` resolves instead of reporting "declared but not
200        // implemented yet". These are the first three entries to leave the
201        // INERT inventory in escriba/tests/action_resolution.rs.
202        r.register(Command::native(
203            "buffer.next",
204            "Go to the next buffer",
205            erase::<BufferNext>(),
206        ));
207        r.register(Command::native(
208            "buffer.prev",
209            "Go to the previous buffer",
210            erase::<BufferPrev>(),
211        ));
212        r.register(Command::native(
213            "buffer.delete",
214            "Close the active buffer",
215            erase::<BufferDelete>(),
216        ));
217        r.register(Command::native(
218            "picker.buffers",
219            "Pick an open buffer",
220            erase::<OpenPicker<false>>(),
221        ));
222        r.register(Command::native(
223            "picker.commands",
224            "Pick a command",
225            erase::<OpenPicker<true>>(),
226        ));
227        r.register(Command::native(
228            "picker.help",
229            "Search every keybinding",
230            erase::<HelpPicker>(),
231        ));
232        r.register(Command::native(
233            "picker.grep",
234            "Search the project for a pattern",
235            erase::<GrepPicker>(),
236        ));
237        r.register(Command::native(
238            "lsp.format",
239            "Format the buffer through its language server",
240            erase::<LspFormat>(),
241        ));
242        r.register(Command::native(
243            "picker.files",
244            "Pick a file under the working directory",
245            erase::<WalkPicker<false>>(),
246        ));
247        r.register(Command::native(
248            "picker.project",
249            "Pick a project root",
250            erase::<WalkPicker<true>>(),
251        ));
252        // ── the oil.nvim verbs ───────────────────────────────────────────
253        // `files.open` IS the file picker — same capability, the name the
254        // catalog binds. Registering it as its own native rather than an
255        // alias keeps `--commands` honest about what each name does.
256        r.register(Command::native(
257            "files.open",
258            "Browse files under the working directory",
259            erase::<WalkPicker<false>>(),
260        ));
261        r.register(Command::native(
262            "files.open-parent",
263            "Browse files from the parent directory",
264            erase::<ParentPicker>(),
265        ));
266        // ── the trouble.nvim verbs ───────────────────────────────────────
267        r.register(Command::native(
268            "trouble.toggle",
269            "Show located findings",
270            erase::<FindingsPicker<true>>(),
271        ));
272        r.register(Command::native(
273            "trouble.workspace",
274            "Show findings across the workspace",
275            erase::<FindingsPicker<true>>(),
276        ));
277        r.register(Command::native(
278            "trouble.document",
279            "Show findings in this buffer",
280            erase::<FindingsPicker<false>>(),
281        ));
282        r.register(Command::native(
283            "window.split",
284            "Split the window horizontally (:sp)",
285            erase::<SplitWindow<true>>(),
286        ));
287        r.register(Command::native(
288            "window.vsplit",
289            "Split the window vertically (:vsp)",
290            erase::<SplitWindow<false>>(),
291        ));
292        r.register(Command::native(
293            "window.close",
294            "Close the active window (:close)",
295            erase::<CloseWindow>(),
296        ));
297        r.register(Command::native(
298            "pane.left",
299            "Focus the window to the left",
300            erase::<FocusDir<-1, 0>>(),
301        ));
302        r.register(Command::native(
303            "pane.right",
304            "Focus the window to the right",
305            erase::<FocusDir<1, 0>>(),
306        ));
307        r.register(Command::native(
308            "pane.up",
309            "Focus the window above",
310            erase::<FocusDir<0, -1>>(),
311        ));
312        r.register(Command::native(
313            "pane.down",
314            "Focus the window below",
315            erase::<FocusDir<0, 1>>(),
316        ));
317        r.register(Command::native(
318            "conflict.next",
319            "Go to the next merge conflict",
320            erase::<ConflictWalk<true>>(),
321        ));
322        r.register(Command::native(
323            "conflict.prev",
324            "Go to the previous merge conflict",
325            erase::<ConflictWalk<false>>(),
326        ));
327        r.register(Command::native(
328            "conflict.choose-ours",
329            "Resolve the conflict keeping ours",
330            erase::<ChooseSide<0>>(),
331        ));
332        r.register(Command::native(
333            "conflict.choose-theirs",
334            "Resolve the conflict keeping theirs",
335            erase::<ChooseSide<1>>(),
336        ));
337        r.register(Command::native(
338            "conflict.choose-both",
339            "Resolve the conflict keeping both",
340            erase::<ChooseSide<2>>(),
341        ));
342        r.register(Command::native(
343            "todo.next",
344            "Go to the next TODO/FIXME marker",
345            erase::<TodoWalk<true>>(),
346        ));
347        r.register(Command::native(
348            "todo.prev",
349            "Go to the previous TODO/FIXME marker",
350            erase::<TodoWalk<false>>(),
351        ));
352        for name in ["comment.toggle-line", "comment.toggle-block"] {
353            r.register(Command::native(
354                name,
355                "Toggle the comment on the current line",
356                erase::<CommentToggle>(),
357            ));
358        }
359        for alias in ["noh", "nohl", "nohlsearch"] {
360            r.register(Command::action(
361                alias,
362                "Stop highlighting matches, keep the pattern",
363                "search.clear-highlight",
364            ));
365        }
366        r.register(Command::native(
367            "undo",
368            "Undo the last change",
369            erase::<Undo>(),
370        ));
371        r.register(Command::native(
372            "redo",
373            "Redo the last undone change",
374            erase::<Redo>(),
375        ));
376        r.register(Command::native(
377            "buffer-info",
378            "Print the active buffer summary",
379            erase::<Info>(),
380        ));
381        r
382    }
383
384    pub fn register(&mut self, command: Command) {
385        self.commands.insert(command.name.clone(), command);
386    }
387
388    /// Is `name` registered? Lets the apply layer report
389    /// override-vs-new without exposing the inner map.
390    #[must_use]
391    pub fn contains(&self, name: &str) -> bool {
392        self.commands.contains_key(name)
393    }
394
395    /// Number of registered commands.
396    #[must_use]
397    pub fn len(&self) -> usize {
398        self.commands.len()
399    }
400
401    /// True when no commands are registered.
402    #[must_use]
403    pub fn is_empty(&self) -> bool {
404        self.commands.is_empty()
405    }
406
407    /// Dispatch `name`.
408    ///
409    /// `Err` means the registry could not dispatch at all — Phase 0's two
410    /// failures, kept distinct because they mean different things to the
411    /// operator. `Ok(outcome)` means a body ran and reported for itself.
412    pub fn run(&self, name: &str, snap: &dyn Snapshot, args: &[String]) -> Result<Outcome> {
413        self.run_bounded(name, snap, args, ALIAS_FUEL)
414    }
415
416    /// One resolution path, bounded.
417    ///
418    /// An action symbol resolves against the BUILT-IN table first, then
419    /// against the registry itself. That second step is the whole point: a
420    /// `(defcmd :name "CommentToggle" :action "comment.toggle-line")` alias
421    /// used to die as `Unhandled` even though `comment.toggle-line` was a
422    /// registered native sitting in the same map — two dispatch tables that
423    /// had to agree, and did not. Every one of the 41 catalog aliases was
424    /// dead for exactly this reason.
425    ///
426    /// Resolving through the registry admits cycles, so the chain runs on
427    /// fuel and exhaustion is a typed `AliasCycle`.
428    fn run_bounded(
429        &self,
430        name: &str,
431        snap: &dyn Snapshot,
432        args: &[String],
433        fuel: u8,
434    ) -> Result<Outcome> {
435        let Some(fuel) = fuel.checked_sub(1) else {
436            return Err(CommandError::AliasCycle(name.to_string()));
437        };
438        let cmd = self
439            .commands
440            .get(name)
441            .ok_or_else(|| CommandError::NotFound(name.to_string()))?;
442        match &cmd.handler {
443            Handler::Native(f) => Ok(f(snap, args)),
444            Handler::Action(sym) => match builtin_action(sym) {
445                Some(f) => Ok(f(snap, args)),
446                // Not a built-in — but the symbol may name a registered
447                // command. `sym != name` keeps a self-referential alias from
448                // burning the whole budget before reporting.
449                None if sym != name && self.commands.contains_key(sym.as_str()) => {
450                    self.run_bounded(sym, snap, args, fuel)
451                }
452                None => Err(CommandError::Unhandled(sym.to_string())),
453            },
454        }
455    }
456
457    #[must_use]
458    pub fn names(&self) -> Vec<&str> {
459        let mut v: Vec<&str> = self.commands.keys().map(String::as_str).collect();
460        v.sort_unstable();
461        v
462    }
463
464    #[must_use]
465    pub fn specs(&self) -> Vec<CommandSpec> {
466        let mut out: Vec<CommandSpec> = self
467            .commands
468            .values()
469            .map(|c| CommandSpec {
470                name: c.name.to_string(),
471                description: c.description.to_string(),
472                args: Vec::new(),
473            })
474            .collect();
475        out.sort_by(|a, b| a.name.cmp(&b.name));
476        out
477    }
478}
479
480/// How many alias hops a chain may take before it is called a cycle.
481///
482/// Small on purpose: a legitimate chain is an alias naming a native, which
483/// is two hops. Anything deeper is a configuration mistake worth reporting.
484const ALIAS_FUEL: u8 = 8;
485
486/// The dotted action symbols escriba implements natively.
487///
488/// Returns `None` for anything else so the caller can try the registry —
489/// this used to return `Err(Unhandled)` directly, which is what made the
490/// built-in table the ONLY table and killed every catalog alias.
491fn builtin_action(sym: &str) -> Option<CommandFn> {
492    Some(match sym {
493        "buffer.save" | "buffer.write" => erase::<Save>(),
494        "buffer.write-all" => erase::<WriteAll>(),
495        "buffer.undo" => erase::<Undo>(),
496        "buffer.redo" => erase::<Redo>(),
497        "buffer.info" => erase::<Info>(),
498        "editor.quit" => erase::<Quit>(),
499        "search.clear-highlight" => erase::<Noh>(),
500        // The not-yet-implemented namespace. The shipped keybindings that
501        // land here are enumerated by `escriba/tests/action_resolution.rs`,
502        // which asserts SET EQUALITY — so the count is READ from there rather
503        // than restated. It said 85 while the real figure had ratcheted to
504        // 78; a duplicated number is a number that rots.
505        // Inert and ANNOUNCED; see CommandError::Unhandled.
506        _ => return None,
507    })
508}
509
510/// The active buffer, or the outcome to return when there isn't one.
511///
512/// "No buffer" is a DECLINE, not a failure: it is a legitimate state (boot,
513/// every `--no-defaults` run) and the operator did nothing wrong.
514fn active_or_decline(b: &escriba_madoguchi::snapshot::Buffers<'_>) -> Result2<BufferId> {
515    b.active()
516        .map(BufferView::id)
517        .ok_or_else(|| Outcome::declined("no active buffer"))
518}
519
520type Result2<T> = std::result::Result<T, Outcome>;
521
522/// Save every modified, path-backed buffer.
523///
524/// Best-effort BY CONSTRUCTION: one slip per buffer, applied independently,
525/// so one buffer's permission error cannot abort the rest. Scratch buffers
526/// have no path and are skipped.
527struct WriteAll;
528impl Native for WriteAll {
529    type Reads = caps!(Buffers);
530    fn run(v: &View<'_, Self::Reads>, _args: &[String]) -> Outcome {
531        let b = v.buffers();
532        let slips: Vec<Negai> = b
533            .ids()
534            .into_iter()
535            .filter(|id| {
536                b.get(*id)
537                    .is_some_and(|x| x.is_modified() && x.path().is_some())
538            })
539            .map(|buffer| Negai::Save { buffer })
540            .collect();
541        if slips.is_empty() {
542            return Outcome::declined("no modified files");
543        }
544        Outcome::did(slips)
545    }
546}
547
548struct Save;
549impl Native for Save {
550    type Reads = caps!(Buffers);
551    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
552        match active_or_decline(&v.buffers()) {
553            Ok(buffer) => Outcome::did(vec![Negai::Save { buffer }]),
554            Err(o) => o,
555        }
556    }
557}
558
559struct Undo;
560impl Native for Undo {
561    type Reads = caps!(Buffers);
562    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
563        match active_or_decline(&v.buffers()) {
564            Ok(buffer) => Outcome::did(vec![Negai::Undo { buffer }]),
565            Err(o) => o,
566        }
567    }
568}
569
570struct Redo;
571impl Native for Redo {
572    type Reads = caps!(Buffers);
573    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
574        match active_or_decline(&v.buffers()) {
575            Ok(buffer) => Outcome::did(vec![Negai::Redo { buffer }]),
576            Err(o) => o,
577        }
578    }
579}
580
581/// Report the active buffer's shape.
582///
583/// This used to `eprintln!`. From a TUI holding the alternate screen that
584/// writes straight through the ratatui frame and corrupts it — a latent bug
585/// the port removed for free, because a command's only way to say something
586/// is now `Negai::Message`, which lands on the status line.
587struct Info;
588impl Native for Info {
589    type Reads = caps!(Buffers);
590    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
591        let b = v.buffers();
592        let Some(buf) = b.active() else {
593            return Outcome::declined("no active buffer");
594        };
595        let mut m = String::with_capacity(48);
596        m.push_str("buffer ");
597        m.push_str(&buf.id().0.to_string());
598        m.push_str(" — ");
599        m.push_str(&buf.line_count().to_string());
600        m.push_str(" line(s)");
601        if buf.is_modified() {
602            m.push_str(" [modified]");
603        }
604        Outcome::did(vec![Negai::Message(m)])
605    }
606}
607
608/// Quit reads NOTHING.
609///
610/// Worth pausing on: under the old `EditContext` this function was handed
611/// `&mut BufferSet` and `&mut ModalState` in order to set one bool. Its
612/// capability set is now literally empty, and the type system enforces that
613/// — `caps!()` proves no membership, so every accessor on its view is
614/// unbuildable.
615/// `buffer.next` / `buffer.prev` — walk the buffer list.
616/// `picker.buffers` / `picker.commands` — open a picker over a source.
617///
618/// Reads `caps!()`: the handler does not build the item list. It cannot —
619/// a picker needs `&mut` across many keypresses and a handler holds a
620/// read-only `Snapshot`. So the slip NAMES the source and the interpreter
621/// populates it, which keeps the one-writer seam intact while the widget
622/// still gets the mutable state it needs.
623struct OpenPicker<const COMMANDS: bool>;
624impl<const COMMANDS: bool> Native for OpenPicker<COMMANDS> {
625    type Reads = caps!();
626    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
627        Outcome::did(vec![Negai::OpenPicker(if COMMANDS {
628            escriba_madoguchi::PickerSource::Commands
629        } else {
630            escriba_madoguchi::PickerSource::Buffers
631        })])
632    }
633}
634
635/// `picker.help` — the searchable keymap.
636struct HelpPicker;
637impl Native for HelpPicker {
638    type Reads = caps!();
639    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
640        Outcome::did(vec![Negai::OpenPicker(
641            escriba_madoguchi::PickerSource::Help,
642        )])
643    }
644}
645
646/// `picker.grep` — matches for a pattern across the project.
647///
648/// The pattern is the command's ARGUMENT (`:picker.grep fn main`). Declining
649/// with no argument rather than opening an empty picker: an overlay with
650/// nothing in it and no way to say why is worse than a message.
651struct GrepPicker;
652impl Native for GrepPicker {
653    type Reads = caps!();
654    fn run(_v: &View<'_, Self::Reads>, args: &[String]) -> Outcome {
655        let pattern = args.join(" ");
656        if pattern.is_empty() {
657            return Outcome::declined("grep: give a pattern — `:picker.grep <pattern>`");
658        }
659        Outcome::did(vec![Negai::GrepProject { pattern }])
660    }
661}
662
663/// `lsp.format` — format the active buffer through its language server.
664///
665/// The name the catalog already binds. `escriba-conform.escribaplugin.lisp`
666/// has declared `(defcmd :name "Format" :action "lsp.format")`, a
667/// `<leader>lf` keybind and a `BufWritePre` hook against this name since it
668/// was written; all three resolved to nothing, and `tests/action_resolution.rs`
669/// listed `lsp.format` in its INERT set to say so out loud. This is the
670/// implementation those declarations were waiting for.
671struct LspFormat;
672impl Native for LspFormat {
673    type Reads = caps!();
674    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
675        Outcome::did(vec![Negai::FormatBuffer])
676    }
677}
678
679/// `picker.files` / `picker.project` — the bounded-walk sources.
680struct WalkPicker<const PROJECT: bool>;
681impl<const PROJECT: bool> Native for WalkPicker<PROJECT> {
682    type Reads = caps!();
683    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
684        Outcome::did(vec![Negai::OpenPicker(if PROJECT {
685            escriba_madoguchi::PickerSource::Project
686        } else {
687            escriba_madoguchi::PickerSource::Files
688        })])
689    }
690}
691
692/// `files.open-parent` — the same bounded walk, rooted one level up.
693///
694/// oil.nvim's `-`: browse from where the current file lives, then upward.
695/// The root is resolved from the working directory rather than the buffer
696/// because a scratch buffer has no directory, and "browse from nowhere" has
697/// no sensible answer — falling back to `.` is the honest one.
698struct ParentPicker;
699impl Native for ParentPicker {
700    type Reads = caps!();
701    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
702        let root = std::env::current_dir()
703            .ok()
704            .and_then(|d| d.parent().map(std::path::Path::to_path_buf))
705            .unwrap_or_else(|| std::path::PathBuf::from(".."));
706        Outcome::did(vec![Negai::OpenPicker(
707            escriba_madoguchi::PickerSource::FilesUnder(root),
708        )])
709    }
710}
711
712/// `trouble.*` — a view over the result registry.
713///
714/// `WORKSPACE` is the whole difference between `trouble.document` and
715/// `trouble.workspace`; `trouble.toggle` is the workspace view because that
716/// is what an operator means by "show me the problems".
717struct FindingsPicker<const WORKSPACE: bool>;
718impl<const WORKSPACE: bool> Native for FindingsPicker<WORKSPACE> {
719    type Reads = caps!();
720    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
721        Outcome::did(vec![Negai::OpenPicker(
722            escriba_madoguchi::PickerSource::Findings {
723                workspace: WORKSPACE,
724            },
725        )])
726    }
727}
728
729/// `:sp` / `:vsp` — split the active window.
730///
731/// Reads `caps!()`: splitting is layout, not buffer content. The handler
732/// names the axis and the interpreter does it, which is the same shape the
733/// picker uses and for the same reason — a handler holds a read-only
734/// `Snapshot`.
735struct SplitWindow<const STACKED: bool>;
736impl<const STACKED: bool> Native for SplitWindow<STACKED> {
737    type Reads = caps!();
738    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
739        Outcome::did(vec![Negai::SplitWindow { stacked: STACKED }])
740    }
741}
742
743/// `:close` / `<C-w>c`.
744struct CloseWindow;
745impl Native for CloseWindow {
746    type Reads = caps!();
747    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
748        Outcome::did(vec![Negai::CloseWindow])
749    }
750}
751
752/// `pane.{left,right,up,down}` — `<C-w>hjkl`.
753///
754/// The direction is two const params rather than an enum so one impl covers
755/// all four without a runtime match, and so a wrong direction is a wrong
756/// TYPE at the registration site rather than a wrong argument.
757struct FocusDir<const DX: i8, const DY: i8>;
758impl<const DX: i8, const DY: i8> Native for FocusDir<DX, DY> {
759    type Reads = caps!();
760    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
761        Outcome::did(vec![Negai::FocusDir { dx: DX, dy: DY }])
762    }
763}
764
765/// `]x` / `[x` — walk merge conflicts.
766///
767/// Identical in shape to `TodoWalk`, and that is the claim being tested: a
768/// conflict is a located finding, so navigating one is the SAME walk. If
769/// this needed anything TodoWalk did not, the shirube model would be wrong.
770struct ConflictWalk<const FORWARD: bool>;
771impl<const FORWARD: bool> Native for ConflictWalk<FORWARD> {
772    type Reads = caps!(Buffers);
773    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
774        let b = v.buffers();
775        let Some(buf) = b.active() else {
776            return Outcome::declined("no active buffer");
777        };
778        let findings = escriba_shirube::conflict::findings(buf.id(), &buf.text());
779        if findings.is_empty() {
780            return Outcome::declined("no merge conflicts in this buffer");
781        }
782        Outcome::did(vec![
783            Negai::PublishFindings {
784                list: "conflict".to_string(),
785                findings,
786            },
787            Negai::WalkList {
788                list: "conflict".to_string(),
789                forward: FORWARD,
790            },
791        ])
792    }
793}
794
795/// `conflict.choose-{ours,theirs,both}` — resolve the conflict at the cursor.
796///
797/// Reads `caps!(Buffers, Cursor)`: it needs the text to find the region and
798/// the cursor to know WHICH region. The edit it emits replaces whole lines,
799/// because there is no such thing as keeping half of "ours".
800struct ChooseSide<const SIDE: u8>;
801impl<const SIDE: u8> Native for ChooseSide<SIDE> {
802    type Reads = caps!(Buffers, Cursor);
803    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
804        use escriba_shirube::conflict::{Side, at, resolution};
805        let b = v.buffers();
806        let Some(buf) = b.active() else {
807            return Outcome::declined("no active buffer");
808        };
809        let text = buf.text();
810        let line = v.cursor().position().line;
811        let Some(c) = at(&text, line) else {
812            // Declined, not failed: standing outside a conflict is an
813            // ordinary place to be, and vim says nothing there either.
814            return Outcome::declined("not inside a merge conflict");
815        };
816        let side = match SIDE {
817            0 => Side::Ours,
818            1 => Side::Theirs,
819            _ => Side::Both,
820        };
821        let (from, to) = c.lines();
822        Outcome::did(vec![
823            Negai::Edit {
824                buffer: buf.id(),
825                edit: escriba_core::Edit {
826                    range: escriba_core::Range::new(
827                        escriba_core::Position::new(from, 0),
828                        escriba_core::Position::new(to, 0),
829                    ),
830                    kind: escriba_core::EditKind::Replace {
831                        text: resolution(&text, c, side),
832                    },
833                },
834            },
835            // Land on the resolved text rather than wherever the deleted
836            // markers left the cursor.
837            Negai::SetCursor {
838                buffer: buf.id(),
839                to: escriba_core::Position::new(from, 0),
840            },
841        ])
842    }
843}
844
845struct BufferNext;
846impl Native for BufferNext {
847    type Reads = caps!();
848    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
849        Outcome::did(vec![Negai::CycleBuffer { forward: true }])
850    }
851}
852
853struct BufferPrev;
854impl Native for BufferPrev {
855    type Reads = caps!();
856    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
857        Outcome::did(vec![Negai::CycleBuffer { forward: false }])
858    }
859}
860
861/// `buffer.delete` — close the active buffer.
862///
863/// Reads `Buffers` only to name WHICH buffer; whether a modified buffer may
864/// close, and what becomes active afterwards, are the interpreter's policy.
865struct BufferDelete;
866impl Native for BufferDelete {
867    type Reads = caps!(Buffers);
868    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
869        match active_or_decline(&v.buffers()) {
870            Ok(buffer) => Outcome::did(vec![Negai::CloseBuffer(buffer)]),
871            Err(o) => o,
872        }
873    }
874}
875
876/// `comment.toggle-line` / `comment.toggle-block` — the first commands to
877/// need TWO capabilities, and the first consumer of `:commentstring`.
878///
879/// Toggle, not comment: if the line is already commented it is uncommented.
880/// A one-way "comment" verb makes the same keystroke mean two things
881/// depending on state, which is how you end up with `//// x`.
882struct CommentToggle;
883impl Native for CommentToggle {
884    type Reads = caps!(Buffers, Cursor, Syntax);
885    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
886        let Some(ft) = v.syntax().filetype() else {
887            return Outcome::declined("no filetype for this buffer");
888        };
889        let Some(comment) = ft.comment.as_ref() else {
890            let mut m = String::from("no comment syntax for ");
891            m.push_str(&ft.name);
892            return Outcome::declined(m);
893        };
894        let b = v.buffers();
895        let Some(buf) = b.active() else {
896            return Outcome::declined("no active buffer");
897        };
898        let line_no = v.cursor().position().line;
899        let Some(line) = buf.line(line_no) else {
900            return Outcome::declined("cursor past the end of the buffer");
901        };
902        // An empty line has nothing to comment, and commenting it would
903        // leave a bare marker the next toggle cannot recognise as content.
904        if line.trim().is_empty() {
905            return Outcome::declined("nothing on this line");
906        }
907
908        // Indentation is preserved: a comment marker inserted before the
909        // indent would destroy the alignment the code is relying on.
910        let indent_len = line.len() - line.trim_start().len();
911        let (indent, body) = line.split_at(indent_len);
912        let toggled = match comment.strip(body) {
913            Some(uncommented) => uncommented.to_string(),
914            None => comment.wrap(body),
915        };
916        let mut text = String::with_capacity(indent.len() + toggled.len());
917        text.push_str(indent);
918        text.push_str(&toggled);
919
920        Outcome::did(vec![Negai::Edit {
921            buffer: buf.id(),
922            edit: escriba_core::Edit {
923                range: escriba_core::Range::new(
924                    escriba_core::Position::new(line_no, 0),
925                    escriba_core::Position::new(
926                        line_no,
927                        u32::try_from(line.chars().count()).unwrap_or(u32::MAX),
928                    ),
929                ),
930                kind: escriba_core::EditKind::Replace { text },
931            },
932        }])
933    }
934}
935
936/// `todo.next` / `todo.prev` — walk the marker list.
937///
938/// Scans on every invocation rather than relying on a cached list. The scan
939/// is pure text and costs nothing at keyboard cadence, and re-scanning means
940/// the list is always fresh — the freshness machinery then guards the window
941/// BETWEEN a publish and a walk, which is where a stale list would otherwise
942/// slip through.
943///
944/// This is also the shape every later producer takes: the command COMPUTES
945/// (it has the text through `Buffers`) and asks the interpreter to publish.
946/// Nothing here touches the registry.
947struct TodoWalk<const FORWARD: bool>;
948impl<const FORWARD: bool> Native for TodoWalk<FORWARD> {
949    type Reads = caps!(Buffers);
950    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
951        let b = v.buffers();
952        let Some(buf) = b.active() else {
953            return Outcome::declined("no active buffer");
954        };
955        let findings = escriba_shirube::scan_markers(buf.id(), &buf.text());
956        if findings.is_empty() {
957            return Outcome::declined("no TODO markers in this buffer");
958        }
959        Outcome::did(vec![
960            Negai::PublishFindings {
961                list: "todo".to_string(),
962                findings,
963            },
964            Negai::WalkList {
965                list: "todo".to_string(),
966                forward: FORWARD,
967            },
968        ])
969    }
970}
971
972/// `:q!` / `:qa!` — leave, whatever the buffers say.
973///
974/// Reads nothing, on purpose. The force form's whole meaning is "do not
975/// consult the thing that would stop you", and a handler that cannot see the
976/// modified flag cannot be talked into honouring it.
977struct Quit;
978impl Native for Quit {
979    type Reads = caps!();
980    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
981        Outcome::did(vec![Negai::Quit])
982    }
983}
984
985/// vim's E37, worded as vim words it — the `(add ! to override)` tail is the
986/// half that matters, because it names the key that gets the operator out.
987fn no_write_since_last_change(what: &str) -> Outcome {
988    let mut m = String::with_capacity(64);
989    m.push_str("E37: No write since last change in ");
990    m.push_str(what);
991    m.push_str(" (add ! to override)");
992    Outcome::declined(m)
993}
994
995/// How a buffer is named in a message: its path, or `[No Name]` as vim calls
996/// an unsaved scratch.
997fn buffer_label(b: &dyn BufferView) -> String {
998    b.path()
999        .map_or_else(|| "[No Name]".to_string(), |p| p.display().to_string())
1000}
1001
1002/// `:q` — leave, unless that would drop an unsaved change.
1003///
1004/// The refusal is what makes the bang mean something. Without it `:q` and
1005/// `:q!` are the same key sequence with different lengths, and the editor
1006/// discards an afternoon's typing without a word — which is the one failure
1007/// mode a modal editor's users are trained to expect protection from.
1008struct QuitChecked<const ALL: bool>;
1009impl<const ALL: bool> Native for QuitChecked<ALL> {
1010    type Reads = caps!(Buffers);
1011    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
1012        let b = v.buffers();
1013        // `:q` asks about the buffer in front of the operator; `:qa` asks
1014        // about every one, because it is the whole editor it is closing.
1015        let blocker = if ALL {
1016            b.ids()
1017                .into_iter()
1018                .filter_map(|id| b.get(id))
1019                .find(|x| x.is_modified())
1020                .map(buffer_label)
1021        } else {
1022            b.active().filter(|x| x.is_modified()).map(buffer_label)
1023        };
1024        match blocker {
1025            Some(what) => no_write_since_last_change(&what),
1026            None => Outcome::did(vec![Negai::Quit]),
1027        }
1028    }
1029}
1030
1031/// `:wq` — write the active buffer, then leave.
1032///
1033/// Writes unconditionally, as vim does: `:wq` is how you touch a file's mtime
1034/// on purpose. `:x` is the other one. A buffer with no path cannot be written
1035/// anywhere, so it declines rather than quitting and silently losing the
1036/// text — `:wq` on a scratch buffer promised a write.
1037struct WriteQuit;
1038impl Native for WriteQuit {
1039    type Reads = caps!(Buffers);
1040    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
1041        let b = v.buffers();
1042        let Some(buf) = b.active() else {
1043            return Outcome::declined("no active buffer");
1044        };
1045        if buf.path().is_none() {
1046            return Outcome::declined("E32: No file name");
1047        }
1048        Outcome::did(vec![Negai::Save { buffer: buf.id() }, Negai::Quit])
1049    }
1050}
1051
1052/// `:x` / `:exit` — write only if modified, then leave.
1053///
1054/// The difference from `:wq` is one `is_modified` and it is not cosmetic: a
1055/// pointless write bumps the mtime, and something is always watching the
1056/// mtime.
1057struct ExitWrite;
1058impl Native for ExitWrite {
1059    type Reads = caps!(Buffers);
1060    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
1061        let b = v.buffers();
1062        let Some(buf) = b.active() else {
1063            return Outcome::declined("no active buffer");
1064        };
1065        if !buf.is_modified() {
1066            return Outcome::did(vec![Negai::Quit]);
1067        }
1068        if buf.path().is_none() {
1069            return Outcome::declined("E32: No file name");
1070        }
1071        Outcome::did(vec![Negai::Save { buffer: buf.id() }, Negai::Quit])
1072    }
1073}
1074
1075/// `:wqa` / `:xa` — write every modified, path-backed buffer, then leave.
1076///
1077/// Shares [`WriteAll`]'s rule about scratch buffers rather than restating it:
1078/// one slip per writable buffer, and a buffer with nowhere to go is skipped.
1079/// It does NOT decline on an unwritable buffer the way `:wq` does — `:wqa` is
1080/// a request to leave, and refusing the whole thing over one scratch buffer
1081/// would leave the operator with no way out but `:qa!`, which discards the
1082/// buffers `:wqa` was about to save.
1083struct WriteQuitAll;
1084impl Native for WriteQuitAll {
1085    type Reads = caps!(Buffers);
1086    fn run(v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
1087        let b = v.buffers();
1088        let mut slips: Vec<Negai> = b
1089            .ids()
1090            .into_iter()
1091            .filter(|id| {
1092                b.get(*id)
1093                    .is_some_and(|x| x.is_modified() && x.path().is_some())
1094            })
1095            .map(|buffer| Negai::Save { buffer })
1096            .collect();
1097        slips.push(Negai::Quit);
1098        Outcome::did(slips)
1099    }
1100}
1101
1102/// `:noh` — the command that proves the seam, and it also reads nothing.
1103///
1104/// It lived as a hard-coded branch inside `EditorState::run_command`,
1105/// bypassing the registry entirely, because the old `EditContext` exposed
1106/// buffers and modal state and could not reach `SearchState`. It is now an
1107/// ordinary command asking for an ordinary slip, and it turns out not to
1108/// need a view at all — it does not READ the search, it asks to change it.
1109struct Noh;
1110impl Native for Noh {
1111    type Reads = caps!();
1112    fn run(_v: &View<'_, Self::Reads>, _: &[String]) -> Outcome {
1113        Outcome::did(vec![Negai::ClearSearchHighlight])
1114    }
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119    use super::*;
1120    use escriba_core::BufferId;
1121    use escriba_madoguchi::{FakeBuffer, FakeSnapshot, Verdict};
1122
1123    /// A snapshot holding one dirty, path-backed buffer.
1124    fn dirty_file() -> FakeSnapshot {
1125        let mut s = FakeSnapshot::default();
1126        s.buffers = vec![FakeBuffer::new(1, "dirty").at("/tmp/x.txt").dirty()];
1127        s.active = Some(BufferId(1));
1128        s
1129    }
1130
1131    #[test]
1132    fn default_set_is_populated() {
1133        let r = CommandRegistry::default_set();
1134        let names = r.names();
1135        assert!(names.contains(&"save"));
1136        assert!(names.contains(&"quit"));
1137    }
1138
1139    #[test]
1140    fn specs_are_sorted() {
1141        let r = CommandRegistry::default_set();
1142        let specs = r.specs();
1143        assert!(specs.windows(2).all(|w| w[0].name <= w[1].name));
1144    }
1145
1146    #[test]
1147    fn not_found_errors() {
1148        // Phase 0's first failure: a name nobody registered. Still an Err,
1149        // because the runtime tells a typo apart from an unbuilt capability.
1150        let r = CommandRegistry::new();
1151        let err = r.run("nope", &FakeSnapshot::default(), &[]).unwrap_err();
1152        assert!(matches!(err, CommandError::NotFound(_)));
1153    }
1154
1155    #[test]
1156    fn a_command_asks_rather_than_acts() {
1157        // The whole point of the port. `write-all` used to reach into
1158        // `&mut BufferSet` and call `.save()`. It now RETURNS a request per
1159        // modified path-backed buffer and touches nothing — which is also
1160        // why it is best-effort by construction: the interpreter applies
1161        // each slip independently, so one permission error cannot abort the
1162        // rest.
1163        let mut r = CommandRegistry::new();
1164        r.register(Command::action(
1165            "w-all",
1166            "Write every modified buffer",
1167            "buffer.write-all",
1168        ));
1169        let out = r
1170            .run("w-all", &dirty_file(), &[])
1171            .expect("registered command dispatches");
1172        assert_eq!(
1173            out.slips,
1174            vec![Negai::Save {
1175                buffer: BufferId(1)
1176            }]
1177        );
1178        assert_eq!(out.verdict, Verdict::Did);
1179    }
1180
1181    #[test]
1182    fn nothing_to_save_declines_rather_than_claiming_success() {
1183        // Three verdicts, not two. A scratch buffer has no path, so there is
1184        // genuinely nothing to write — and saying "Did" would be the same
1185        // silent lie Phase 0 removed.
1186        let mut r = CommandRegistry::new();
1187        r.register(Command::action("w-all", "Write all", "buffer.write-all"));
1188        let out = r
1189            .run("w-all", &FakeSnapshot::with_buffer("scratch"), &[])
1190            .expect("dispatches");
1191        assert!(out.slips.is_empty());
1192        assert_eq!(out.verdict, Verdict::Declined("no modified files".into()));
1193    }
1194
1195    #[test]
1196    fn no_active_buffer_declines_rather_than_failing() {
1197        // Boot, and every `--no-defaults` run, reach commands with no
1198        // buffer. The operator did nothing wrong, so it is not an error.
1199        let mut r = CommandRegistry::new();
1200        r.register(Command::action("w", "Save", "buffer.save"));
1201        let out = r
1202            .run("w", &FakeSnapshot::default(), &[])
1203            .expect("dispatches");
1204        assert_eq!(out.verdict, Verdict::Declined("no active buffer".into()));
1205        assert!(out.slips.is_empty(), "a decline asks for nothing");
1206    }
1207
1208    #[test]
1209    fn unknown_action_symbol_is_reported_not_silent() {
1210        // This test used to assert the DEFECT — it called `.expect()` on the
1211        // Ok, pinning `_ => Ok(())`, under which a dead keybinding and a
1212        // working one were indistinguishable at every layer.
1213        //
1214        // Inert is still correct: `picker.files` genuinely has not landed.
1215        // SILENT was never correct. It must be `Unhandled`, not `NotFound`:
1216        // the command IS registered, which is what made the silence
1217        // misleading in the first place.
1218        let mut r = CommandRegistry::new();
1219        r.register(Command::action("pick", "Pick a file", "picker.files"));
1220        let err = r
1221            .run("pick", &FakeSnapshot::default(), &[])
1222            .expect_err("an unimplemented action must report, not report success");
1223        assert!(
1224            matches!(&err, CommandError::Unhandled(s) if s == "picker.files"),
1225            "expected Unhandled(picker.files), got {err:?}",
1226        );
1227        assert!(r.contains("pick"), "the command survives its own failure");
1228    }
1229
1230    #[test]
1231    fn action_naming_a_command_is_inert_not_recursive() {
1232        // `:action` takes action SYMBOLS, not command names: `run_action`
1233        // resolves dotted symbols and does NOT recurse into the registry.
1234        // Recursion would let a handler reach anything by naming it, which
1235        // is the ceiling madoguchi exists to remove.
1236        //
1237        // What changed with the port: the non-recursion is now REPORTED
1238        // rather than looking like a successful save.
1239        let mut r = CommandRegistry::new();
1240        r.register(Command::action("alias", "aliases save by name", "save"));
1241        let err = r
1242            .run("alias", &dirty_file(), &[])
1243            .expect_err("a command-name alias resolves nothing, and says so");
1244        assert!(
1245            matches!(&err, CommandError::Unhandled(s) if s == "save"),
1246            "expected Unhandled(save), got {err:?}",
1247        );
1248    }
1249
1250    #[test]
1251    fn quit_is_a_request_not_a_flag_poke() {
1252        // Was `*ctx.quit_requested = true` — a command reaching into a
1253        // borrowed flag. Quit is now a request like any other, and the
1254        // interpreter decides, because the interpreter is the thing that
1255        // knows about unsaved buffers.
1256        let mut r = CommandRegistry::new();
1257        r.register(Command::action("bye", "Quit", "editor.quit"));
1258        let out = r
1259            .run("bye", &FakeSnapshot::default(), &[])
1260            .expect("dispatches");
1261        assert_eq!(out.slips, vec![Negai::Quit]);
1262    }
1263
1264    #[test]
1265    fn buffer_info_speaks_through_a_slip_not_stderr() {
1266        // It used to `eprintln!`, which from a TUI holding the alternate
1267        // screen writes straight through the ratatui frame and corrupts it.
1268        // A command's only way to say anything is now Negai::Message.
1269        let mut r = CommandRegistry::new();
1270        r.register(Command::action("info", "Buffer info", "buffer.info"));
1271        let out = r.run("info", &dirty_file(), &[]).expect("dispatches");
1272        let Some(Negai::Message(m)) = out.slips.first() else {
1273            panic!("expected a Message slip, got {:?}", out.slips);
1274        };
1275        assert!(m.contains("buffer 1"), "{m}");
1276        assert!(m.contains("[modified]"), "{m}");
1277    }
1278}