Skip to main content

indigo_core/mode/
command.rs

1use crate::{buffer::Buffer, client::ClientMut, mode::prompt, window::WindowState};
2use anyhow::anyhow;
3use bpaf::{OptionParser, ParseFailure, Parser as _, choice, construct, long, positional, pure};
4use camino::Utf8PathBuf;
5
6#[derive(Clone, Debug)]
7pub enum Command {
8    Nop,
9    Echo { error: bool, message: Vec<String> },
10    Edit { path: Utf8PathBuf },
11    Write { path: Option<Utf8PathBuf> },
12    Quit { exit_code: Option<u8> },
13    QuitForce { exit_code: Option<u8> },
14    WriteQuit { exit_code: Option<u8> },
15    Readonly,
16    Panic,
17}
18
19pub fn enter_command_mode(client: &mut ClientMut) {
20    prompt::enter(client, "", |client, input| match parse_command(input) {
21        Ok(command) => handle_command(client, &command),
22        Err(error) => client.set_error(error.to_string()),
23    });
24}
25
26struct Spec {
27    name: &'static str,
28    aliases: &'static [&'static str],
29    /// Parses the command's arguments. The name and aliases are applied by `parse_command`.
30    parser: fn() -> OptionParser<Command>,
31}
32
33const COMMANDS: &[Spec] = &[
34    Spec {
35        name: "echo",
36        aliases: &[],
37        parser: || {
38            let error = long("error").switch();
39            let message = positional("MESSAGE").many();
40            construct!(Command::Echo { error, message }).to_options()
41        },
42    },
43    Spec {
44        name: "edit",
45        aliases: &["e"],
46        parser: || {
47            let path = positional("PATH");
48            construct!(Command::Edit { path }).to_options()
49        },
50    },
51    Spec {
52        name: "write",
53        aliases: &["w"],
54        parser: || {
55            let path = positional("PATH").optional();
56            construct!(Command::Write { path }).to_options()
57        },
58    },
59    Spec {
60        name: "quit",
61        aliases: &["q"],
62        parser: || {
63            let exit_code = positional("EXIT_CODE").optional();
64            construct!(Command::Quit { exit_code }).to_options()
65        },
66    },
67    Spec {
68        name: "quit!",
69        aliases: &["q!"],
70        parser: || {
71            let exit_code = positional("EXIT_CODE").optional();
72            construct!(Command::QuitForce { exit_code }).to_options()
73        },
74    },
75    Spec {
76        name: "writequit",
77        aliases: &["wq"],
78        parser: || {
79            let exit_code = positional("EXIT_CODE").optional();
80            construct!(Command::WriteQuit { exit_code }).to_options()
81        },
82    },
83    Spec {
84        name: "readonly",
85        aliases: &["ro"],
86        parser: || pure(Command::Readonly).to_options(),
87    },
88    Spec {
89        name: "panic",
90        aliases: &[],
91        parser: || pure(Command::Panic).to_options(),
92    },
93];
94
95fn parse_command(command: &str) -> anyhow::Result<Command> {
96    let parser = choice(COMMANDS.iter().map(|spec| {
97        let mut parser = (spec.parser)().command(spec.name);
98        for alias in spec.aliases {
99            parser = parser.long(alias);
100        }
101        parser.boxed()
102    }))
103    .to_options();
104
105    let Ok(args) = shell_words::split(command) else {
106        anyhow::bail!("Invalid command");
107    };
108
109    if args.is_empty() {
110        return Ok(Command::Nop);
111    }
112
113    parser.run_inner(args.as_slice()).map_err(|failure| {
114        let message = match failure {
115            ParseFailure::Stderr(doc) => doc.monochrome(true),
116            ParseFailure::Stdout(doc, full) => doc.monochrome(full),
117            ParseFailure::Completion(s) => s,
118        };
119        anyhow!("{message}")
120    })
121}
122
123fn handle_command(client: &mut ClientMut, command: &Command) {
124    match command {
125        Command::Nop => {}
126        Command::Echo { error, message } => {
127            if *error {
128                client.set_error(message.join(" "));
129            } else {
130                client.set_message(message.join(" "));
131            }
132        }
133        Command::Edit { path } => {
134            // TODO: Edit existing buffer for path if one exists.
135            let absolute_path = client.absolute_path(path);
136            match Buffer::open(client.fs(), &absolute_path) {
137                Ok(buffer) => {
138                    // In Kakoune, windows are inextricably linked to buffers, so changing buffer
139                    // means changing window, creating a new one if necessary.
140                    // https://github.com/mawww/kakoune/blob/afc035ac0e17a6280edec511dfe8da1c0dd565ab/doc/pages/scopes.asciidoc?plain=1#L29-L30
141                    let buffer_key = client.session_mut().insert_buffer(buffer);
142                    let window_state = WindowState::new(buffer_key);
143                    let window_key = client.insert_window(window_state);
144                    assert!(client.focus_window(window_key));
145                    // TODO: Delete previous window. It's no longer focused, so (at the time of
146                    // writing) that means it's not displayed, it's just hanging out unused in
147                    // memory.
148                }
149                Err(error) => {
150                    let path = client.display_path(&absolute_path);
151                    client.set_error(format!("Failed to open {path}: {error:#}"));
152                }
153            }
154        }
155        Command::Write { path } => {
156            let fs = client.fs();
157            let absolute_path = path.as_ref().map(|path| client.absolute_path(path));
158            let result = if let Some(absolute_path) = &absolute_path {
159                client.focused_buffer_mut().save_as(fs, absolute_path)
160            } else {
161                client.focused_buffer_mut().save(fs)
162            };
163            if let Err(error) = result {
164                let path = absolute_path
165                    .as_deref()
166                    .or_else(|| client.focused_buffer().path())
167                    .map_or_else(
168                        || "a scratch buffer".to_owned(),
169                        |path| client.display_path(path),
170                    );
171                let error = format!("Failed to save {path}: {error:#}");
172                client.set_error(error);
173            }
174        }
175        Command::Quit { exit_code } => {
176            let mut modified = None;
177            for (_, buffer) in client.session().buffers() {
178                if buffer.is_modified().unwrap_or(false) {
179                    modified = Some(buffer.path().map_or_else(
180                        || "a scratch buffer".to_owned(),
181                        |path| client.display_path(path),
182                    ));
183                    break;
184                }
185            }
186            if let Some(modified) = modified {
187                let error = format!("Unsaved changes in {modified}");
188                client.set_error(error);
189            } else {
190                client.exit(exit_code.unwrap_or(0));
191            }
192        }
193        Command::QuitForce { exit_code } => {
194            client.exit(exit_code.unwrap_or(0));
195        }
196        Command::WriteQuit { exit_code } => {
197            let fs = client.fs();
198            match client.focused_buffer_mut().save(fs) {
199                Ok(()) => client.exit(exit_code.unwrap_or(0)),
200                Err(error) => {
201                    let path = client.focused_buffer().path().map_or_else(
202                        || "a scratch buffer".to_owned(),
203                        |path| client.display_path(path),
204                    );
205                    let error = format!("Failed to save {path}: {error:#}");
206                    client.set_error(error);
207                }
208            }
209        }
210        Command::Readonly => {
211            let new_readonly = !client.focused_buffer().text.readonly;
212            client.focused_buffer_mut().text.readonly = new_readonly;
213            if new_readonly {
214                client.set_message("Buffer is now readonly");
215            } else {
216                client.set_message("Buffer is no longer readonly");
217            }
218        }
219        Command::Panic => panic!(),
220    }
221}