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

Shell commands #547

Merged
merged 20 commits into from
Aug 31, 2021
Merged
Show file tree
Hide file tree
Changes from 13 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
118 changes: 116 additions & 2 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ pub struct Command {
}

macro_rules! commands {
( $($name:ident, $doc:literal),* ) => {
( $($name:ident, $doc:literal,)* ) => {
Omnikar marked this conversation as resolved.
Show resolved Hide resolved
$(
#[allow(non_upper_case_globals)]
pub const $name: Self = Self {
Expand Down Expand Up @@ -302,7 +302,12 @@ impl Command {
surround_delete, "Surround delete",
select_textobject_around, "Select around object",
select_textobject_inner, "Select inside object",
suspend, "Suspend"
shell_pipe, "Pipe selections through shell command",
shell_pipe_to, "Pipe selections into shell command, ignoring command output",
shell_insert_output, "Insert output of shell command before each selection",
shell_append_output, "Append output of shell command after each selection",
shell_keep_pipe, "Filter selections with shell predicate",
suspend, "Suspend",
);
}

Expand Down Expand Up @@ -4238,6 +4243,115 @@ fn surround_delete(cx: &mut Context) {
})
}

#[derive(Eq, PartialEq)]
enum ShellBehavior {
Replace,
Insert,
Append,
Filter,
None,
}

fn shell_pipe(cx: &mut Context) {
shell(cx, "pipe:", true, ShellBehavior::Replace);
}

fn shell_pipe_to(cx: &mut Context) {
shell(cx, "pipe-to:", true, ShellBehavior::None);
}

fn shell_insert_output(cx: &mut Context) {
shell(cx, "insert-output:", false, ShellBehavior::Insert);
}

fn shell_append_output(cx: &mut Context) {
shell(cx, "append-output:", false, ShellBehavior::Append);
}

fn shell_keep_pipe(cx: &mut Context) {
shell(cx, "keep-pipe:", true, ShellBehavior::Filter);
}

fn shell(cx: &mut Context, prompt: &str, pipe: bool, behavior: ShellBehavior) {
Omnikar marked this conversation as resolved.
Show resolved Hide resolved
use std::io::Write;
use std::process::{Command, Stdio};
if cx.editor.config.shell.is_empty() {
return;
}
let prompt = Prompt::new(
prompt.to_owned(),
Some('|'),
|_input: &str| Vec::new(),
move |cx: &mut compositor::Context, input: &str, event: PromptEvent| {
let shell = &cx.editor.config.shell;
if event == PromptEvent::Validate {
let (view, doc) = current!(cx.editor);
let selection = doc.selection(view.id);
let mut error_occurred = false;
let transaction =
Transaction::change_by_selection(doc.text(), selection, |range| {
let mut process = Command::new(&shell[0])
.args(&shell[1..])
.arg(input)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
if pipe {
let stdin = process.stdin.as_mut().unwrap();
let fragment = range.fragment(doc.text().slice(..));
stdin.write_all(fragment.as_bytes()).unwrap();
}

let output = process.wait_with_output().unwrap();
if behavior != ShellBehavior::Filter {
Omnikar marked this conversation as resolved.
Show resolved Hide resolved
if !output.status.success() {
let stderr = output.stderr;
if !stderr.is_empty() {
log::error!(
"Shell error: {}",
String::from_utf8_lossy(&stderr)
);
}
error_occurred = true;
return (0, 0, None);
}
let stdout = output.stdout;
let tendril = Tendril::try_from_byte_slice(&stdout).unwrap();
Omnikar marked this conversation as resolved.
Show resolved Hide resolved
let (from, to) = match behavior {
ShellBehavior::Replace => (range.from(), range.to()),
ShellBehavior::Insert => (range.from(), range.from()),
ShellBehavior::Append => (range.to(), range.to()),
_ => (range.from(), range.from()),
};
(from, to, Some(tendril))
} else {
// if the process exits successfully, keep the selection, otherwise delete it.
let keep = output.status.success();
(
range.from(),
if keep { range.from() } else { range.to() },
None,
)
}
});

if behavior != ShellBehavior::None {
doc.apply(&transaction, view.id);
doc.append_changes_to_history(view.id);
}

if error_occurred {
cx.editor.set_error("Command failed".to_owned());
}
}
},
);

cx.push_layer(Box::new(prompt));
}

fn suspend(_cx: &mut Context) {
#[cfg(not(windows))]
signal_hook::low_level::raise(signal_hook::consts::signal::SIGTSTP).unwrap();
Expand Down
5 changes: 5 additions & 0 deletions helix-term/src/keymap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,11 @@ impl Default for Keymaps {
},

"\"" => select_register,
"|" => shell_pipe,
"A-|" => shell_pipe_to,
"!" => shell_insert_output,
"A-!" => shell_append_output,
"$" => shell_keep_pipe,
"C-z" => suspend,
});
let mut select = normal.clone();
Expand Down
7 changes: 7 additions & 0 deletions helix-view/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub struct Config {
pub scroll_lines: isize,
/// Mouse support. Defaults to true.
pub mouse: bool,
/// Shell to use for shell commands. Defaults to ["cmd", "/C"] on Windows and ["sh", "-c"] otherwise.
pub shell: Vec<String>,
/// Line number mode.
pub line_number: LineNumber,
/// Middle click paste support. Defaults to true
Expand All @@ -55,6 +57,11 @@ impl Default for Config {
scrolloff: 5,
scroll_lines: 3,
mouse: true,
shell: if cfg!(windows) {
vec!["cmd".to_owned(), "/C".to_owned()]
} else {
vec!["sh".to_owned(), "-c".to_owned()]
},
line_number: LineNumber::Absolute,
middle_click_paste: true,
}
Expand Down