From 05a888e42f88d43ca21bab79ab1c7d2215691767 Mon Sep 17 00:00:00 2001 From: ibrahim dursun Date: Sat, 24 Sep 2022 21:30:34 +0000 Subject: [PATCH] feat: implement :read typed command --- helix-term/src/commands/typed.rs | 43 ++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/helix-term/src/commands/typed.rs b/helix-term/src/commands/typed.rs index 96ff75c54a0f..f45e1c67ffc4 100644 --- a/helix-term/src/commands/typed.rs +++ b/helix-term/src/commands/typed.rs @@ -1606,6 +1606,42 @@ fn run_shell_command( Ok(()) } +fn read_file_info_buffer( + cx: &mut compositor::Context, + args: &[Cow], + event: PromptEvent, +) -> anyhow::Result<()> { + if event != PromptEvent::Validate { + return Ok(()); + } + + let (view, doc) = current!(cx.editor); + + ensure!(!args.is_empty(), "file name is expected"); + + let filename = args.get(0).unwrap(); + let path = PathBuf::from(filename.to_string()); + if path.exists() { + match std::fs::read_to_string(path) { + Ok(contents) => { + let contents = Tendril::from(contents); + let selection = doc.selection(view.id); + let transaction = Transaction::insert(doc.text(), selection, contents); + doc.apply(&transaction, view.id); + } + Err(error) => { + cx.editor + .set_error(format!("error reading file: {}", error)); + } + } + } else { + cx.editor + .set_error(format!("file doesn't exist: {}", filename)); + } + + Ok(()) +} + pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[ TypableCommand { name: "quit", @@ -2093,6 +2129,13 @@ pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[ fun: run_shell_command, completer: Some(completers::directory), }, + TypableCommand { + name: "read", + aliases: &["r"], + doc: "Load a file into buffer", + fun: read_file_info_buffer, + completer: Some(completers::filename), + }, ]; pub static TYPABLE_COMMAND_MAP: Lazy> =