1extern 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 #[error("action `{0}` is declared but not implemented yet")]
27 Unhandled(String),
28 #[error("command failed: {0}")]
29 Failed(String),
30 }
35
36pub type Result<T> = std::result::Result<T, CommandError>;
37
38pub type CommandFn = fn(&dyn Snapshot, &[String]) -> Outcome;
47
48#[derive(Debug, Clone)]
63pub enum Handler {
64 Native(CommandFn),
66 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 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 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 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 #[must_use]
213 pub fn contains(&self, name: &str) -> bool {
214 self.commands.contains_key(name)
215 }
216
217 #[must_use]
219 pub fn len(&self) -> usize {
220 self.commands.len()
221 }
222
223 #[must_use]
225 pub fn is_empty(&self) -> bool {
226 self.commands.is_empty()
227 }
228
229 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
268fn 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 _ => Err(CommandError::Unhandled(sym.to_string())),
282 }
283}
284
285fn 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
297struct 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
356struct 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
383struct 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
407struct 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
422struct 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 if line.trim().is_empty() {
451 return Outcome::declined("nothing on this line");
452 }
453
454 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
482struct 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
526struct 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 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 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 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 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 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 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 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 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 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}