feat: :cd - changes to the previous working directory (#12194)

Co-authored-by: Michael Davis <mcarsondavis@gmail.com>
This commit is contained in:
Nikita Revenco 2024-12-05 23:40:37 +00:00 committed by GitHub
parent a6f80c5bd9
commit 93deb1f6ae
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 13 additions and 4 deletions

View File

@ -7,6 +7,7 @@
use once_cell::sync::Lazy; 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); static CWD: RwLock<Option<PathBuf>> = RwLock::new(None);
// Get the current working directory. // Get the current working directory.
@ -36,12 +37,12 @@ pub fn current_working_dir() -> PathBuf {
cwd 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); let path = crate::path::canonicalize(path);
std::env::set_current_dir(&path)?; std::env::set_current_dir(&path)?;
let mut cwd = CWD.write().unwrap(); 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 { pub fn env_var_is_set(env_var_name: &str) -> bool {

View File

@ -1091,6 +1091,11 @@ fn change_current_directory(
} }
let dir = match args.first() { let dir = match args.first() {
Some(Cow::Borrowed("-")) => cx
.editor
.last_cwd
.clone()
.ok_or(anyhow!("No previous working directory"))?,
Some(input_path) => { Some(input_path) => {
helix_stdx::path::expand_tilde(Path::new(input_path.as_ref()).to_owned()) helix_stdx::path::expand_tilde(Path::new(input_path.as_ref()).to_owned())
.deref() .deref()
@ -1099,12 +1104,13 @@ fn change_current_directory(
None => home_dir()?.as_path().to_owned(), 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!( cx.editor.set_status(format!(
"Current working directory is now {}", "Current working directory is now {}",
helix_stdx::env::current_working_dir().display() helix_stdx::env::current_working_dir().display()
)); ));
Ok(()) Ok(())
} }

View File

@ -1073,6 +1073,7 @@ pub struct Editor {
redraw_timer: Pin<Box<Sleep>>, redraw_timer: Pin<Box<Sleep>>,
last_motion: Option<Motion>, last_motion: Option<Motion>,
pub last_completion: Option<CompleteAction>, pub last_completion: Option<CompleteAction>,
pub last_cwd: Option<PathBuf>,
pub exit_code: i32, pub exit_code: i32,
@ -1206,6 +1207,7 @@ pub fn new(
redraw_timer: Box::pin(sleep(Duration::MAX)), redraw_timer: Box::pin(sleep(Duration::MAX)),
last_motion: None, last_motion: None,
last_completion: None, last_completion: None,
last_cwd: None,
config, config,
auto_pairs, auto_pairs,
exit_code: 0, exit_code: 0,