Emacs: Backup Current File 📜

By Xah Lee. Date: . Last updated: .

Here's a command to backup the current file or marked files in dired.

(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 the original name with the datetime .yyyymmddhhmmss~ appended.

Overwrite existing file.

If the current buffer is not associated with a file, do nothing.

URL `http://xahlee.info/emacs/emacs/elisp_make-backup.html'
Created: 2018-06-06
Version: 2025-07-22"
  (interactive)
  (let ((xtimestamp (format-time-string "%Y%m%d%H%M%S")))
    (if buffer-file-name
        (let ((xbackupName (concat buffer-file-name "." xtimestamp "~")))
          (copy-file buffer-file-name xbackupName t)
          (message "\nBackup saved at: %s" xbackupName))
      (if (eq major-mode 'dired-mode)
          (progn
            (mapc (lambda (xx)
                    (let ((xbackupName
                           (concat xx "." xtimestamp "~")))
                      (copy-file xx xbackupName t)))
                  (dired-get-marked-files))
            (revert-buffer))
        (user-error "xah-make-backup: 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 nor dired, nothing's done.

URL `http://xahlee.info/emacs/emacs/elisp_make-backup.html'
Created: 2015-10-14
Version: 2015-10-14"
  (interactive)
  (if buffer-file-name
      (progn
        (xah-make-backup)
        (when (buffer-modified-p)
          (save-buffer)))
    (progn
      (xah-make-backup))))

Emacs, auto save, backup