From dfed81a10b3de5f544ebe88a6e11bde9519d0cba Mon Sep 17 00:00:00 2001 From: trivernis Date: Tue, 12 Sep 2023 20:22:10 +0200 Subject: [PATCH] Add delete command --- book/src/generated/typable-cmd.md | 1 + helix-term/src/commands/typed.rs | 31 +++++++++++++++++++++++++++++++ helix-view/src/document.rs | 15 +++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/book/src/generated/typable-cmd.md b/book/src/generated/typable-cmd.md index 4b737893..600184fa 100644 --- a/book/src/generated/typable-cmd.md +++ b/book/src/generated/typable-cmd.md @@ -85,3 +85,4 @@ | `:reset-diff-change`, `:diffget`, `:diffg` | Reset the diff change at the cursor position. | | `:clear-register` | Clear given register. If no argument is provided, clear all registers. | | `:redraw` | Clear and re-render the whole UI | +| `:rm` | Deletes the file associated with the buffer | diff --git a/helix-term/src/commands/typed.rs b/helix-term/src/commands/typed.rs index abe6dd97..d425db3d 100644 --- a/helix-term/src/commands/typed.rs +++ b/helix-term/src/commands/typed.rs @@ -299,6 +299,30 @@ fn force_buffer_close_all( buffer_close_by_ids_impl(cx, &document_ids, true) } +fn delete( + cx: &mut compositor::Context, + _args: &[Cow], + event: PromptEvent, +) -> anyhow::Result<()> { + if event != PromptEvent::Validate { + return Ok(()); + } + + cx.block_try_flush_writes()?; + let doc = doc_mut!(cx.editor); + + if doc.path().is_none() { + bail!("cannot delete a buffer with no associated file on the disk"); + } + + let doc_id = view!(cx.editor).doc; + + let future = doc.delete(); + cx.jobs.add(Job::new(future)); + + buffer_close_by_ids_impl(cx, &[doc_id], true) +} + fn buffer_next( cx: &mut compositor::Context, _args: &[Cow], @@ -2430,6 +2454,13 @@ pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[ fun: open, signature: CommandSignature::all(completers::filename), }, + TypableCommand { + name: "delete", + aliases: &["remove", "rm", "del"], + doc: "Deletes the file associated with the current buffer", + fun: delete, + signature: CommandSignature::none(), + }, TypableCommand { name: "buffer-close", aliases: &["bc", "bclose"], diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs index bb61eaa6..45a83c3b 100644 --- a/helix-view/src/document.rs +++ b/helix-view/src/document.rs @@ -728,6 +728,21 @@ impl Document { } } + /// Deletes the file associated with this document + pub fn delete(&mut self) -> impl Future> { + let path = self + .path() + .expect("Cannot delete with no path set!") + .clone(); + + async move { + use tokio::fs; + fs::remove_file(path).await?; + + Ok(()) + } + } + /// If supported, returns the changes that should be applied to this document in order /// to format it nicely. // We can't use anyhow::Result here since the output of the future has to be