Skip to main content

mortise_core/
editor.rs

1//! Opening a file in the user's editor, at a line.
2
3use std::path::Path;
4use std::process::Stdio;
5
6use serde::{Deserialize, Serialize};
7
8use crate::program::split_words;
9
10/// The editor that opens files.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
12#[serde(rename_all = "kebab-case")]
13pub enum Editor {
14    #[default]
15    VsCode,
16    PhpStorm,
17    Zed,
18    /// A command the user wrote.
19    Custom,
20}
21
22impl Editor {
23    /// The command of the editor, with `{file}` and `{line}` where they go.
24    /// `None` for [`Editor::Custom`], whose command the user writes.
25    pub fn command(self) -> Option<&'static str> {
26        match self {
27            Editor::VsCode => Some("code --goto {file}:{line}"),
28            Editor::PhpStorm => Some("phpstorm --line {line} {file}"),
29            Editor::Zed => Some("zed {file}:{line}"),
30            Editor::Custom => None,
31        }
32    }
33}
34
35/// The editor did not start. `program` is the first word of the command and
36/// `message` is the operating system's own text.
37#[derive(Debug, thiserror::Error)]
38#[error("{program}: {message}")]
39pub struct EditorError {
40    pub program: String,
41    pub message: String,
42}
43
44/// Splits a command into its program and arguments, with the file and the line put in.
45///
46/// Words are split at spaces; a part in double quotes is one word. The file and
47/// the line are put in after splitting, so a path with spaces stays one argument.
48pub fn editor_arguments(command: &str, file: &Path, line: u32) -> Vec<String> {
49    let file = file.to_string_lossy();
50    split_words(command)
51        .into_iter()
52        .map(|word| {
53            word.replace("{file}", &file)
54                .replace("{line}", &line.to_string())
55        })
56        .collect()
57}
58
59/// Starts the editor on a file at a line. Does not wait for it to close.
60pub fn open_in_editor(command: &str, file: &Path, line: u32) -> Result<(), EditorError> {
61    let mut words = editor_arguments(command, file, line).into_iter();
62    let program = words.next().unwrap_or_default();
63    crate::program::command(&program)
64        .args(words)
65        .stdout(Stdio::null())
66        .stderr(Stdio::null())
67        .spawn()
68        .map(|_| ())
69        .map_err(|error| EditorError {
70            program,
71            message: error.to_string(),
72        })
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[test]
80    fn the_file_and_the_line_are_put_into_the_command() {
81        let file = Path::new("/code/shop api/Modules/Billing/app/Models/Invoice.php");
82        assert_eq!(
83            editor_arguments(Editor::VsCode.command().unwrap(), file, 12),
84            [
85                "code",
86                "--goto",
87                "/code/shop api/Modules/Billing/app/Models/Invoice.php:12"
88            ]
89        );
90        assert_eq!(
91            editor_arguments(Editor::PhpStorm.command().unwrap(), file, 7),
92            [
93                "phpstorm",
94                "--line",
95                "7",
96                "/code/shop api/Modules/Billing/app/Models/Invoice.php"
97            ]
98        );
99        assert_eq!(
100            editor_arguments(
101                r#""/Applications/My Editor/bin/edit"  -l {line}  {file}"#,
102                Path::new("a.php"),
103                3
104            ),
105            ["/Applications/My Editor/bin/edit", "-l", "3", "a.php"]
106        );
107        assert!(editor_arguments("   ", file, 1).is_empty());
108    }
109
110    #[test]
111    fn an_editor_that_is_not_there_gives_its_name_and_the_systems_message() {
112        let error =
113            open_in_editor("mortise-no-such-editor {file}", Path::new("a.php"), 1).unwrap_err();
114        assert_eq!(error.program, "mortise-no-such-editor");
115        assert!(!error.message.is_empty());
116        assert!(error.to_string().starts_with("mortise-no-such-editor: "));
117    }
118}