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