Emacs: Backup Current File

By Xah Lee. Date: . Last updated: .

Here's a simple command to backup the current file.

(defun xah-make-backup ()
  "Make a backup copy of current file or dired marked files.
If in dired, backup current file or marked files.
The backup file name is
 ‹name›~‹timestamp›~
example:
 file.html~20150721T014457~
in the same dir. If such a file already exist, it's overwritten.
If the current buffer is not associated with a file, nothing's done.
URL `http://ergoemacs.org/emacs/elisp_make-backup.html'
Version 2015-10-14"
  (interactive)
  (let (($fname (buffer-file-name)))
    (if $fname
        (let (($backup-name
               (concat $fname "~" (format-time-string "%Y%m%dT%H%M%S") "~")))
          (copy-file $fname $backup-name t)
          (message (concat "Backup saved at: " $backup-name)))
      (if (string-equal major-mode "dired-mode")
          (progn
            (mapc (lambda ($x)
                    (let (($backup-name
                           (concat $x "~" (format-time-string "%Y%m%dT%H%M%S") "~")))
                      (copy-file $x $backup-name t)))
                  (dired-get-marked-files))
            (message "marked files backed up"))
        (user-error "buffer not file nor dired")))))
(defun xah-make-backup-and-save ()
  "backup of current file and save, or backup dired marked files.
For detail, see `xah-make-backup'.
If the current buffer is not associated with a file, nothing's done.
URL `http://ergoemacs.org/emacs/elisp_make-backup.html'
Version 2015-10-14"
  (interactive)
  (if (buffer-file-name)
      (progn
        (xah-make-backup)
        (when (buffer-modified-p)
          (save-buffer)))
    (progn
      (xah-make-backup))))

You can give one of the command a key, such as 【F8】. [see Emacs: How to Define Keys]

To delete all backups of current directory, in dired, press【~ x】(that's dired-flag-backup-files and dired-do-flagged-delete) [see Emacs: File Manager, dired]

To jump from current file to its dired location, Alt+x dired-jump.

[see Emacs: Turn Off Auto Backup; Set Backups into a Directory; How to Delete Backup Files]

Current File Commands

  1. Emacs: Open File Path Under Cursor
  2. Emacs: Copy File Path of Current Buffer
  3. Emacs: Run Current File
  4. Emacs: Delete Current File
  5. Emacs: Backup Current File
  6. Emacs: Batch Convert Line Ending in Dired
  7. Emacs: Open File in External App
Like my tutorial? Put $5 at patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs