Skip to main content

oe/
main.rs

1//! Open files (optionally at line:col) in existing Nvim / Helix pane.
2//!
3//! # Errors
4//! - Argument parsing, pane discovery, or command execution fails.
5
6use core::str::FromStr;
7
8use rootcause::prelude::ResultExt;
9use rootcause::report;
10use ytil_editor::Editor;
11use ytil_editor::FileToOpen;
12use ytil_sys::cli::Args;
13
14/// Open files (optionally at line:col) in existing Nvim / Helix pane.
15#[ytil_sys::main]
16fn main() -> rootcause::Result<()> {
17    let enriched_path_env = get_enriched_path_env()?;
18    let args = ytil_sys::cli::get();
19
20    if args.has_help() {
21        println!("{}", include_str!("../help.txt"));
22        return Ok(());
23    }
24
25    let Some(editor) = args.first().map(|x| Editor::from_str(x)).transpose()? else {
26        return Err(report!("missing editor arg")).attach_with(|| format!("args={args:#?}"));
27    };
28
29    let Some(file_to_open) = args.get(1) else {
30        return Err(report!("missing file arg")).attach_with(|| format!("args={args:#?}"));
31    };
32
33    let pane_id = match args.get(2) {
34        Some(x) => x.parse()?,
35        None => ytil_wezterm::get_current_pane_id()?,
36    };
37
38    let panes = ytil_wezterm::get_all_panes(&[enriched_path_env.by_ref()])?;
39
40    let file_to_open = FileToOpen::try_from((file_to_open.as_str(), pane_id, panes.as_slice()))?;
41
42    let editor_pane_id =
43        ytil_wezterm::get_sibling_pane_with_titles(&panes, pane_id, editor.pane_titles()).map(|x| x.pane_id)?;
44
45    let open_file_cmd = editor.open_file_cmd(&file_to_open);
46    let escaped_open_file_cmd = escape_single_quotes(&open_file_cmd);
47
48    ytil_cmd::silent_cmd("sh")
49        .args([
50            "-c",
51            &format!(
52                "{} && {} && {} && {}",
53                // `wezterm cli send-text $'\e'` sends the "ESC" to `WezTerm` to exit from insert mode
54                // https://github.com/wez/wezterm/discussions/3945
55                ytil_wezterm::send_text_to_pane_cmd(r"$'\e'", editor_pane_id),
56                ytil_wezterm::send_text_to_pane_cmd(&format!("'{escaped_open_file_cmd}'"), editor_pane_id),
57                ytil_wezterm::submit_pane_cmd(editor_pane_id),
58                ytil_wezterm::activate_pane_cmd(editor_pane_id),
59            ),
60        ])
61        .envs(std::iter::once(enriched_path_env.by_ref()))
62        .spawn()?;
63
64    Ok(())
65}
66
67/// Wrapper for environment variables.
68struct Env {
69    /// The name of the environment variable (static string).
70    name: &'static str,
71    /// The value of the environment variable (dynamically constructed string).
72    value: String,
73}
74
75impl Env {
76    /// Returns environment variable as tuple.
77    pub fn by_ref(&self) -> (&'static str, &str) {
78        (self.name, &self.value)
79    }
80}
81
82/// Creates enriched PATH for `WezTerm` integration.
83///
84/// # Errors
85/// - A required environment variable is missing or invalid Unicode.
86fn get_enriched_path_env() -> rootcause::Result<Env> {
87    let enriched_path = [
88        &std::env::var("PATH").unwrap_or_else(|_| String::new()),
89        "/opt/homebrew/bin",
90        &ytil_sys::dir::build_home_path(&[".local", "bin"])?.to_string_lossy(),
91    ]
92    .join(":");
93
94    Ok(Env {
95        name: "PATH",
96        value: enriched_path,
97    })
98}
99
100/// Escape single quotes for safe embedding in shell single-quoted strings.
101///
102/// Replaces each `'` with `'\''` (end quote, escaped quote, begin quote).
103fn escape_single_quotes(s: &str) -> String {
104    s.replace('\'', "'\\''")
105}
106
107#[cfg(test)]
108mod tests {
109    use rstest::rstest;
110
111    use super::*;
112
113    #[rstest]
114    #[case::no_quotes("hello world", "hello world")]
115    #[case::single_quote("it's here", "it'\\''s here")]
116    #[case::multiple_quotes("a'b'c", "a'\\''b'\\''c")]
117    #[case::only_quote("'", "'\\''")]
118    #[case::empty("", "")]
119    fn test_escape_single_quotes_produces_expected_output(#[case] input: &str, #[case] expected: &str) {
120        pretty_assertions::assert_eq!(escape_single_quotes(input), expected);
121    }
122}