Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to use $file and $pwd in shell commands and formatter args #3642

Closed
Closed
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use helix_view::{
clipboard::ClipboardType,
document::{FormatterError, Mode, SCRATCH_BUFFER_NAME},
editor::{Action, Motion},
env::inject_environment,
info::Info,
input::KeyEvent,
keyboard::KeyCode,
Expand Down Expand Up @@ -4546,7 +4547,8 @@ fn shell_keep_pipe(cx: &mut Context) {

for (i, range) in selection.ranges().iter().enumerate() {
let fragment = range.slice(text);
let (_output, success) = match shell_impl(shell, input, Some(fragment)) {
let input = input.split(' ').map(Cow::from).collect::<Vec<_>>();
let (_output, success) = match shell_impl(doc, shell, &input, Some(fragment)) {
Ok(result) => result,
Err(err) => {
cx.editor.set_error(err.to_string());
Expand Down Expand Up @@ -4575,14 +4577,17 @@ fn shell_keep_pipe(cx: &mut Context) {
}

fn shell_impl(
doc: &Document,
shell: &[String],
cmd: &str,
args: &[Cow<str>],
input: Option<RopeSlice>,
) -> anyhow::Result<(Tendril, bool)> {
use std::io::Write;
use std::process::{Command, Stdio};
ensure!(!shell.is_empty(), "No shell set");

let cmd = inject_environment(args.iter(), doc).join(" ");

let mut process = Command::new(&shell[0]);
process
.args(&shell[1..])
Expand Down Expand Up @@ -4629,7 +4634,7 @@ fn shell_impl(
Ok((tendril, output.status.success()))
}

fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) {
fn shell(cx: &mut compositor::Context, cmd: &[Cow<str>], behavior: &ShellBehavior) {
let pipe = match behavior {
ShellBehavior::Replace | ShellBehavior::Ignore => true,
ShellBehavior::Insert | ShellBehavior::Append => false,
Expand All @@ -4645,7 +4650,7 @@ fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) {

for range in selection.ranges() {
let fragment = range.slice(text);
let (output, success) = match shell_impl(shell, cmd, pipe.then(|| fragment)) {
let (output, success) = match shell_impl(doc, shell, cmd, pipe.then(|| fragment)) {
Ok(result) => result,
Err(err) => {
cx.editor.set_error(err.to_string());
Expand Down Expand Up @@ -4692,7 +4697,8 @@ fn shell_prompt(cx: &mut Context, prompt: Cow<'static, str>, behavior: ShellBeha
return;
}

shell(cx, input, &behavior);
let input = input.split(' ').map(Cow::from).collect::<Vec<_>>();
shell(cx, &input, &behavior);
},
);
}
Expand Down
11 changes: 6 additions & 5 deletions helix-term/src/commands/typed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1448,7 +1448,7 @@ fn append_output(
}

ensure!(!args.is_empty(), "Shell command required");
shell(cx, &args.join(" "), &ShellBehavior::Append);
shell(cx, args, &ShellBehavior::Append);
Ok(())
}

Expand All @@ -1462,7 +1462,7 @@ fn insert_output(
}

ensure!(!args.is_empty(), "Shell command required");
shell(cx, &args.join(" "), &ShellBehavior::Insert);
shell(cx, args, &ShellBehavior::Insert);
Ok(())
}

Expand All @@ -1472,7 +1472,7 @@ fn pipe(cx: &mut compositor::Context, args: &[Cow<str>], event: PromptEvent) ->
}

ensure!(!args.is_empty(), "Shell command required");
shell(cx, &args.join(" "), &ShellBehavior::Replace);
shell(cx, args, &ShellBehavior::Replace);
Ok(())
}

Expand All @@ -1484,9 +1484,10 @@ fn run_shell_command(
if event != PromptEvent::Validate {
return Ok(());
}

let shell = &cx.editor.config().shell;
let (output, success) = shell_impl(shell, &args.join(" "), None)?;
let doc = doc!(cx.editor);

let (output, success) = shell_impl(doc, shell, args, None)?;
if success {
cx.editor.set_status("Command succeed");
} else {
Expand Down
3 changes: 2 additions & 1 deletion helix-view/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use helix_core::{
DEFAULT_LINE_ENDING,
};

use crate::env::inject_environment;
use crate::{DocumentId, Editor, ViewId};

/// 8kB of buffer space for encoding and decoding `Rope`s.
Expand Down Expand Up @@ -412,7 +413,7 @@ impl Document {
let text = self.text().clone();
let mut process = tokio::process::Command::new(&formatter.command);
process
.args(&formatter.args)
.args(inject_environment(formatter.args.iter(), self))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
Expand Down
25 changes: 25 additions & 0 deletions helix-view/src/env.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use std::fmt::Display;

use crate::Document;

pub fn inject_environment<T>(strs: T, doc: &Document) -> Vec<String>
AlexanderBrevig marked this conversation as resolved.
Show resolved Hide resolved
where
T: Iterator,
<T as Iterator>::Item: Display,
{
let path = doc.path().and_then(|p| p.to_str()).unwrap_or_else(|| {
log::error!("No $path found for document: {:?}", doc.url());
"ENV:NO_PATH"
});
AlexanderBrevig marked this conversation as resolved.
Show resolved Hide resolved
let pwd = std::env::current_dir()
.unwrap_or_default()
.into_os_string()
.into_string()
.unwrap_or_else(|err| {
log::error!("No $pwd found for: {:?}", err);
"ENV:NO_PATH".to_string()
});

strs.map(|s| s.to_string().replace("$file", path).replace("$pwd", &pwd))
.collect()
}
4 changes: 3 additions & 1 deletion helix-view/src/handlers/dap.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::editor::{Action, Breakpoint};
use crate::env::inject_environment;
use crate::{align_view, Align, Editor};
use helix_core::Selection;
use helix_dap::{self as dap, Client, Payload, Request, ThreadId};
Expand Down Expand Up @@ -300,8 +301,9 @@ impl Editor {
None => return false,
};

let doc = doc!(self);
let process = match std::process::Command::new(config.command)
.args(config.args)
.args(inject_environment(config.args.iter(), doc))
.arg(arguments.args.join(" "))
.spawn()
{
Expand Down
1 change: 1 addition & 0 deletions helix-view/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod macros;
pub mod clipboard;
pub mod document;
pub mod editor;
pub mod env;
pub mod graphics;
pub mod gutter;
pub mod handlers {
Expand Down