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 closes the 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.

URL `http://ergoemacs.org/emacs/elisp_delete-current-file.html'
Version 2015-05-26"
  (interactive "P")
  (let* (
         (ξfname (buffer-file-name))
         (ξbuffer-is-file-p ξfname)
         (ξbackup-suffix (concat "~" (format-time-string "%Y%m%dT%H%M%S") "~")))
    (if ξbuffer-is-file-p
        (progn
          (save-buffer ξfname)
          (when (not φno-backup-p)
            (copy-file
             ξfname
             (concat ξfname ξbackup-suffix)
             t))
          (delete-file ξfname)
          (message "Deleted. Backup created at 「%s」." (concat ξfname ξbackup-suffix)))
      (when (not φno-backup-p)
        (widen)
        (write-region (point-min) (point-max) (concat "xx" ξbackup-suffix))
        (message "Backup created at 「%s」." (concat "xx" ξbackup-suffix))))
    (kill-buffer (current-buffer))))

This command is very convenient if you code {Python, Perl, 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

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