Skip to main content

oxinav_core/
launch.rs

1//! Deciding which external program to start, and with which arguments.
2//!
3//! Everything here is pure: the environment the decision depends on comes in
4//! as a `LaunchEnv`, and the result is a `CommandSpec` describing the process.
5//! Spawning it is the app's job, so the choice of terminal can be tested for
6//! any machine without starting anything.
7
8use std::path::{Path, PathBuf};
9use thiserror::Error;
10
11/// A process to start: `program` with `args`, running in `cwd`.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct CommandSpec {
14    pub program: String,
15    pub args: Vec<String>,
16    pub cwd: PathBuf,
17}
18
19/// The parts of the environment that decide which terminal to use.
20pub struct LaunchEnv<'a> {
21    /// `$TERMINAL`, the user's explicit choice.
22    pub terminal: Option<String>,
23    /// `$XDG_CURRENT_DESKTOP`, colon-separated (`ubuntu:GNOME`).
24    pub desktop: Option<String>,
25    /// `$VISUAL`, the preferred editor.
26    pub visual: Option<String>,
27    /// `$EDITOR`, used when `$VISUAL` is unset.
28    pub editor: Option<String>,
29    /// Whether a program can be started: a name is looked up on `PATH`, a
30    /// path is checked directly.
31    pub which: &'a dyn Fn(&str) -> bool,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Error)]
35pub enum LaunchError {
36    #[error("No terminal emulator was found. Set $TERMINAL to the one you use.")]
37    NoTerminal,
38    #[error("No terminal emulator was found to run {0}. Set $TERMINAL to the one you use.")]
39    NoTerminalForEditor(String),
40    #[error("The editor {0} was not found. Check $VISUAL and $EDITOR.")]
41    EditorNotFound(String),
42}
43
44/// How to open a file for editing.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum EditorLaunch {
47    /// A GUI editor, started as is.
48    Direct(CommandSpec),
49    /// A terminal editor, already wrapped in a terminal emulator.
50    InTerminal(CommandSpec),
51    /// No editor is configured: open the file with the desktop's default
52    /// application, as Enter does.
53    DefaultApp,
54}
55
56/// Editors that need a terminal to draw in. `emacs` and `emacsclient` are
57/// decided by their arguments instead (see `needs_terminal`).
58const TERMINAL_EDITORS: &[&str] = &[
59    "vi", "vim", "nvim", "view", "nano", "pico", "micro", "hx", "helix", "kak", "joe", "jed", "ne",
60    "mcedit", "mg", "ed",
61];
62
63fn needs_terminal(program: &str, args: &[String]) -> bool {
64    let name = Path::new(program)
65        .file_name()
66        .and_then(|name| name.to_str())
67        .unwrap_or(program);
68    let has = |flags: &[&str]| args.iter().any(|arg| flags.contains(&arg.as_str()));
69    match name {
70        // With a display, bare emacs opens a window of its own.
71        "emacs" => has(&["-nw", "-t"]),
72        "emacsclient" => has(&["-nw", "-t", "--tty"]),
73        _ => TERMINAL_EDITORS.contains(&name),
74    }
75}
76
77/// The editor for `file`: `$VISUAL`, else `$EDITOR`, split on whitespace
78/// with its arguments ahead of the file. A terminal editor runs in a
79/// terminal opened in the file's directory.
80pub fn editor_command(env: &LaunchEnv, file: &Path) -> Result<EditorLaunch, LaunchError> {
81    let configured = [&env.visual, &env.editor]
82        .into_iter()
83        .flatten()
84        .find(|value| !value.trim().is_empty());
85    let Some(configured) = configured else {
86        return Ok(EditorLaunch::DefaultApp);
87    };
88
89    let mut words = configured.split_whitespace().map(str::to_string);
90    let program = words.next().expect("a non-blank value has a first word");
91    let mut args: Vec<String> = words.collect();
92    if !(env.which)(&program) {
93        return Err(LaunchError::EditorNotFound(program));
94    }
95    let terminal = needs_terminal(&program, &args);
96    // Passed as one argument and never through a shell, so a path with
97    // spaces needs no quoting.
98    args.push(file.to_string_lossy().into_owned());
99    let dir = file.parent().unwrap_or(file).to_path_buf();
100
101    if terminal {
102        let command: Vec<String> = std::iter::once(program.clone()).chain(args).collect();
103        return terminal_command(env, &dir, Some(&command))
104            .map(EditorLaunch::InTerminal)
105            .map_err(|_| LaunchError::NoTerminalForEditor(program));
106    }
107    Ok(EditorLaunch::Direct(CommandSpec {
108        program,
109        args,
110        cwd: dir,
111    }))
112}
113
114/// Where a terminal takes its starting directory.
115#[derive(Clone, Copy)]
116enum DirArgs {
117    /// These flags, then the directory as its own argument.
118    Flag(&'static [&'static str]),
119    /// A single `flag=DIR` argument.
120    Equals(&'static str),
121    /// No flag; the terminal inherits the process's `cwd`.
122    Inherit,
123}
124
125/// A terminal emulator OxiNav knows the command line of.
126struct Terminal {
127    program: &'static str,
128    dir: DirArgs,
129    /// Arguments placed before the command to run.
130    run: &'static [&'static str],
131}
132
133const KNOWN_TERMINALS: &[Terminal] = &[
134    // The proposed freedesktop default-terminal launcher: it picks the
135    // user's configured terminal and knows that terminal's own flags.
136    Terminal {
137        program: "xdg-terminal-exec",
138        dir: DirArgs::Equals("--dir"),
139        run: &["--"],
140    },
141    Terminal {
142        program: "konsole",
143        dir: DirArgs::Flag(&["--workdir"]),
144        run: &["-e"],
145    },
146    Terminal {
147        program: "gnome-terminal",
148        dir: DirArgs::Equals("--working-directory"),
149        run: &["--"],
150    },
151    Terminal {
152        program: "kgx",
153        dir: DirArgs::Equals("--working-directory"),
154        run: &["--"],
155    },
156    Terminal {
157        program: "xfce4-terminal",
158        dir: DirArgs::Equals("--working-directory"),
159        run: &["-x"],
160    },
161    Terminal {
162        program: "alacritty",
163        dir: DirArgs::Flag(&["--working-directory"]),
164        run: &["-e"],
165    },
166    Terminal {
167        program: "kitty",
168        dir: DirArgs::Flag(&["--directory"]),
169        run: &[],
170    },
171    Terminal {
172        program: "foot",
173        dir: DirArgs::Equals("--working-directory"),
174        run: &[],
175    },
176    Terminal {
177        program: "wezterm",
178        dir: DirArgs::Flag(&["start", "--cwd"]),
179        run: &["--"],
180    },
181    Terminal {
182        program: "xterm",
183        dir: DirArgs::Inherit,
184        run: &["-e"],
185    },
186    Terminal {
187        program: "x-terminal-emulator",
188        dir: DirArgs::Inherit,
189        run: &["-e"],
190    },
191];
192
193/// How a `$TERMINAL` OxiNav has never heard of is driven: it inherits the
194/// directory, and `-e` is the most common way to run a command.
195const UNKNOWN_TERMINAL: Terminal = Terminal {
196    program: "",
197    dir: DirArgs::Inherit,
198    run: &["-e"],
199};
200
201/// The desktop's own terminals, by `$XDG_CURRENT_DESKTOP` component.
202const DESKTOP_TERMINALS: &[(&str, &[&str])] = &[
203    ("KDE", &["konsole"]),
204    ("GNOME", &["kgx", "gnome-terminal"]),
205    ("XFCE", &["xfce4-terminal"]),
206];
207
208/// Tried last, in order, when nothing more specific is available.
209const FALLBACK_TERMINALS: &[&str] = &[
210    "konsole",
211    "gnome-terminal",
212    "kgx",
213    "xfce4-terminal",
214    "alacritty",
215    "kitty",
216    "foot",
217    "wezterm",
218    "xterm",
219];
220
221/// The command that opens a terminal in `dir`, optionally running `run`
222/// inside it instead of a shell.
223pub fn terminal_command(
224    env: &LaunchEnv,
225    dir: &Path,
226    run: Option<&[String]>,
227) -> Result<CommandSpec, LaunchError> {
228    if cfg!(target_os = "macos") {
229        Ok(macos_terminal(env, dir, run))
230    } else if cfg!(target_os = "windows") {
231        Ok(windows_terminal(env, dir, run))
232    } else {
233        unix_terminal(env, dir, run)
234    }
235}
236
237/// `$TERMINAL` when it names an installed program. It may carry arguments
238/// of its own (`kitty --single-instance`); they go straight after the
239/// program, ahead of OxiNav's flags.
240fn terminal_from_variable(
241    env: &LaunchEnv,
242    dir: &Path,
243    run: Option<&[String]>,
244) -> Option<CommandSpec> {
245    let terminal = env.terminal.as_deref()?;
246    let mut words = terminal.split_whitespace();
247    let program = words.next()?;
248    if !(env.which)(program) {
249        return None;
250    }
251    let extra: Vec<String> = words.map(str::to_string).collect();
252    let name = Path::new(program)
253        .file_name()
254        .and_then(|name| name.to_str())
255        .unwrap_or(program);
256    let known = known_terminal(name).unwrap_or(&UNKNOWN_TERMINAL);
257    Some(build(program, extra, known, dir, run))
258}
259
260/// `$TERMINAL`, then `xdg-terminal-exec`, then the desktop's own terminal,
261/// then Debian's `x-terminal-emulator`, then the fallback list — skipping
262/// anything that is not installed.
263fn unix_terminal(
264    env: &LaunchEnv,
265    dir: &Path,
266    run: Option<&[String]>,
267) -> Result<CommandSpec, LaunchError> {
268    if let Some(spec) = terminal_from_variable(env, dir, run) {
269        return Ok(spec);
270    }
271
272    let desktop_terminals = env
273        .desktop
274        .iter()
275        .flat_map(|desktop| desktop.split(':'))
276        .flat_map(|component| {
277            DESKTOP_TERMINALS
278                .iter()
279                .filter(move |(name, _)| name.eq_ignore_ascii_case(component))
280                .flat_map(|(_, programs)| programs.iter().copied())
281        });
282    let candidates = std::iter::once("xdg-terminal-exec")
283        .chain(desktop_terminals)
284        .chain(std::iter::once("x-terminal-emulator"))
285        .chain(FALLBACK_TERMINALS.iter().copied());
286
287    for program in candidates {
288        if (env.which)(program) {
289            let known = known_terminal(program).expect("every candidate is in the table");
290            return Ok(build(program, Vec::new(), known, dir, run));
291        }
292    }
293    Err(LaunchError::NoTerminal)
294}
295
296fn known_terminal(name: &str) -> Option<&'static Terminal> {
297    KNOWN_TERMINALS.iter().find(|t| t.program == name)
298}
299
300fn build(
301    program: &str,
302    mut args: Vec<String>,
303    terminal: &Terminal,
304    dir: &Path,
305    run: Option<&[String]>,
306) -> CommandSpec {
307    let dir_text = dir.to_string_lossy();
308    match terminal.dir {
309        DirArgs::Flag(flags) => {
310            args.extend(flags.iter().map(|flag| flag.to_string()));
311            args.push(dir_text.into_owned());
312        }
313        DirArgs::Equals(flag) => args.push(format!("{flag}={dir_text}")),
314        DirArgs::Inherit => {}
315    }
316    if let Some(command) = run {
317        args.extend(terminal.run.iter().map(|arg| arg.to_string()));
318        args.extend(command.iter().cloned());
319    }
320    CommandSpec {
321        program: program.to_string(),
322        args,
323        // Set even when a flag names the directory: terminals without one
324        // inherit it, and for the rest it is a harmless backup.
325        cwd: dir.to_path_buf(),
326    }
327}
328
329/// A `$TERMINAL` on `PATH` (kitty, alacritty, wezterm…) is driven exactly as
330/// on Linux. Otherwise `$TERMINAL` names an application (`iTerm`), and
331/// without it Terminal.app is used.
332///
333/// `open -a APP DIR` can only open the directory. Running a command goes
334/// through Terminal.app's `do script`, the one scriptable entry point every
335/// Mac has, so a command always runs in Terminal.app unless `$TERMINAL` is a
336/// command-line terminal.
337fn macos_terminal(env: &LaunchEnv, dir: &Path, run: Option<&[String]>) -> CommandSpec {
338    if let Some(spec) = terminal_from_variable(env, dir, run) {
339        return spec;
340    }
341    let dir_text = dir.to_string_lossy().into_owned();
342    let (program, args) = match run {
343        None => {
344            let app = env
345                .terminal
346                .as_deref()
347                .map(str::trim)
348                .filter(|app| !app.is_empty())
349                .unwrap_or("Terminal");
350            ("open", vec!["-a".to_string(), app.to_string(), dir_text])
351        }
352        Some(command) => {
353            let line = std::iter::once("cd".to_string())
354                .chain(std::iter::once(shell_quote(&dir_text)))
355                .chain(std::iter::once("&&".to_string()))
356                .chain(command.iter().map(|arg| shell_quote(arg)))
357                .collect::<Vec<_>>()
358                .join(" ");
359            let script = format!(
360                "tell application \"Terminal\" to do script \"{}\"",
361                applescript_escape(&line)
362            );
363            (
364                "osascript",
365                vec![
366                    "-e".to_string(),
367                    script,
368                    "-e".to_string(),
369                    "tell application \"Terminal\" to activate".to_string(),
370                ],
371            )
372        }
373    };
374    CommandSpec {
375        program: program.to_string(),
376        args,
377        cwd: dir.to_path_buf(),
378    }
379}
380
381/// Single-quote `text` for a POSIX shell.
382fn shell_quote(text: &str) -> String {
383    format!("'{}'", text.replace('\'', "'\\''"))
384}
385
386/// Escape `text` for the inside of an AppleScript string literal.
387fn applescript_escape(text: &str) -> String {
388    text.replace('\\', "\\\\").replace('"', "\\\"")
389}
390
391/// Windows Terminal when it is installed, else a plain `cmd` window.
392fn windows_terminal(env: &LaunchEnv, dir: &Path, run: Option<&[String]>) -> CommandSpec {
393    let dir_text = dir.to_string_lossy().into_owned();
394    let (program, mut args) = if (env.which)("wt") {
395        ("wt", vec!["-d".to_string(), dir_text])
396    } else {
397        let args = match run {
398            // `cwd` already puts cmd in the directory; /K keeps the window
399            // open after the command so its output can be read.
400            Some(_) => vec!["/K".to_string()],
401            None => vec![
402                "/K".to_string(),
403                "cd".to_string(),
404                "/d".to_string(),
405                dir_text,
406            ],
407        };
408        ("cmd", args)
409    };
410    if let Some(command) = run {
411        args.extend(command.iter().cloned());
412    }
413    CommandSpec {
414        program: program.to_string(),
415        args,
416        cwd: dir.to_path_buf(),
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423
424    fn env<'a>(
425        terminal: Option<&str>,
426        desktop: Option<&str>,
427        which: &'a dyn Fn(&str) -> bool,
428    ) -> LaunchEnv<'a> {
429        LaunchEnv {
430            terminal: terminal.map(str::to_string),
431            desktop: desktop.map(str::to_string),
432            visual: None,
433            editor: None,
434            which,
435        }
436    }
437
438    fn editor_env<'a>(
439        visual: Option<&str>,
440        editor: Option<&str>,
441        which: &'a dyn Fn(&str) -> bool,
442    ) -> LaunchEnv<'a> {
443        LaunchEnv {
444            visual: visual.map(str::to_string),
445            editor: editor.map(str::to_string),
446            ..env(None, Some("KDE"), which)
447        }
448    }
449
450    fn file() -> PathBuf {
451        PathBuf::from("/home/u/a.txt")
452    }
453
454    fn direct(launch: EditorLaunch) -> CommandSpec {
455        match launch {
456            EditorLaunch::Direct(spec) => spec,
457            other => panic!("expected a direct launch, got {other:?}"),
458        }
459    }
460
461    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
462    fn in_terminal(launch: EditorLaunch) -> CommandSpec {
463        match launch {
464            EditorLaunch::InTerminal(spec) => spec,
465            other => panic!("expected a terminal launch, got {other:?}"),
466        }
467    }
468
469    fn dir() -> PathBuf {
470        PathBuf::from("/home/u/src")
471    }
472
473    fn strings(words: &[&str]) -> Vec<String> {
474        words.iter().map(|w| w.to_string()).collect()
475    }
476
477    fn installed(programs: &'static [&'static str]) -> impl Fn(&str) -> bool {
478        move |program| programs.contains(&program)
479    }
480
481    #[test]
482    fn terminal_variable_wins_over_the_desktop() {
483        let which = installed(&["alacritty", "konsole"]);
484        let spec =
485            unix_terminal(&env(Some("alacritty"), Some("KDE"), &which), &dir(), None).unwrap();
486        assert_eq!(spec.program, "alacritty");
487    }
488
489    #[test]
490    fn terminal_variable_keeps_its_own_arguments_first() {
491        let which = installed(&["kitty"]);
492        let spec = unix_terminal(
493            &env(Some("kitty --single-instance"), None, &which),
494            &dir(),
495            None,
496        )
497        .unwrap();
498        assert_eq!(spec.program, "kitty");
499        assert_eq!(
500            spec.args,
501            strings(&["--single-instance", "--directory", "/home/u/src"])
502        );
503    }
504
505    #[test]
506    fn terminal_variable_given_as_a_path_uses_the_known_flags() {
507        let which = installed(&["/usr/bin/konsole"]);
508        let spec =
509            unix_terminal(&env(Some("/usr/bin/konsole"), None, &which), &dir(), None).unwrap();
510        assert_eq!(spec.program, "/usr/bin/konsole");
511        assert_eq!(spec.args, strings(&["--workdir", "/home/u/src"]));
512    }
513
514    #[test]
515    fn missing_terminal_variable_falls_through() {
516        let which = installed(&["konsole"]);
517        let spec =
518            unix_terminal(&env(Some("nonexistent"), Some("KDE"), &which), &dir(), None).unwrap();
519        assert_eq!(spec.program, "konsole");
520    }
521
522    #[test]
523    fn kde_picks_konsole() {
524        let which = installed(&["konsole", "gnome-terminal", "x-terminal-emulator"]);
525        let spec = unix_terminal(&env(None, Some("KDE"), &which), &dir(), None).unwrap();
526        assert_eq!(spec.program, "konsole");
527    }
528
529    #[test]
530    fn gnome_is_found_among_desktop_components() {
531        let which = installed(&["gnome-terminal", "konsole", "x-terminal-emulator"]);
532        let spec = unix_terminal(&env(None, Some("ubuntu:GNOME"), &which), &dir(), None).unwrap();
533        assert_eq!(spec.program, "gnome-terminal");
534    }
535
536    #[test]
537    fn gnome_prefers_console_over_terminal() {
538        let which = installed(&["gnome-terminal", "kgx"]);
539        let spec = unix_terminal(&env(None, Some("GNOME"), &which), &dir(), None).unwrap();
540        assert_eq!(spec.program, "kgx");
541    }
542
543    #[test]
544    fn debian_alternative_comes_before_the_fallback_list() {
545        let which = installed(&["xterm", "x-terminal-emulator"]);
546        let spec = unix_terminal(&env(None, Some("sway"), &which), &dir(), None).unwrap();
547        assert_eq!(spec.program, "x-terminal-emulator");
548    }
549
550    #[test]
551    fn fallback_list_is_used_last() {
552        let which = installed(&["foot"]);
553        let spec = unix_terminal(&env(None, None, &which), &dir(), None).unwrap();
554        assert_eq!(spec.program, "foot");
555    }
556
557    #[test]
558    fn nothing_installed_is_an_error() {
559        let which = installed(&[]);
560        assert_eq!(
561            unix_terminal(&env(Some("alacritty"), Some("KDE"), &which), &dir(), None),
562            Err(LaunchError::NoTerminal)
563        );
564    }
565
566    #[test]
567    fn every_known_terminal_gets_its_directory_and_run_arguments() {
568        let run = strings(&["vim", "notes.txt"]);
569        let cases: &[(&str, &[&str])] = &[
570            (
571                "konsole",
572                &["--workdir", "/home/u/src", "-e", "vim", "notes.txt"],
573            ),
574            (
575                "gnome-terminal",
576                &["--working-directory=/home/u/src", "--", "vim", "notes.txt"],
577            ),
578            (
579                "kgx",
580                &["--working-directory=/home/u/src", "--", "vim", "notes.txt"],
581            ),
582            (
583                "xfce4-terminal",
584                &["--working-directory=/home/u/src", "-x", "vim", "notes.txt"],
585            ),
586            (
587                "alacritty",
588                &[
589                    "--working-directory",
590                    "/home/u/src",
591                    "-e",
592                    "vim",
593                    "notes.txt",
594                ],
595            ),
596            ("kitty", &["--directory", "/home/u/src", "vim", "notes.txt"]),
597            (
598                "foot",
599                &["--working-directory=/home/u/src", "vim", "notes.txt"],
600            ),
601            (
602                "wezterm",
603                &["start", "--cwd", "/home/u/src", "--", "vim", "notes.txt"],
604            ),
605            ("xterm", &["-e", "vim", "notes.txt"]),
606            ("x-terminal-emulator", &["-e", "vim", "notes.txt"]),
607        ];
608        for (program, expected) in cases {
609            let which = move |p: &str| p == *program;
610            let spec =
611                unix_terminal(&env(Some(program), None, &which), &dir(), Some(&run)).unwrap();
612            assert_eq!(spec.args, strings(expected), "{program}");
613            assert_eq!(spec.cwd, dir(), "{program}");
614        }
615    }
616
617    #[test]
618    fn without_a_command_only_the_directory_is_passed() {
619        let which = installed(&["konsole"]);
620        let spec = unix_terminal(&env(None, Some("KDE"), &which), &dir(), None).unwrap();
621        assert_eq!(spec.args, strings(&["--workdir", "/home/u/src"]));
622    }
623
624    #[test]
625    fn unknown_terminal_variable_inherits_the_directory_and_uses_dash_e() {
626        let which = installed(&["myterm"]);
627        let run = strings(&["nano", "a.txt"]);
628        let spec = unix_terminal(&env(Some("myterm"), None, &which), &dir(), Some(&run)).unwrap();
629        assert_eq!(spec.program, "myterm");
630        assert_eq!(spec.args, strings(&["-e", "nano", "a.txt"]));
631        assert_eq!(spec.cwd, dir());
632    }
633
634    #[test]
635    fn xdg_terminal_exec_comes_before_the_desktop() {
636        let which = installed(&["konsole", "xdg-terminal-exec"]);
637        let run = strings(&["vim", "notes.txt"]);
638        let spec = unix_terminal(&env(None, Some("KDE"), &which), &dir(), Some(&run)).unwrap();
639        assert_eq!(spec.program, "xdg-terminal-exec");
640        assert_eq!(
641            spec.args,
642            strings(&["--dir=/home/u/src", "--", "vim", "notes.txt"])
643        );
644    }
645
646    #[test]
647    fn terminal_variable_wins_over_xdg_terminal_exec() {
648        let which = installed(&["kitty", "xdg-terminal-exec"]);
649        let spec = unix_terminal(&env(Some("kitty"), None, &which), &dir(), None).unwrap();
650        assert_eq!(spec.program, "kitty");
651    }
652
653    #[test]
654    fn macos_opens_terminal_app_in_the_directory() {
655        let none = installed(&[]);
656        let spec = macos_terminal(&env(None, None, &none), &dir(), None);
657        assert_eq!(spec.program, "open");
658        assert_eq!(spec.args, strings(&["-a", "Terminal", "/home/u/src"]));
659    }
660
661    #[test]
662    fn macos_terminal_variable_names_an_application() {
663        let none = installed(&[]);
664        let spec = macos_terminal(&env(Some("iTerm"), None, &none), &dir(), None);
665        assert_eq!(spec.program, "open");
666        assert_eq!(spec.args, strings(&["-a", "iTerm", "/home/u/src"]));
667    }
668
669    #[test]
670    fn macos_terminal_variable_on_path_is_driven_like_linux() {
671        let which = installed(&["kitty"]);
672        let run = strings(&["vim", "notes.txt"]);
673        let spec = macos_terminal(&env(Some("kitty"), None, &which), &dir(), Some(&run));
674        assert_eq!(spec.program, "kitty");
675        assert_eq!(
676            spec.args,
677            strings(&["--directory", "/home/u/src", "vim", "notes.txt"])
678        );
679    }
680
681    #[test]
682    fn macos_runs_a_command_through_terminal_app() {
683        let none = installed(&[]);
684        let run = strings(&["vim", "say \"hi\".txt"]);
685        let spec = macos_terminal(
686            &env(None, None, &none),
687            Path::new("/Users/u/it's here"),
688            Some(&run),
689        );
690        assert_eq!(spec.program, "osascript");
691        assert_eq!(
692            spec.args,
693            strings(&[
694                "-e",
695                r#"tell application "Terminal" to do script "cd '/Users/u/it'\\''s here' && 'vim' 'say \"hi\".txt'""#,
696                "-e",
697                r#"tell application "Terminal" to activate"#,
698            ])
699        );
700    }
701
702    #[test]
703    fn visual_wins_over_editor() {
704        let which = installed(&["code", "vim"]);
705        let spec = direct(
706            editor_command(&editor_env(Some("code -w"), Some("vim"), &which), &file()).unwrap(),
707        );
708        assert_eq!(spec.program, "code");
709        assert_eq!(spec.args, strings(&["-w", "/home/u/a.txt"]));
710    }
711
712    #[test]
713    fn editor_is_used_when_visual_is_unset_or_blank() {
714        let which = installed(&["kate"]);
715        for visual in [None, Some(""), Some("   ")] {
716            let spec =
717                direct(editor_command(&editor_env(visual, Some("kate"), &which), &file()).unwrap());
718            assert_eq!(spec.program, "kate");
719            assert_eq!(spec.args, strings(&["/home/u/a.txt"]));
720            assert_eq!(spec.cwd, PathBuf::from("/home/u"));
721        }
722    }
723
724    // Which terminal wraps the editor is decided per platform by
725    // `terminal_command`; these pin down the Linux/BSD choice. macOS and
726    // Windows always have a terminal, so the error case cannot happen there.
727    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
728    #[test]
729    fn terminal_editor_runs_in_a_terminal_in_the_files_directory() {
730        let which = installed(&["vim", "konsole"]);
731        let spec =
732            in_terminal(editor_command(&editor_env(None, Some("vim"), &which), &file()).unwrap());
733        assert_eq!(spec.program, "konsole");
734        assert_eq!(
735            spec.args,
736            strings(&["--workdir", "/home/u", "-e", "vim", "/home/u/a.txt"])
737        );
738        assert_eq!(spec.cwd, PathBuf::from("/home/u"));
739    }
740
741    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
742    #[test]
743    fn terminal_editor_keeps_its_arguments() {
744        let which = installed(&["nvim", "konsole"]);
745        let spec = in_terminal(
746            editor_command(&editor_env(None, Some("nvim -p"), &which), &file()).unwrap(),
747        );
748        assert_eq!(
749            spec.args,
750            strings(&["--workdir", "/home/u", "-e", "nvim", "-p", "/home/u/a.txt"])
751        );
752    }
753
754    #[test]
755    fn emacs_is_direct_unless_told_to_use_the_terminal() {
756        let which = installed(&["emacs", "emacsclient", "konsole"]);
757        let launch = |value| editor_command(&editor_env(Some(value), None, &which), &file());
758        assert!(matches!(launch("emacs").unwrap(), EditorLaunch::Direct(_)));
759        assert!(matches!(
760            launch("emacs -nw").unwrap(),
761            EditorLaunch::InTerminal(_)
762        ));
763        assert!(matches!(
764            launch("emacsclient -c").unwrap(),
765            EditorLaunch::Direct(_)
766        ));
767        assert!(matches!(
768            launch("emacsclient --tty").unwrap(),
769            EditorLaunch::InTerminal(_)
770        ));
771    }
772
773    #[test]
774    fn editor_given_as_a_path_is_classified_by_its_name() {
775        let which = installed(&["/usr/bin/nano", "konsole"]);
776        assert!(matches!(
777            editor_command(&editor_env(None, Some("/usr/bin/nano"), &which), &file()).unwrap(),
778            EditorLaunch::InTerminal(_)
779        ));
780    }
781
782    #[test]
783    fn no_editor_configured_falls_back_to_the_default_app() {
784        let which = installed(&["vim"]);
785        assert_eq!(
786            editor_command(&editor_env(None, None, &which), &file()),
787            Ok(EditorLaunch::DefaultApp)
788        );
789    }
790
791    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
792    #[test]
793    fn terminal_editor_without_a_terminal_is_an_error() {
794        let which = installed(&["nano"]);
795        assert_eq!(
796            editor_command(&editor_env(None, Some("nano"), &which), &file()),
797            Err(LaunchError::NoTerminalForEditor("nano".to_string()))
798        );
799    }
800
801    #[test]
802    fn missing_editor_is_an_error() {
803        let which = installed(&["konsole"]);
804        assert_eq!(
805            editor_command(&editor_env(None, Some("nonexistent"), &which), &file()),
806            Err(LaunchError::EditorNotFound("nonexistent".to_string()))
807        );
808    }
809
810    #[test]
811    fn path_with_spaces_stays_one_argument() {
812        let which = installed(&["kate"]);
813        let spec = direct(
814            editor_command(
815                &editor_env(None, Some("kate"), &which),
816                Path::new("/home/u/my notes/a b.txt"),
817            )
818            .unwrap(),
819        );
820        assert_eq!(spec.args, strings(&["/home/u/my notes/a b.txt"]));
821        assert_eq!(spec.cwd, PathBuf::from("/home/u/my notes"));
822    }
823
824    #[test]
825    fn shell_quote_survives_single_quotes() {
826        assert_eq!(shell_quote("a'b"), r#"'a'\''b'"#);
827        assert_eq!(shell_quote("plain"), "'plain'");
828    }
829
830    #[test]
831    fn windows_prefers_windows_terminal_over_cmd() {
832        let which = installed(&["wt"]);
833        let spec = windows_terminal(&env(None, None, &which), &dir(), None);
834        assert_eq!(spec.program, "wt");
835        assert_eq!(spec.args, strings(&["-d", "/home/u/src"]));
836
837        let none = installed(&[]);
838        let spec = windows_terminal(&env(None, None, &none), &dir(), None);
839        assert_eq!(spec.program, "cmd");
840        assert_eq!(spec.args, strings(&["/K", "cd", "/d", "/home/u/src"]));
841
842        let spec = windows_terminal(
843            &env(None, None, &none),
844            &dir(),
845            Some(&strings(&["notepad"])),
846        );
847        assert_eq!(spec.args, strings(&["/K", "notepad"]));
848    }
849}