Deleting files in Emacs

August 2022

"Picture your dream home. I bet it’s not filled with clutter."

Joshua Becker

When my computer is cluttered, I delete some files.

And I do that in Emacs. Because of course I do. Emacs has delete-file, but that leaves the buffer in Emacs. Why keep a buffer around if you wanted its associated file to disappear? You risk accidentally saving the buffer again, resurrecting the file. Also, any list of buffers you look at has some buffers you explicitly got rid of.

So let's kill the buffer.

kill-buffer works fine. But it's two steps: delete-file, followed by kill-buffer. And I have to remember to do both of them. Two steps is worse than one.

I wrote the following function to do everything in one step.

(defun delete-visited-file (buffer-name)
  "Delete the file visited by the buffer named BUFFER-NAME."
  (interactive "bDelete file visited by buffer ")
  (let* ((buffer (get-buffer buffer-name))
         (filename (buffer-file-name buffer)))
    (when buffer
      (when (and filename
                 (file-exists-p filename))
        (delete-file filename))
      (kill-buffer buffer))))
    

To use this function, add it to your config file. You can then run it with M-x delete-visited-file.

I submitted it to Emacs, but the maintainers believe it would be unpopular, so they declined it. If you use this function, please let me know.

If you want to hear when I publish more, sign up for my mailing list!

    previous

    < Re-move files in Emacs
    tag: emacs

    next

    Nix Development Shells >