Renaming and deleting the current file in Emacs


There are multiple ways to delete a file in Emacs, but, as far as I know, they all require you to leave or find the file you want to operate on.

At some point I came across the tip I'll share today, but unfortunately, I don't remember where I found it.

Not having to leave the current buffer really speed up the delete/rename process and, for that purpose, I have two custom commands in my config

File: =fdx/rename-current-buffer-file

This command will try to rename the current buffer. It'll just open a prompt on the mini-buffer with the current file path that we can edit and press enter to change the name (or move the file).

  (defun fdx/rename-current-buffer-file ()
    "Renames current buffer and file it is visiting."
    (interactive)
    (let ((name (buffer-name))
          (filename (buffer-file-name)))
      (if (not (and filename (file-exists-p filename)))
          (error "Buffer '%s' is not visiting a file!" name)
        (let ((new-name (read-file-name "New name: " filename)))
          (if (get-buffer new-name)
              (error "A buffer named '%s' already exists!" new-name)
            (rename-file filename new-name 1)
            (rename-buffer new-name)
            (set-visited-file-name new-name)
            (set-buffer-modified-p nil)
            (message "File '%s' successfully renamed to '%s'"
                     name (file-name-nondirectory new-name)))))))

I have it bound to C-x C-r for rename.

  (global-set-key (kbd "C-x C-r") 'fdx/rename-current-buffer-file)

File: fdx/delete-current-buffer-file

This command will just ask us if we want to remove the current file. After saying yes, the file is gone. Piece of cake.

  (defun fdx/delete-current-buffer-file ()
    "Removes file connected to current buffer and kills buffer."
    (interactive)
    (let ((filename (buffer-file-name))
          (buffer (current-buffer))
          (name (buffer-name)))
      (if (not (and filename (file-exists-p filename)))
          (ido-kill-buffer)
        (when (yes-or-no-p "Are you sure you want to remove this file? ")
          (delete-file filename)
          (kill-buffer buffer)
          (message "File '%s' successfully removed" filename)))))

I have it bound to C-x C-k, since k is the universal Emacs key for kill.

  (global-set-key (kbd "C-x C-k") 'fdx/delete-current-buffer-file)

As always, I hope you found this tip useful.

Saluti.