Emacs Lisp: Delete Current File

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

Here's a emacs lisp command that deletes the current file.

(defun xah-delete-current-file (&optional φno-backup-p)
  "Delete the file associated with the current buffer.

Also close the current buffer.  If no file is associated, just close buffer.

A backup file is created with filename appended “~‹date time stamp›~”. Existing file of the same name is overwritten. If the file is not associated with buffer, the backup file name starts with “xx_”.

When called with `universal-argument', don't create backup."
  (interactive "P")
  (let* (
         (fName (buffer-file-name))
         (bufferIsFile-p (if (null fName) nil t ))
         (backupName (concat fName "~" (format-time-string "%Y%m%d_%H%M%S") "~")))
    (if bufferIsFile-p
          (save-buffer fName)
          (if φno-backup-p
            (copy-file fName backupName t))
          (delete-file fName)
          (message "deleted and backup created at 「%s」." backupName))
        (if φno-backup-p
          (write-region (point-min) (point-max) (concat "xx_~" (format-time-string "%Y%m%d_%H%M%S") "~")))))
    (kill-buffer (current-buffer))))

This command is very convenient if you code {python, ruby, …} and often creates temp testing scripts. Use it together with Emacs Lisp: Run Current File. Also, it's useful when using emacs to view images. 〔➤ Emacs 24.4: Use Emacs as Image Viewer

Here's explanation of the lisp code:

Like it?
Buy Xah Emacs Tutorial
or share
blog comments powered by Disqus