Skip to content

Commit

Permalink
feat: :cd - changes to the previous working directory (#12194)
Browse files Browse the repository at this point in the history
Co-authored-by: Michael Davis <[email protected]>
  • Loading branch information
NikitaRevenco and the-mikedavis authored Dec 5, 2024
1 parent a6f80c5 commit 93deb1f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
7 changes: 4 additions & 3 deletions helix-stdx/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::{

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<Option<PathBuf>> = RwLock::new(None);

// Get the current working directory.
Expand Down Expand Up @@ -36,12 +37,12 @@ pub fn current_working_dir() -> PathBuf {
cwd
}

pub fn set_current_working_dir(path: impl AsRef<Path>) -> std::io::Result<()> {
pub fn set_current_working_dir(path: impl AsRef<Path>) -> std::io::Result<Option<PathBuf>> {
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 {
Expand Down
8 changes: 7 additions & 1 deletion helix-term/src/commands/typed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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(())
}

Expand Down
2 changes: 2 additions & 0 deletions helix-view/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1073,6 +1073,7 @@ pub struct Editor {
redraw_timer: Pin<Box<Sleep>>,
last_motion: Option<Motion>,
pub last_completion: Option<CompleteAction>,
pub last_cwd: Option<PathBuf>,

pub exit_code: i32,

Expand Down Expand Up @@ -1206,6 +1207,7 @@ impl Editor {
redraw_timer: Box::pin(sleep(Duration::MAX)),
last_motion: None,
last_completion: None,
last_cwd: None,
config,
auto_pairs,
exit_code: 0,
Expand Down

0 comments on commit 93deb1f

Please sign in to comment.