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 in this format
The last part is hour, minutes, seconds.

Overwrite existing file.

If the current buffer is not associated with a file, nothing's done.

URL `http://xahlee.info/emacs/emacs/elisp_make-backup.html'
Version: 2018-06-06 2022-06-13 2024-04-21"
  (let ((xfname buffer-file-name)
        (xdateTimeFormat "%Y-%m-%d_%H%M%S"))
    (if xfname
        (let ((xbackupName
               (concat xfname "~" (format-time-string xdateTimeFormat) "~")))
          (copy-file xfname xbackupName t)
          (message (concat "\nBackup saved at: " xbackupName)))
      (if (eq major-mode 'dired-mode)
            (mapc (lambda (xx)
                    (let ((xbackupName
                           (concat xx "~" (format-time-string xdateTimeFormat) "~")))
                      (copy-file xx xbackupName t)))
        (user-error "%s: buffer not file nor dired" real-this-command)))))
(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'
Version 2015-10-14"
  (if (buffer-file-name)
        (when (buffer-modified-p)

Emacs, auto save, backup