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 4 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
108 changes: 106 additions & 2 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,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 @@ -292,7 +292,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_ignore, "Pipe selections into shell command, ignoring command output",
shell_insert, "Insert output of shell command before each selection",
shell_append, "Append output of shell command after each selection",
shell_filter, "Filter selections with shell predicate",
suspend, "Suspend",
);
}

Expand Down Expand Up @@ -3896,6 +3901,105 @@ 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_ignore(cx: &mut Context) {
shell(cx, "pipe:", true, ShellBehavior::None);
}

fn shell_insert(cx: &mut Context) {
shell(cx, "command:", false, ShellBehavior::Insert);
}

fn shell_append(cx: &mut Context) {
shell(cx, "command:", false, ShellBehavior::Append);
}

fn shell_filter(cx: &mut Context) {
shell(cx, "filter:", true, ShellBehavior::Filter);
Omnikar marked this conversation as resolved.
Show resolved Hide resolved
}

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};
let shell = Option::<Vec<_>>::None; // this should come from config, but can't currently
let shell = match shell {
Some(v) if !v.is_empty() => v,
_ => {
if cfg!(windows) {
vec!["cmd".to_owned(), "/C".to_owned()]
} else {
vec!["sh".to_owned(), "-c".to_owned()]
}
}
};
let prompt = Prompt::new(
prompt.to_owned(),
Some('!'),
Omnikar marked this conversation as resolved.
Show resolved Hide resolved
|_input: &str| Vec::new(),
move |cx: &mut compositor::Context, input: &str, event: PromptEvent| {
if event == PromptEvent::Validate {
let (view, doc) = current!(cx.editor);
let selection = doc.selection(view.id);
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::null())
.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();
}

if behavior != ShellBehavior::Filter {
Omnikar marked this conversation as resolved.
Show resolved Hide resolved
let output = process.wait_with_output().unwrap().stdout;
let tendril = Tendril::try_from_byte_slice(&output).unwrap();
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 output = process.wait_with_output().unwrap().status.success();
(
range.from(),
if output { range.from() } else { range.to() },
None,
)
}
});

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

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
1 change: 1 addition & 0 deletions helix-term/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::keymap::Keymaps;
#[derive(Debug, Default, Clone, PartialEq, Deserialize)]
pub struct Config {
pub theme: Option<String>,
pub shell: Option<Vec<String>>,
pickfire marked this conversation as resolved.
Show resolved Hide resolved
#[serde(default)]
pub lsp: LspConfig,
#[serde(default)]
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 @@ -502,6 +502,11 @@ impl Default for Keymaps {
},

"\"" => select_register,
"|" => shell_pipe,
"A-|" => shell_pipe_ignore,
"!" => shell_insert,
"A-!" => shell_append,
"$" => shell_filter,
pickfire marked this conversation as resolved.
Show resolved Hide resolved
"C-z" => suspend,
});
// TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether
Expand Down