diff --git a/book/src/commands.md b/book/src/commands.md index ee507276b51f..53cd4bcde629 100644 --- a/book/src/commands.md +++ b/book/src/commands.md @@ -1,6 +1,7 @@ # Commands - [Typable commands](#typable-commands) + - [Using variables](#using-variables-in-typable-commands) - [Static commands](#static-commands) ## Typable commands @@ -9,6 +10,34 @@ Typable commands are used from command mode and may take arguments. Command mode {{#include ./generated/typable-cmd.md}} +### Using variables in typable commands + +Helix provides several variables that can be used when typing commands or creating custom shortcuts. These variables are listed below: + +| Variable | Description | +| --- | --- | +| `%{basename}` or `%{b}` | The name and extension of the currently focused file. | +| `%{dirname}` or `%{d}` | The absolute path of the parent directory of the currently focused file. | +| `%{cwd}` | The absolute path of the current working directory of Helix. | +| `%{repo}` | The absolute path of the VCS repository helix is opened in. Fallback to `cwd` if not inside a VCS repository| +| `%{filename}` or `%{f}` | The absolute path of the currently focused file. | +| `%{filename:rel}` | The relative path of the file according to `cwd` (will give absolute path if the file is not a child of the current working directory) | +| `%{filename:repo_rel}` | The relative path of the file according to `repo` (will give absolute path if the file is not a child of the VCS directory or the cwd) | +| `%{ext}` | The extension of the current file | +| `%{lang}` | The language of the current file | +| `%{linenumber}` | The line number where the primary cursor is positioned. | +| `%{cursorcolumn}` | The position of the primary cursor inside the current line. | +| `%{selection}` | The text selected by the primary cursor. | +| `%sh{cmd}` | Executes `cmd` with the default shell and returns the command output, if any. | + +#### Example + +```toml +[keys.normal] +# Print blame info for the line where the main cursor is. +C-b = ":echo %sh{git blame -L %{linenumber} %{filename}}" +``` + ## Static Commands Static commands take no arguments and can be bound to keys. Static commands can also be executed from the command picker (`?`). The built-in static commands are: diff --git a/book/src/generated/typable-cmd.md b/book/src/generated/typable-cmd.md index 80cebebe9383..2cb1a6ce193d 100644 --- a/book/src/generated/typable-cmd.md +++ b/book/src/generated/typable-cmd.md @@ -89,3 +89,4 @@ | `:yank-diagnostic` | Yank diagnostic(s) under primary cursor to register, or clipboard by default | | `:read`, `:r` | Load a file into buffer | | `:trim-trailing-whitespace`, `:trim` | Delete whitespace | +| `:echo` | Print the processed input to the editor status | diff --git a/helix-core/src/shellwords.rs b/helix-core/src/shellwords.rs index 9d873c366c99..ca761e0d7790 100644 --- a/helix-core/src/shellwords.rs +++ b/helix-core/src/shellwords.rs @@ -40,93 +40,120 @@ pub struct Shellwords<'a> { impl<'a> From<&'a str> for Shellwords<'a> { fn from(input: &'a str) -> Self { use State::*; - let mut state = Unquoted; let mut words = Vec::new(); let mut parts = Vec::new(); let mut escaped = String::with_capacity(input.len()); - + let mut inside_variable_expansion = false; + let mut nested_variable_expansion_count = 0; let mut part_start = 0; let mut unescaped_start = 0; let mut end = 0; for (i, c) in input.char_indices() { - state = match state { - OnWhitespace => match c { - '"' => { - end = i; - Dquoted + if c == '%' { + //%sh{this "should" be escaped} + if let Some(t) = input.get(i + 1..i + 3) { + if t == "sh" { + nested_variable_expansion_count += 1; + inside_variable_expansion = true; } - '\'' => { - end = i; - Quoted + } + //%{this "should" be escaped} + if let Some(t) = input.get(i + 1..i + 2) { + if t == "{" { + nested_variable_expansion_count += 1; + inside_variable_expansion = true; } - '\\' => { - if cfg!(unix) { - escaped.push_str(&input[unescaped_start..i]); - unescaped_start = i + 1; - UnquotedEscaped - } else { + } + } + if c == '}' { + nested_variable_expansion_count -= 1; + if nested_variable_expansion_count == 0 { + inside_variable_expansion = false; + } + } + + state = if !inside_variable_expansion { + match state { + OnWhitespace => match c { + '"' => { + end = i; + Dquoted + } + '\'' => { + end = i; + Quoted + } + '\\' => { + if cfg!(unix) { + escaped.push_str(&input[unescaped_start..i]); + unescaped_start = i + 1; + UnquotedEscaped + } else { + OnWhitespace + } + } + c if c.is_ascii_whitespace() => { + end = i; OnWhitespace } - } - c if c.is_ascii_whitespace() => { - end = i; - OnWhitespace - } - _ => Unquoted, - }, - Unquoted => match c { - '\\' => { - if cfg!(unix) { - escaped.push_str(&input[unescaped_start..i]); - unescaped_start = i + 1; - UnquotedEscaped - } else { - Unquoted + _ => Unquoted, + }, + Unquoted => match c { + '\\' => { + if cfg!(unix) { + escaped.push_str(&input[unescaped_start..i]); + unescaped_start = i + 1; + UnquotedEscaped + } else { + Unquoted + } } - } - c if c.is_ascii_whitespace() => { - end = i; - OnWhitespace - } - _ => Unquoted, - }, - UnquotedEscaped => Unquoted, - Quoted => match c { - '\\' => { - if cfg!(unix) { - escaped.push_str(&input[unescaped_start..i]); - unescaped_start = i + 1; - QuoteEscaped - } else { - Quoted + c if c.is_ascii_whitespace() => { + end = i; + OnWhitespace } - } - '\'' => { - end = i; - OnWhitespace - } - _ => Quoted, - }, - QuoteEscaped => Quoted, - Dquoted => match c { - '\\' => { - if cfg!(unix) { - escaped.push_str(&input[unescaped_start..i]); - unescaped_start = i + 1; - DquoteEscaped - } else { - Dquoted + _ => Unquoted, + }, + UnquotedEscaped => Unquoted, + Quoted => match c { + '\\' => { + if cfg!(unix) { + escaped.push_str(&input[unescaped_start..i]); + unescaped_start = i + 1; + QuoteEscaped + } else { + Quoted + } } - } - '"' => { - end = i; - OnWhitespace - } - _ => Dquoted, - }, - DquoteEscaped => Dquoted, + '\'' => { + end = i; + OnWhitespace + } + _ => Quoted, + }, + QuoteEscaped => Quoted, + Dquoted => match c { + '\\' => { + if cfg!(unix) { + escaped.push_str(&input[unescaped_start..i]); + unescaped_start = i + 1; + DquoteEscaped + } else { + Dquoted + } + } + '"' => { + end = i; + OnWhitespace + } + _ => Dquoted, + }, + DquoteEscaped => Dquoted, + } + } else { + state }; let c_len = c.len_utf8(); @@ -235,6 +262,38 @@ mod test { // TODO test is_owned and is_borrowed, once they get stabilized. assert_eq!(expected, result); } + #[test] + fn test_expansion() { + let input = r#"echo %{filename} %{linenumber}"#; + let shellwords = Shellwords::from(input); + let result = shellwords.words().to_vec(); + let expected = vec![ + Cow::from("echo"), + Cow::from("%{filename}"), + Cow::from("%{linenumber}"), + ]; + assert_eq!(expected, result); + + let input = r#"echo %{filename} 'world' %{something to 'escape}"#; + let shellwords = Shellwords::from(input); + let result = shellwords.words().to_vec(); + let expected = vec![ + Cow::from("echo"), + Cow::from("%{filename}"), + Cow::from("world"), + Cow::from("%{something to 'escape}"), + ]; + assert_eq!(expected, result); + let input = r#"echo %sh{%sh{%{filename}}} cool"#; + let shellwords = Shellwords::from(input); + let result = shellwords.words().to_vec(); + let expected = vec![ + Cow::from("echo"), + Cow::from("%sh{%sh{%{filename}}}"), + Cow::from("cool"), + ]; + assert_eq!(expected, result); + } #[test] #[cfg(unix)] diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index c09479d75687..f91ae481b9f2 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -243,13 +243,30 @@ impl MappableCommand { match &self { Self::Typable { name, args, doc: _ } => { let args: Vec> = args.iter().map(Cow::from).collect(); + let mut joined_args = args.join(" "); + let expanded_args = match args.len() { + 0 => vec![], + _ => { + if let Ok(expanded) = + cx.editor.expand_variable_in_string(&joined_args, true) + { + joined_args = expanded.to_string(); + joined_args.split(' ').map(Cow::from).collect() + } else { + args + } + } + }; if let Some(command) = typed::TYPABLE_COMMAND_MAP.get(name.as_str()) { let mut cx = compositor::Context { editor: cx.editor, jobs: cx.jobs, scroll: None, }; - if let Err(e) = (command.fun)(&mut cx, &args[..], PromptEvent::Validate) { + + if let Err(e) = + (command.fun)(&mut cx, &expanded_args[..], PromptEvent::Validate) + { cx.editor.set_error(format!("{}", e)); } } diff --git a/helix-term/src/commands/typed.rs b/helix-term/src/commands/typed.rs index a0892e1f2cc8..ef16e588bffd 100644 --- a/helix-term/src/commands/typed.rs +++ b/helix-term/src/commands/typed.rs @@ -2620,6 +2620,18 @@ fn trim_whitespace( Ok(()) } +fn echo(cx: &mut compositor::Context, args: &[Cow], event: PromptEvent) -> anyhow::Result<()> { + if event != PromptEvent::Validate { + return Ok(()); + } + + let args = args.join(" "); + + cx.editor.set_status(args); + + Ok(()) +} + pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[ TypableCommand { name: "quit", @@ -3247,7 +3259,13 @@ pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[ doc: "Delete trailing whitespace from the current selections", fun: trim_whitespace, signature: CommandSignature::none(), - + }, + TypableCommand { + name: "echo", + aliases: &[], + doc: "Print the processed input to the editor status", + fun: echo, + signature: CommandSignature::none() }, ]; @@ -3328,8 +3346,18 @@ pub(super) fn command_mode(cx: &mut Context) { // Handle typable commands if let Some(cmd) = typed::TYPABLE_COMMAND_MAP.get(parts[0]) { let shellwords = Shellwords::from(input); - let args = shellwords.words(); - + let words = shellwords.words().to_vec(); + let args = if event == PromptEvent::Validate { + match cx.editor.expand_variables_in_vec(&words, true) { + Ok(args) => args, + Err(e) => { + cx.editor.set_error(format!("{}", e)); + return; + } + } + } else { + words + }; if let Err(e) = (cmd.fun)(cx, &args[1..], event) { cx.editor.set_error(format!("{}", e)); } diff --git a/helix-term/src/ui/mod.rs b/helix-term/src/ui/mod.rs index 7fb41ff0c5a2..85cb375160c8 100644 --- a/helix-term/src/ui/mod.rs +++ b/helix-term/src/ui/mod.rs @@ -522,7 +522,13 @@ pub mod completers { use std::path::Path; let is_tilde = input == "~"; - let path = helix_stdx::path::expand_tilde(Path::new(input)); + let path = editor + .expand_variable_in_string(input, false) + .map_or(input.to_string(), |expanded_input| { + expanded_input.into_owned() + }); + + let path = helix_stdx::path::expand_tilde(Path::new(path.as_str())); let (dir, file_name) = if input.ends_with(std::path::MAIN_SEPARATOR) { (path, None) diff --git a/helix-term/tests/test/commands.rs b/helix-term/tests/test/commands.rs index 32badaa415fe..6116d7b9256c 100644 --- a/helix-term/tests/test/commands.rs +++ b/helix-term/tests/test/commands.rs @@ -4,6 +4,7 @@ use super::*; mod insert; mod movement; +mod variable_expansion; mod write; #[tokio::test(flavor = "multi_thread")] diff --git a/helix-term/tests/test/commands/variable_expansion.rs b/helix-term/tests/test/commands/variable_expansion.rs new file mode 100644 index 000000000000..61580d7e427a --- /dev/null +++ b/helix-term/tests/test/commands/variable_expansion.rs @@ -0,0 +1,183 @@ +use super::*; +use std::borrow::Cow; +#[tokio::test(flavor = "multi_thread")] +async fn test_variable_expansion() -> anyhow::Result<()> { + { + let mut app = AppBuilder::new().build()?; + + test_key_sequence( + &mut app, + Some(":echo %{filename}"), + Some(&|app| { + assert_eq!( + app.editor.get_status().unwrap().0, + helix_view::document::SCRATCH_BUFFER_NAME + ); + }), + false, + ) + .await?; + let mut app = AppBuilder::new().build()?; + + test_key_sequence( + &mut app, + Some(":echo %{basename}"), + Some(&|app| { + assert_eq!( + app.editor.get_status().unwrap().0, + helix_view::document::SCRATCH_BUFFER_NAME + ); + }), + false, + ) + .await?; + + let mut app = AppBuilder::new().build()?; + + test_key_sequence( + &mut app, + Some(":echo %{dirname}"), + Some(&|app| { + assert_eq!( + app.editor.get_status().unwrap().0, + helix_view::document::SCRATCH_BUFFER_NAME + ); + }), + false, + ) + .await?; + } + + { + let file = tempfile::NamedTempFile::new()?; + let mut app = AppBuilder::new().with_file(file.path(), None).build()?; + + test_key_sequence( + &mut app, + Some(":echo %{filename}"), + Some(&|app| { + assert_eq!( + app.editor.get_status().unwrap().0, + helix_stdx::path::canonicalize(file.path()) + .to_str() + .unwrap() + ); + }), + false, + ) + .await?; + + let mut app = AppBuilder::new().with_file(file.path(), None).build()?; + + test_key_sequence( + &mut app, + Some(":echo %{basename}"), + Some(&|app| { + assert_eq!( + app.editor.get_status().unwrap().0, + file.path().file_name().unwrap().to_str().unwrap() + ); + }), + false, + ) + .await?; + + let mut app = AppBuilder::new().with_file(file.path(), None).build()?; + + test_key_sequence( + &mut app, + Some(":echo %{dirname}"), + Some(&|app| { + assert_eq!( + app.editor.get_status().unwrap().0, + helix_stdx::path::canonicalize(file.path().parent().unwrap()) + .to_str() + .unwrap() + ); + }), + false, + ) + .await?; + } + + { + let file = tempfile::NamedTempFile::new()?; + let mut app = AppBuilder::new().with_file(file.path(), None).build()?; + test_key_sequence( + &mut app, + Some("ihelix%:echo %{selection}"), + Some(&|app| { + assert_eq!(app.editor.get_status().unwrap().0, "helix"); + }), + false, + ) + .await?; + } + + { + let file = tempfile::NamedTempFile::new()?; + let mut app = AppBuilder::new().with_file(file.path(), None).build()?; + test_key_sequence( + &mut app, + Some("ihelixhelixhelix:echo %{linenumber}"), + Some(&|app| { + assert_eq!(app.editor.get_status().unwrap().0, "4"); + }), + false, + ) + .await?; + + let mut app = AppBuilder::new().build()?; + + test_key_sequence( + &mut app, + Some(":echo %sh{echo %{filename}}"), + Some(&|app| { + assert_eq!( + app.editor.get_status().unwrap().0, + helix_view::document::SCRATCH_BUFFER_NAME + ); + }), + false, + ) + .await?; + let mut app = AppBuilder::new().build()?; + + test_key_sequence( + &mut app, + Some(":echo %sh{echo %{filename} %{linenumber}}"), + Some(&|app| { + assert_eq!( + app.editor.get_status().unwrap().0, + &Cow::from(format!( + "{} {}", + helix_view::document::SCRATCH_BUFFER_NAME, + 1 + )) + ); + }), + false, + ) + .await?; + let mut app = AppBuilder::new().build()?; + + test_key_sequence( + &mut app, + Some(":echo %sh{echo %{filename} %sh{echo %{filename}}}"), + Some(&|app| { + assert_eq!( + app.editor.get_status().unwrap().0, + &Cow::from(format!( + "{} {}", + helix_view::document::SCRATCH_BUFFER_NAME, + helix_view::document::SCRATCH_BUFFER_NAME + )) + ); + }), + false, + ) + .await?; + } + + Ok(()) +} diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs index 0727aeac94be..70210ac3676b 100644 --- a/helix-view/src/editor.rs +++ b/helix-view/src/editor.rs @@ -1,3 +1,5 @@ +mod variable_expansion; + use crate::{ annotations::diagnostics::{DiagnosticFilter, InlineDiagnosticsConfig}, clipboard::ClipboardProvider, diff --git a/helix-view/src/editor/variable_expansion.rs b/helix-view/src/editor/variable_expansion.rs new file mode 100644 index 000000000000..da6d1ae26cb9 --- /dev/null +++ b/helix-view/src/editor/variable_expansion.rs @@ -0,0 +1,210 @@ +use helix_core::coords_at_pos; + +use crate::Editor; +use std::borrow::Cow; + +impl Editor { + pub fn expand_variables_in_vec<'a>( + &self, + args: &'a Vec>, + expand_sh: bool, + ) -> anyhow::Result>> { + let mut output = Vec::with_capacity(args.len()); + for arg in args { + if let Ok(s) = self.expand_variable_in_string(arg, expand_sh) { + output.push(s); + } + } + + Ok(output) + } + pub fn expand_variable_in_string<'a>( + &self, + input: &'a str, + expand_sh: bool, + ) -> anyhow::Result> { + let (view, doc) = current_ref!(self); + let shell = &self.config().shell; + + let mut output: Option = None; + + let mut chars = input.char_indices(); + let mut last_push_end: usize = 0; + + while let Some((index, char)) = chars.next() { + if char == '%' { + if let Some((_, char)) = chars.next() { + if char == '{' { + for (end, char) in chars.by_ref() { + if char == '}' { + if output.is_none() { + output = Some(String::with_capacity(input.len())) + } + + if let Some(o) = output.as_mut() { + o.push_str(&input[last_push_end..index]); + last_push_end = end + 1; + + let value = match &input[index + 2..end] { + "basename" | "b" => doc + .path() + .and_then(|it| { + it.file_name().and_then(|it| it.to_str()) + }) + .unwrap_or(crate::document::SCRATCH_BUFFER_NAME) + .to_owned(), + "filename" | "f" => doc + .path() + .and_then(|it| it.to_str()) + .unwrap_or(crate::document::SCRATCH_BUFFER_NAME) + .to_owned(), + "filename:repo_rel" => { + // This will get repo root or cwd if not inside a git repo. + let workspace_path = helix_loader::find_workspace().0; + doc.path() + .and_then(|p| { + p.strip_prefix(workspace_path) + .unwrap_or(p) + .to_str() + }) + .unwrap_or(crate::document::SCRATCH_BUFFER_NAME) + .to_owned() + } + "filename:rel" => { + let cwd = helix_stdx::env::current_working_dir(); + doc.path() + .and_then(|p| { + p.strip_prefix(cwd).unwrap_or(p).to_str() + }) + .unwrap_or(crate::document::SCRATCH_BUFFER_NAME) + .to_owned() + } + "dirname" | "d" => doc + .path() + .and_then(|p| p.parent()) + .and_then(std::path::Path::to_str) + .unwrap_or(crate::document::SCRATCH_BUFFER_NAME) + .to_owned(), + "repo" => helix_loader::find_workspace() + .0 + .to_str() + .unwrap_or("") + .to_owned(), + "cwd" => helix_stdx::env::current_working_dir() + .to_str() + .unwrap() + .to_owned(), + "linenumber" => (doc + .selection(view.id) + .primary() + .cursor_line(doc.text().slice(..)) + + 1) + .to_string(), + "cursorcolumn" => (coords_at_pos( + doc.text().slice(..), + doc.selection(view.id) + .primary() + .cursor(doc.text().slice(..)), + ) + .col + 1) + .to_string(), + "lang" => doc.language_name().unwrap_or("text").to_string(), + "ext" => doc + .relative_path() + .and_then(|p| { + p.extension()?.to_os_string().into_string().ok() + }) + .unwrap_or_default(), + "selection" => doc + .selection(view.id) + .primary() + .fragment(doc.text().slice(..)) + .to_string(), + _ => anyhow::bail!("Unknown variable"), + }; + + o.push_str(value.trim()); + + break; + } + } + } + } else if char == 's' && expand_sh { + if let (Some((_, 'h')), Some((_, '{'))) = (chars.next(), chars.next()) { + let mut right_bracket_remaining = 1; + for (end, char) in chars.by_ref() { + if char == '}' { + right_bracket_remaining -= 1; + + if right_bracket_remaining == 0 { + if output.is_none() { + output = Some(String::with_capacity(input.len())) + } + + if let Some(o) = output.as_mut() { + let body = self.expand_variable_in_string( + &input[index + 4..end], + expand_sh, + )?; + + let output = tokio::task::block_in_place(move || { + helix_lsp::block_on(async move { + let mut command = + tokio::process::Command::new(&shell[0]); + command.args(&shell[1..]).arg(&body[..]); + + let output = + command.output().await.map_err(|_| { + anyhow::anyhow!( + "Shell command failed: {body}" + ) + })?; + + if output.status.success() { + String::from_utf8(output.stdout).map_err( + |_| { + anyhow::anyhow!( + "Process did not output valid UTF-8" + ) + }, + ) + } else if output.stderr.is_empty() { + Err(anyhow::anyhow!( + "Shell command failed: {body}" + )) + } else { + let stderr = + String::from_utf8_lossy(&output.stderr); + + Err(anyhow::anyhow!("{stderr}")) + } + }) + }); + o.push_str(&input[last_push_end..index]); + last_push_end = end + 1; + + o.push_str(output?.trim()); + + break; + } + } + } else if char == '{' { + right_bracket_remaining += 1; + } + } + } + } + } + } + } + + if let Some(o) = output.as_mut() { + o.push_str(&input[last_push_end..]); + } + + match output { + Some(o) => Ok(Cow::Owned(o)), + None => Ok(Cow::Borrowed(input)), + } + } +}