12

For a long time I've had Emacs put backups for all files into a single folder:

(setq backup-directory-alist '(("." . "~/.emacs.d/backups")))

I hardly ever visit the backups directory, but recently I noticed that it contains a lot of *-autoloads.el files that I don't need backups for. How can I tell Emacs not to make backups of these types of files?

itsjeyd
  • 14,586
  • 3
  • 58
  • 87

1 Answers1

16

You can customize the location through backup-directory-alist. Each entry in the list says where to put the backups of files matching a pattern; if the location is nil, the backup will be in the same directory as the original. The order matters: the first match is used.

(setq backup-directory-alist '(("-autoloads\\.el\\'")
                               ("." . "~/.emacs.d/backups")))

If you want to suppress backups altogether on the basis of the file name or location, there doesn't appear to be a built-in mechanism for that, but it's easy enough to add. The variable backup-enable-predicate contains the name of a function that determines whether a file should have backups. The default setting normal-backup-enable-predicate only inhibits backups in the directories that Emacs uses for temporary files. You can add your own function that checks the file name as well.

(defvar backup-inhibit-file-name-regexp "-autoloads\\.el\\'"
  "Files whose full path matches this regular expression will not be backed up.")
(defun regexp-backup-enable-predicate (filename)
  "Disable backups for files whose name matches `backup-inhibit-file-name-regexp'.
Also call `normal-backup-enable-predicate'."
  (save-match-data
    (and (not (string-match backup-inhibit-file-name-regexp filename))
     (normal-backup-enable-predicate filename))))
(setq backup-enable-predicate 'regexp-backup-enable-predicate)

Even if this function returns t, other mechanisms can disable backups.

If you want to disable backups in a specific major mode, set make-backup-files to nil in the major mode's setup hook (possibly based on the file name and other characteristics). Don't forget to make the variable buffer-local.

Another way to disable backups for certain files is to set backup-inhibited. This variable survives a major mode change. It's how VC disables backups on files under version control (through an entry in file-find-hook). Don't forget to make the variable buffer-local.

  • Which pattern should I use to disable it for the files `*/.git\COMMIT_EDITMSG`? – alper Oct 04 '22 at 15:56
  • @alper The regexp needs to match that specific suffix in the file's full name (with the directory part), and `.` needs to be quoted in a regexp, so: `(setq backup-directory-alist '(("/\\.git/COMMIT_EDITMSG\\'")` – Gilles 'SO- stop being evil' Oct 04 '22 at 16:21
  • Thanks if I've multiple files can I add in to the alist one after another like `("" . "")` ? – alper Oct 04 '22 at 16:30