Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make Emacs backup every time I save?

Tags:

emacs

backup

From time to time I delete files that I shouldn't and worst is files that I've been writing myself. Therefore I have many times been saved by the backup feature of Emacs.

But my problem is that Emacs only makes a backup the very first time you save a buffer. Is there a way to make Emacs do it every time I press C-x C-s?

This is what my .emacs look like currently (only the part that deals with backups):

* snip *

;; ===== Backups =====

;; Enable backup files.
(setq make-backup-files t)

;; Save all backup file in this directory.
(setq backup-directory-alist (quote ((".*" . "~/.emacs_backups/"))))

;; Always backup by copying (safest, but slowest)
(setq backup-by-copying t)

;; Append .~1~ (and increasing numbers) to end of file when saving backup
(setq version-control t)

;; Defining how many old versions of a file to keep (starting from the
;; most recent and counting backward
(setq kept-new-versions 100)

* snip *

like image 646
dala Avatar asked Aug 02 '11 18:08

dala


People also ask

Does Emacs auto save?

Emacs periodically saves all files that you are visiting; this is called auto-saving. Auto-saving prevents you from losing more than a limited amount of work if the system crashes. By default, auto-saves happen every 300 keystrokes, or after around 30 seconds of idle time.

Why does Emacs create an additional file ending with a ~?

This is a backup file created automatically by emacs. Don't worry. Show activity on this post. When you save a file in Emacs, it automatically creates a backup file (what the file looked like before editing) with the “~” prefix.


2 Answers

After reading this: EmacsWiki: Force Backups

I added these lines to my .emacs:

(defun force-backup-of-buffer ()
  (setq buffer-backed-up nil))

(add-hook 'before-save-hook  'force-backup-of-buffer)

It utilizes the standard back up/version control but resets the flag that indicates wether or not the buffer has been backed up this session before a save.

First two rows define a function that resets the flag that indicates wether the buffer was backed up during this session.

Last row adds an event hook that executes the function before a save.

This does exactly what I wanted.

like image 115
dala Avatar answered Oct 14 '22 12:10

dala


If you want to do it on your own, here's a start:

(defun backup-and-save ()
  (interactive)
  (setq filename (buffer-file-name))
  (write-file (concat filename (format-time-string "_" "%Y%m%d%H%M%S")))
  (write-file filename)
  )

It saves a copy as originalfilename_timestamp in connection with a timestamp.

You might of course adjust it to store it in a separate backup folder or add other "tweaks".

like image 38
phimuemue Avatar answered Oct 14 '22 13:10

phimuemue