ChatGPT解决这个技术问题 Extra ChatGPT

How do I control how Emacs makes backup files?

Emacs puts backup files named foo~ everywhere and I don't like having to remember to delete them. Also, if I edit a file that has a hard link somewhere else in the file system, the hard link points to the backup when I'm done editing, and that's confusing and awful. How can I either eliminate these backup files, or have them go somewhere other than the same directory?


A
AST

If you've ever been saved by an Emacs backup file, you probably want more of them, not less of them. It is annoying that they go in the same directory as the file you're editing, but that is easy to change. You can make all backup files go into a directory by putting something like the following in your .emacs.

(setq backup-directory-alist `(("." . "~/.saves")))

There are a number of arcane details associated with how Emacs might create your backup files. Should it rename the original and write out the edited buffer? What if the original is linked? In general, the safest but slowest bet is to always make backups by copying.

(setq backup-by-copying t)

If that's too slow for some reason you might also have a look at backup-by-copying-when-linked.

Since your backups are all in their own place now, you might want more of them, rather than less of them. Have a look at the Emacs documentation for these variables (with C-h v).

(setq delete-old-versions t
  kept-new-versions 6
  kept-old-versions 2
  version-control t)

Finally, if you absolutely must have no backup files:

(setq make-backup-files nil)

It makes me sick to think of it though.


why use backups? why not use git/mercurial? good version control systems and programming methodologies should trump individual file backup by the editor
@vol7ron : The backups are for when you are editing something not under version control - like a config file or something quick and dirty that you haven't gotten around to putting into version control yet. Then, when you haven't been doing what you ought to, the editor saves your neck.
@vol7ron - That's just wrong. You shouldn't be putting crap into revision control that you don't want to keep. It just makes finding the important stuff way harder. Instead, use your editor backups for what they are good for (backing up changes in case of emergency) and revision control for what its good for (keeping important versions of your software and facilitating team development). Use the right tool for the job.
Downvoting b/c of the judgmentalism. Backup files add so much overhead and almost no value. You have to save to run your tests, anyway, so it's rare to go more than 5 minutes without saving. Even if I'm editing non version controlled config files, is emacs so unstable that it's constantly crashing? What workflow merits this kind of overhead?
"Backup files add so much overhead and almost no value": isn't that judgmentalism?
A
Andreas Spindler

Emacs backup/auto-save files can be very helpful. But these features are confusing.

Backup files

Backup files have tildes (~ or ~9~) at the end and shall be written to the user home directory. When make-backup-files is non-nil Emacs automatically creates a backup of the original file the first time the file is saved from a buffer. If you're editing a new file Emacs will create a backup the second time you save the file.

No matter how many times you save the file the backup remains unchanged. If you kill the buffer and then visit the file again, or the next time you start a new Emacs session, a new backup file will be made. The new backup reflects the file's content after reopened, or at the start of editing sessions. But an existing backup is never touched again. Therefore I find it useful to created numbered backups (see the configuration below).

To create backups explicitly use save-buffer (C-x C-s) with prefix arguments.

diff-backup and dired-diff-backup compares a file with its backup or vice versa. But there is no function to restore backup files. For example, under Windows, to restore a backup file

C:\Users\USERNAME\.emacs.d\backups\!drive_c!Users!USERNAME!.emacs.el.~7~

it has to be manually copied as

C:\Users\USERNAME\.emacs.el

Auto-save files

Auto-save files use hashmarks (#) and shall be written locally within the project directory (along with the actual files). The reason is that auto-save files are just temporary files that Emacs creates until a file is saved again (like with hurrying obedience).

Before the user presses C-x C-s (save-buffer) to save a file Emacs auto-saves files - based on counting keystrokes (auto-save-interval) or when you stop typing (auto-save-timeout).

Emacs also auto-saves whenever it crashes, including killing the Emacs job with a shell command.

When the user saves the file, the auto-saved version is deleted. But when the user exits the file without saving it, Emacs or the X session crashes, the auto-saved files still exist.

Use revert-buffer or recover-file to restore auto-save files. Note that Emacs records interrupted sessions for later recovery in files named ~/.emacs.d/auto-save-list. The recover-session function will use this information.

The preferred method to recover from an auto-saved filed is M-x revert-buffer RET. Emacs will ask either "Buffer has been auto-saved recently. Revert from auto-save file?" or "Revert buffer from file FILENAME?". In case of the latter there is no auto-save file. For example, because you have saved before typing another auto-save-intervall keystrokes, in which case Emacs had deleted the auto-save file.

Auto-save is nowadays disabled by default because it can slow down editing when connected to a slow machine, and because many files contain sensitive data.

Configuration

Here is a configuration that IMHO works best:

(defvar --backup-directory (concat user-emacs-directory "backups"))
(if (not (file-exists-p --backup-directory))
        (make-directory --backup-directory t))
(setq backup-directory-alist `(("." . ,--backup-directory)))
(setq make-backup-files t               ; backup of a file the first time it is saved.
      backup-by-copying t               ; don't clobber symlinks
      version-control t                 ; version numbers for backup files
      delete-old-versions t             ; delete excess backup files silently
      delete-by-moving-to-trash t
      kept-old-versions 6               ; oldest versions to keep when a new numbered backup is made (default: 2)
      kept-new-versions 9               ; newest versions to keep when a new numbered backup is made (default: 2)
      auto-save-default t               ; auto-save every buffer that visits a file
      auto-save-timeout 20              ; number of seconds idle time before auto-save (default: 30)
      auto-save-interval 200            ; number of keystrokes between auto-saves (default: 300)
      )

Sensitive data

Another problem is that you don't want to have Emacs spread copies of files with sensitive data. Use this mode on a per-file basis. As this is a minor mode, for my purposes I renamed it sensitive-minor-mode.

To enable it for all .vcf and .gpg files, in your .emacs use something like:

(setq auto-mode-alist
      (append
       (list
        '("\\.\\(vcf\\|gpg\\)$" . sensitive-minor-mode)
        )
       auto-mode-alist))

Alternatively, to protect only some files, like some .txt files, use a line like

// -*-mode:asciidoc; mode:sensitive-minor; fill-column:132-*-

in the file.


So you do not use autosave? These settings allow you to avoid having to see those nasty #filename.tex# files in your folder?
I always use autosave and backup files by default, except for files with sensitive data. Sensitive mode disables autosaving and backups. BTW, #file.ext# files are not really nasty, because Emacs creates and deletes them as needed. If they remain either Emacs is still running, or they're an artifact from a crashed Emacs. In both cases they can save the day ;-)
Ah, thanks for that extra information. I do indeed have mostly positive experience with them (they did save my day). Only when you're looking for ugliness, well you got it right there :)
BTW it is one thing to make backups, and a different thing to restore backups. Hence play with auto-save. Kill the Emacs job or ssh session. If there is an auto-save file diff it with the actual file. Then fire Emacs and find out by yourself what revert-buffer does. This will pay off quickly in cases of emergency.
The sensitive-mode works great. Thanks. Please note that in your post you call it sensitive-minor-mode whereas in the definition (link) it is called sensitive-mode. Maybe you want to align that.
C
Community

The accepted answer is good, but it can be greatly improved by additionally backing up on every save and backing up versioned files.

First, basic settings as described in the accepted answer:

(setq version-control t     ;; Use version numbers for backups.
      kept-new-versions 10  ;; Number of newest versions to keep.
      kept-old-versions 0   ;; Number of oldest versions to keep.
      delete-old-versions t ;; Don't ask to delete excess backup versions.
      backup-by-copying t)  ;; Copy all files, don't rename them.

Next, also backup versioned files, which Emacs does not do by default (you don't commit on every save, right?):

(setq vc-make-backup-files t)

Finally, make a backup on each save, not just the first. We make two kinds of backups:

per-session backups: once on the first save of the buffer in each Emacs session. These simulate Emac's default backup behavior. per-save backups: once on every save. Emacs does not do this by default, but it's very useful if you leave Emacs running for a long time.

The backups go in different places and Emacs creates the backup dirs automatically if they don't exist:

;; Default and per-save backups go here:
(setq backup-directory-alist '(("" . "~/.emacs.d/backup/per-save")))

(defun force-backup-of-buffer ()
  ;; Make a special "per session" backup at the first save of each
  ;; emacs session.
  (when (not buffer-backed-up)
    ;; Override the default parameters for per-session backups.
    (let ((backup-directory-alist '(("" . "~/.emacs.d/backup/per-session")))
          (kept-new-versions 3))
      (backup-buffer)))
  ;; Make a "per save" backup on each save.  The first save results in
  ;; both a per-session and a per-save backup, to keep the numbering
  ;; of per-save backups consistent.
  (let ((buffer-backed-up nil))
    (backup-buffer)))

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

I became very interested in this topic after I wrote $< instead of $@ in my Makefile, about three hours after my previous commit :P

The above is based on an Emacs Wiki page I heavily edited.


I pasted the above code inside my init.el file, yet I don't get any backup directory and emacs still creates the backup files all over. I might have misunderstood something, I'm new to emacs :P
@Soeholm: did you paste all of the code in my answer, including the setqs at the top of my answer? The above works for me in Emacs 24.5.1.
It started working now. I had all the code pasted in, so I'm not sure why it was slow to accept my new configuration. But thanks a lot!
As a followup, I know why it didn't work now. It worked on one machine, but not the other. It was because I had an empty .emacs file in my home directory, which took priority over my .emacs.d directory. Silly mistake..
I don't know why by it does not save the file I am workig on, but it only saves newly created files
D
Dave Webb

Another way of configuring backup options is via the Customize interface. Enter:

M-x customize-group

And then at the Customize group: prompt enter backup.

If you scroll to the bottom of the buffer you'll see Backup Directory Alist. Click Show Value and set the first entry of the list as follows:

Regexp matching filename: .*
Backup directory name: /path/to/your/backup/dir

Alternatively, you can turn backups off my setting Make Backup Files to off.

If you don't want Emacs to automatically edit your .emacs file you'll want to set up a customisations file.


I wish I had known about customize-group 2 years ago. Thank you!
P
Paweł Hajdan

You can disable them altogether by

(setq make-backup-files nil)

I like to set this from the shell prompt, when I'm hopping from host to host I don't like to have .emacs files: emacs --eval "(setq make-backup-files nil)"
F
FeralWhippet

(setq delete-auto-save-files t)

deletes buffer's auto save file when it is saved or when killed with no changes in it. thus you still get some of the safety of auto save files, since they are only left around when a buffer is killed with unsaved changes or if emacs exits unexpectedly. if you want to do this, but really need history on some of your files, consider putting them under source control.