From 93deb1f6ae891c2fad144c3807515ad3b13004d6 Mon Sep 17 00:00:00 2001 From: Nikita Revenco <154856872+NikitaRevenco@users.noreply.github.com> Date: Thu, 5 Dec 2024 23:40:37 +0000 Subject: [PATCH] feat: `:cd -` changes to the previous working directory (#12194) Co-authored-by: Michael Davis --- helix-stdx/src/env.rs | 7 ++++--- helix-term/src/commands/typed.rs | 8 +++++++- helix-view/src/editor.rs | 2 ++ 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/helix-stdx/src/env.rs b/helix-stdx/src/env.rs index d29a98fde..6e14c7a87 100644 --- a/helix-stdx/src/env.rs +++ b/helix-stdx/src/env.rs @@ -7,6 +7,7 @@ use once_cell::sync::Lazy; +// We keep the CWD as a static so that we can access it in places where we don't have access to the Editor static CWD: RwLock> = RwLock::new(None); // Get the current working directory. @@ -36,12 +37,12 @@ pub fn current_working_dir() -> PathBuf { cwd } -pub fn set_current_working_dir(path: impl AsRef) -> std::io::Result<()> { +pub fn set_current_working_dir(path: impl AsRef) -> std::io::Result> { let path = crate::path::canonicalize(path); std::env::set_current_dir(&path)?; let mut cwd = CWD.write().unwrap(); - *cwd = Some(path); - Ok(()) + + Ok(cwd.replace(path)) } pub fn env_var_is_set(env_var_name: &str) -> bool { diff --git a/helix-term/src/commands/typed.rs b/helix-term/src/commands/typed.rs index e6ec8b571..25288ad29 100644 --- a/helix-term/src/commands/typed.rs +++ b/helix-term/src/commands/typed.rs @@ -1091,6 +1091,11 @@ fn change_current_directory( } let dir = match args.first() { + Some(Cow::Borrowed("-")) => cx + .editor + .last_cwd + .clone() + .ok_or(anyhow!("No previous working directory"))?, Some(input_path) => { helix_stdx::path::expand_tilde(Path::new(input_path.as_ref()).to_owned()) .deref() @@ -1099,12 +1104,13 @@ fn change_current_directory( None => home_dir()?.as_path().to_owned(), }; - helix_stdx::env::set_current_working_dir(dir)?; + cx.editor.last_cwd = helix_stdx::env::set_current_working_dir(dir)?; cx.editor.set_status(format!( "Current working directory is now {}", helix_stdx::env::current_working_dir().display() )); + Ok(()) } diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs index 174190e5d..aa9a11533 100644 --- a/helix-view/src/editor.rs +++ b/helix-view/src/editor.rs @@ -1073,6 +1073,7 @@ pub struct Editor { redraw_timer: Pin>, last_motion: Option, pub last_completion: Option, + pub last_cwd: Option, pub exit_code: i32, @@ -1206,6 +1207,7 @@ pub fn new( redraw_timer: Box::pin(sleep(Duration::MAX)), last_motion: None, last_completion: None, + last_cwd: None, config, auto_pairs, exit_code: 0,