Emacs: Backup Current File 🚀
Here's a command to backup the current file. It creates a copy of the file in the current dir, with file name ending in ~.
(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 x.html~2018-05-15_133429~ The last part is hour, minutes, seconds. in the same dir. If such a file already exist, it is overwritten. 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 2020-12-18 2022-06-13" (interactive) (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 "Backup saved at: " xbackupName))) (if (eq major-mode 'dired-mode) (progn (mapc (lambda (xx) (let ((xbackupName (concat xx "~" (format-time-string xdateTimeFormat) "~"))) (copy-file xx xbackupName t))) (dired-get-marked-files)) (revert-buffer)) (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" (interactive) (if (buffer-file-name) (progn (xah-make-backup) (when (buffer-modified-p) (save-buffer))) (progn (xah-make-backup))))