From 166b879db89ded93e0d22749e3214635867fe297 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jes=C3=BAs=20R?= Date: Wed, 5 Apr 2023 19:46:34 -0600 Subject: [PATCH] add cmd: Change CWD to current buffer's directory --- helix-term/src/commands.rs | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index b55f1ab72bd7..5d122cdced40 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -4,6 +4,7 @@ pub(crate) mod typed; pub use dap::*; use helix_vcs::Hunk; +use log::warn; pub use lsp::*; use tokio::sync::oneshot; use tui::widgets::Row; @@ -472,6 +473,7 @@ impl MappableCommand { record_macro, "Record macro", replay_macro, "Replay macro", command_palette, "Open command palette", + change_current_directory_to_buffer_directory, "Change current directory to current buffer's directory", ); } @@ -5379,3 +5381,45 @@ fn replay_macro(cx: &mut Context) { cx.editor.macro_replaying.pop(); })); } + +fn change_current_directory_to_buffer_directory(cx: &mut Context) { + let buff_dir = doc!(cx.editor) + .path() + .and_then(|path| path.parent().map(|path| path.to_path_buf())); + + let buff_dir = match buff_dir { + Some(path) => path, + None => { + cx.editor.set_error("Current buffer has no path or parent"); + + return; + } + }; + + match std::env::current_dir() { + Ok(cwd) => { + if buff_dir.display().to_string() == cwd.display().to_string() { + cx.editor.set_status(format!( + "Current working directory is already {}", + cwd.display() + )); + + return; + } + } + Err(e) => warn!("Couldn't get the current working directory: {e})"), + } + + if let Err(e) = std::env::set_current_dir(&buff_dir) { + cx.editor.set_error(format!( + "Couldn't change the current working directory: {e}" + )); + + return; + } + + cx.editor.set_status(format!( + "Current working directory is now {}", + buff_dir.display() + )); +}