1 ;;; auto-save.el -- Safer autosaving for EFS and tmp.
3 ;; Copyright (C) 1997 Free Software Foundation, Inc.
4 ;; Copyright (C) 1992 by Sebastian Kremer <sk@thp.uni-koeln.de>
5 ;; Copyright (C) 2001 Ben Wing.
7 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>
8 ;; Maintainer: XEmacs Development Team
9 ;; Keywords: extensions, dumped
12 ;; SXEmacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; SXEmacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Synched up with: Not in FSF
29 ;; This file is dumped with SXEmacs.
31 ;; Combines autosaving for efs (to a local or remote directory)
32 ;; with the ability to do autosaves to a fixed directory on a local
33 ;; disk, in case NFS is slow. The auto-save file used for
34 ;; /usr/foo/bar/baz.txt
36 ;; AUTOSAVE/#=2Fusr=2Ffoo=2Fbar=2Fbaz.txt#"
37 ;; assuming AUTOSAVE is the non-nil value of the variable
38 ;; `auto-save-directory'.
40 ;; Autosaves even if the current directory is not writable.
42 ;; Can limit autosave names to 14 characters using a hash function,
43 ;; see `auto-save-hash-p'.
45 ;; See `auto-save-directory' and `make-auto-save-file-name' and
46 ;; references therein for complete documentation.
48 ;; `M-x recover-all-files' will effectively do recover-file on all
49 ;; files whose autosave file is newer (one of the benefits of having
50 ;; all autosave files in the same place).
52 ;; This file is dumped with XEmacs.
54 ;; If you want to autosave in the fixed directory /tmp/USER-autosave/
55 ;; (setq auto-save-directory
56 ;; (concat "/tmp/" (user-login-name) "-autosave/"))
58 ;; If you don't want to save in /tmp (e.g., because it is swap
59 ;; mounted) but rather in ~/.autosave/
60 ;; (setq auto-save-directory (expand-file-name "~/.autosave/"))
62 ;; If you want to save each file in its own directory (the default)
63 ;; (setq auto-save-directory nil)
64 ;; You still can take advantage of autosaving efs remote files
65 ;; in a fixed local directory, `auto-save-directory-fallback' will
68 ;; If you want to use 14 character hashed autosave filenames
69 ;; (setq auto-save-hash-p t)
71 ;; Finally, put this line after the others in your ~/.emacs:
72 ;; (require 'auto-save)
77 ;; This code is loosely derived from autosave-in-tmp.el by Jamie
78 ;; Zawinski <jwz@jwz.org> (the version I had was last modified 22
79 ;; dec 90 jwz) and code submitted to ange-ftp-lovers on Sun, 5 Apr
80 ;; 92 23:20:47 EDT by drw@BOURBAKI.MIT.EDU (Dale R. Worley).
81 ;; auto-save.el tries to cover the functionality of those two
84 ;; Valuable comments and help from Dale Worley, Andy Norman, Jamie
85 ;; Zawinski and Sandy Rutherford are gratefully acknowledged.
87 (defconst auto-save-version "1.26"
88 "Version number of auto-save.")
95 (defgroup auto-save nil
96 "Autosaving with support for efs and /tmp."
99 (put 'auto-save-interval 'custom-type 'integer)
100 (put 'auto-save-interval 'factory-value '(300))
101 (custom-add-to-group 'auto-save 'auto-save-interval 'custom-variable)
103 (defcustom auto-save-directory nil
105 ;; Don't make this user-variable-p, it should be set in .emacs and
106 ;; left at that. In particular, it should remain constant across
107 ;; several Emacs session to make recover-all-files work.
109 ;; However, it's OK for it to be customizable, as most of the
110 ;; customizable variables are set at the time `.emacs' is read.
113 "If non-nil, fixed directory for autosaving: all autosave files go
114 there. If this directory does not yet exist at load time, it is
115 created and its mode is set to 0700 so that nobody else can read your
118 If nil, each autosave files goes into the same directory as its
119 corresponding visited file.
121 A non-nil `auto-save-directory' could be on a local disk such as in
122 /tmp, then auto-saves will always be fast, even if NFS or the
123 automounter is slow. In the usual case of /tmp being locally mounted,
124 note that if you run emacs on two different machines, they will not
125 see each other's auto-save files.
127 The value \(expand-file-name \"~/.autosave/\"\) might be better if /tmp
128 is mounted from swap (possible in SunOS, type `df /tmp' to find out)
129 and thus vanishes after a reboot, or if your system is particularly
130 thorough when cleaning up /tmp, clearing even non-empty subdirectories.
132 It should never be an efs remote filename because that would
133 defeat `efs-auto-save-remotely'.
135 Unless you set `auto-save-hash-p', you shouldn't set this to a
136 directory in a filesystem that does not support long filenames, since
139 /home/sk/lib/emacs/lisp/auto-save.el
141 will have a longish filename like
143 AUTO-SAVE-DIRECTORY/#=2Fhome=2Fsk=2Flib=2Femacs=2Flisp=2Fauto-save.el#
147 See also variables `auto-save-directory-fallback',
148 `efs-auto-save' and `efs-auto-save-remotely'."
149 :type '(choice (const :tag "Same as file" nil)
154 (defcustom auto-save-hash-p nil
155 "If non-nil, hashed autosave names of length 14 are used.
156 This is to avoid autosave filenames longer than 14 characters.
157 The directory used is `auto-save-hash-directory' regardless of
158 `auto-save-directory'.
159 Hashing defeats `recover-all-files', you have to recover files
160 individually by doing `recover-file'."
164 ;;; This defvar is in efs.el now, but doesn't hurt to give it here as
165 ;;; well so that loading first auto-save.el does not abort.
167 ;; #### Now that `auto-save' is dumped, this is looks obnoxious.
168 (or (boundp 'efs-auto-save) (defvar efs-auto-save 0))
169 (or (boundp 'efs-auto-save-remotely) (defvar efs-auto-save-remotely nil))
171 (defcustom auto-save-offer-delete nil
172 "*If non-nil, `recover-all-files' offers to delete autosave files
173 that are out of date or were dismissed for recovering.
174 Special value 'always deletes those files silently."
175 :type '(choice (const :tag "on" t)
176 (const :tag "off" nil)
177 (const :tag "Delete silently" always))
180 ;;;; end of customization
183 ;;; Preparations to be done at load time
185 ;; Do not call expand-file-name! This is evaluated at dump time now!
186 (defvar auto-save-directory-fallback "~/.autosave/"
187 ;; not user-variable-p, see above
188 "Directory used for local autosaving of remote files if
189 both `auto-save-directory' and `efs-auto-save-remotely' are nil.
190 Also used if a working directory to be used for autosaving is not writable.
191 This *must* always be the name of directory that exists or can be
192 created by you, never nil.")
194 (defvar auto-save-hash-directory
195 (expand-file-name "hash/" (or auto-save-directory
196 auto-save-directory-fallback))
197 "If non-nil, directory used for hashed autosave filenames.")
199 (defun auto-save-checked-directory (dir)
200 "Make sure the directory DIR exists and return it expanded if non-nil."
202 (setq dir (expand-file-name dir))
203 ;; Make sure directory exists
204 (unless (file-directory-p dir)
205 ;; Else we create and chmod 0700 the directory
206 (setq dir (directory-file-name dir)) ; some systems need this
208 (set-file-modes dir #o700))
211 ;; This make no sense at dump time
212 ;; (mapc #'auto-save-check-directory
213 ; '(auto-save-directory auto-save-directory-fallback))
215 ;(and auto-save-hash-p
216 ; (auto-save-check-directory 'auto-save-hash-directory))
219 ;;; Computing an autosave name for a file and vice versa
221 (defun make-auto-save-file-name (&optional file-name)
222 "Return file name to use for auto-saves of current buffer.
223 Does not consider `auto-save-visited-file-name'; that is checked
224 before calling this function.
226 Offers to autosave all files in the same `auto-save-directory'. All
227 autosave files can then be recovered at once with function
230 Takes care to make autosave files for files accessed through efs
231 be local files if variable `efs-auto-save-remotely' is nil.
233 Takes care of slashes in buffer names to prevent autosave errors.
235 Takes care that autosave files for buffers not visiting any file (such
236 as `*mail*') from two simultaneous Emacses don't collide by prepending
239 Uses 14 character autosave names if `auto-save-hash-p' is true.
241 Autosaves even if the current directory is not writable, using
242 directory `auto-save-directory-fallback'.
244 You can redefine this for customization (he he :-).
245 See also function `auto-save-file-name-p'."
247 ;; We have to be very careful about not signalling an error in this
248 ;; function since files.el does not provide for this (e.g. find-file
249 ;; would fail for each new file).
251 (setq file-name (or file-name
253 (and buffer-file-name
254 (expand-file-name buffer-file-name))))
255 (condition-case error-data
257 ;; So autosavename looks like #%...#, roughly as with the
258 ;; old make-auto-save-file-name function. The
259 ;; make-temp-name inserts the pid of this Emacs: this
260 ;; avoids autosaving from two Emacses into the same file.
261 ;; It cannot be recovered automatically then because in
262 ;; the next Emacs session (the one after the crash) the
263 ;; pid will be different, but file-less buffers like
264 ;; *mail* must be recovered manually anyway.
266 ;; jwz: putting the emacs PID in the auto-save file name is bad
267 ;; news, because that defeats auto-save-recovery of *mail*
268 ;; buffers -- the (sensible) code in sendmail.el calls
269 ;; (make-auto-save-file-name) to determine whether there is
270 ;; unsent, auto-saved mail to recover. If that mail came from a
271 ;; previous emacs process (far and away the most likely case)
272 ;; then this can never succeed as the pid differs.
273 ;;(name-prefix (if file-name nil (make-temp-name "#%")))
274 (name-prefix (if file-name nil "#%"))
276 (save-name (or file-name
277 ;; Prevent autosave errors. Buffername
278 ;; (to become non-dir part of filename) will
279 ;; be escaped twice. Don't care.
280 (auto-save-escape-name (buffer-name))))
281 (remote-p (and (stringp file-name)
282 (and (fboundp #'efs-ftp-path)
283 (declare-fboundp (efs-ftp-path file-name))))))
284 ;; Return the appropriate auto save file name:
285 (expand-file-name;; a buffername needs this, a filename not
287 (if efs-auto-save-remotely
288 (auto-save-name-in-same-directory save-name)
289 ;; We have to use the `fixed-directory' now since the
290 ;; `same-directory' would be remote.
291 ;; It will use the fallback if needed.
292 (auto-save-name-in-fixed-directory save-name)))
293 ;; Else it is a local file (or a buffer without a file,
294 ;; hence the name-prefix).
295 ((or auto-save-directory auto-save-hash-p)
296 ;; Hashed files always go into the special hash dir,
297 ;; never in the same directory, to make recognizing
299 (auto-save-name-in-fixed-directory save-name name-prefix))
301 (auto-save-name-in-same-directory save-name name-prefix)))))
303 ;; If any error occurs in the above code, return what the old
304 ;; version of this function would have done. It is not ok to
305 ;; return nil, e.g., when after-find-file tests
306 ;; file-newer-than-file-p, nil would bomb.
308 (error (warn "Error caught in `make-auto-save-file-name':\n%s"
309 (error-message-string error-data))
312 (concat (file-name-directory file-name)
314 (file-name-nondirectory file-name)
317 (concat "#%" (auto-save-escape-name (buffer-name))
319 (if (or (file-writable-p fname)
320 (file-exists-p fname))
322 (expand-file-name (concat "~/"
323 (file-name-nondirectory fname))))))))
325 (defun auto-save-file-name-p (filename)
326 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
327 FILENAME should lack slashes.
328 You can redefine this for customization."
329 (string-match #r"\`#.*#\'" filename))
331 (defun auto-save-original-name (savename)
332 "Reverse of `make-auto-save-file-name'.
333 Returns nil if SAVENAME was not associated with a file (e.g., it came
334 from an autosaved `*mail*' buffer) or does not appear to be an
335 autosave file at all.
336 Hashed files are not understood, see `auto-save-hash-p'."
337 (let ((basename (file-name-nondirectory savename))
338 (savedir (file-name-directory savename)))
339 (cond ((or (not (auto-save-file-name-p basename))
340 (string-match "^#%" basename))
342 ;; now we know it looks like #...# thus substring is safe to use
344 (and auto-save-directory
345 (expand-file-name auto-save-directory)))
348 (expand-file-name auto-save-directory-fallback)))
349 ;; it is of the `-fixed-directory' type
350 (auto-save-unescape-name (substring basename 1 -1)))
352 ;; else it is of `-same-directory' type
353 (concat savedir (substring basename 1 -1))))))
355 (defun auto-save-name-in-fixed-directory (filename &optional prefix)
356 ;; Escape and enclose the whole FILENAME in `#' to make an auto
357 ;; save file in the auto-save-directory, or if that is nil, in
358 ;; auto-save-directory-fallback (which must be the name of an
359 ;; existing directory). If the results would be too long for 14
360 ;; character filenames, and `auto-save-hash-p' is set, hash FILENAME
361 ;; into a shorter name.
362 ;; Optional PREFIX is string to use instead of "#" to prefix name.
363 (let ((base-name (concat (or prefix "#")
364 (auto-save-escape-name filename)
366 (if (and auto-save-hash-p
367 auto-save-hash-directory
368 (> (length base-name) 14))
369 (expand-file-name (auto-save-cyclic-hash-14 filename)
370 (auto-save-checked-directory auto-save-hash-directory))
371 (expand-file-name base-name
372 (auto-save-checked-directory
373 (or auto-save-directory
374 auto-save-directory-fallback))))))
376 (defun auto-save-name-in-same-directory (filename &optional prefix)
377 ;; Enclose the non-directory part of FILENAME in `#' to make an auto
378 ;; save file in the same directory as FILENAME. But if this
379 ;; directory is not writable, use auto-save-directory-fallback.
380 ;; FILENAME is assumed to be in non-directory form (no trailing slash).
381 ;; It may be a name without a directory part (presumably it really
382 ;; comes from a buffer name then), the fallback is used then.
383 ;; Optional PREFIX is string to use instead of "#" to prefix name.
384 (let ((directory (file-name-directory filename)))
386 (file-writable-p directory)
387 (setq directory (auto-save-checked-directory
388 auto-save-directory-fallback)))
389 (concat directory ; (concat nil) is ""
391 (file-name-nondirectory filename)
394 (defconst auto-save-reserved-chars
396 ?\0 ?\1 ?\2 ?\3 ?\4 ?\5 ?\6 ?\7 ?\10 ?\11 ?\12 ?\13 ?\14 ?\15 ?\16
397 ?\17 ?\20 ?\21 ?\22 ?\23 ?\24 ?\25 ?\26 ?\27 ?\30 ?\31 ?\32 ?\33
398 ?\34 ?\35 ?\36 ?\37 ?\40 ?? ?* ?: ?< ?> ?| ?/ ?\\ ?& ?^ ?% ?= ?\")
399 "List of characters disallowed (or potentially disallowed) in filenames.
400 Includes everything that can get us into trouble Unix.")
402 ;; This code based on code in Bill Perry's url.el.
404 (defun auto-save-escape-name (str)
405 "Escape any evil nasty characters in a potential filename.
406 Uses quoted-printable-style escaping -- e.g. the dreaded =3D.
407 Does not use URL escaping (with %) because filenames beginning with #% are
408 a special signal for non-file buffers."
412 (if (memq char auto-save-reserved-chars)
414 (upcase (format "=0%x" char))
415 (upcase (format "=%x" char)))
416 (char-to-string char))))
419 (defun auto-save-unhex (x)
426 (defun auto-save-unescape-name (str)
427 "Undo any escaping of evil nasty characters in a file name.
428 See `auto-save-escape-name'."
429 (setq str (or str ""))
431 (case-fold-search t))
432 (while (string-match "=[0-9a-f][0-9a-f]" str)
433 (let* ((start (match-beginning 0))
434 (ch1 (auto-save-unhex (elt str (+ start 1))))
436 (auto-save-unhex (elt str (+ start 2))))))
437 (setq tmp (concat tmp (substring str 0 start)
438 (char-to-string code))
439 str (substring str (match-end 0)))))
440 (setq tmp (concat tmp str))
443 ;; The old versions are below.
445 ;(defun auto-save-escape-name (s)
446 ; ;; "Quote any slashes in string S by replacing them with the two
447 ; ;;characters `\\!'.
448 ; ;;Also, replace any backslash by double backslash, to make it one-to-one."
450 ; (while (string-match "[/\\]" s limit)
451 ; (setq s (concat (substring s 0 (match-beginning 0))
452 ; (if (string= (substring s
453 ; (match-beginning 0)
458 ; (substring s (match-end 0))))
459 ; (setq limit (1+ (match-end 0)))))
462 ;(defun auto-save-unescape-name (s)
463 ; ;;"Reverse of `auto-save-escape-name'."
465 ; (while (setq pos (string-match "\\\\[\\!]" s pos))
466 ; (setq s (concat (substring s 0 pos)
467 ; (if (eq ?! (aref s (1+ pos))) "/" "\\")
468 ; (substring s (+ pos 2)))
473 ;;; Hashing for autosave names
475 ;;; Hashing function contributed by Andy Norman <ange@hplb.hpl.hp.com>
476 ;;; based upon C code from pot@fly.cnuce.cnr.IT (Francesco Potorti`).
478 (defun auto-save-cyclic-hash-14 (s)
479 ;; "Hash string S into a string of length 14.
480 ;; A 7-bytes cyclic code for burst correction is calculated on a
481 ;; byte-by-byte basis. The polynomial used is D^7 + D^6 + D^3 +1.
482 ;; The resulting string consists of hexadecimal digits [0-9a-f].
483 ;; In particular, it contains no slash, so it can be used as autosave name."
484 (let ((crc (make-vector 7 ?\0)))
487 (setq new (+ new (aref crc 6)))
488 (aset crc 6 (+ (aref crc 5) new))
489 (aset crc 5 (aref crc 4))
490 (aset crc 4 (aref crc 3))
491 (aset crc 3 (+ (aref crc 2) new))
492 (aset crc 2 (aref crc 1))
493 (aset crc 1 (aref crc 0))
496 (format "%02x%02x%02x%02x%02x%02x%02x"
497 (logand 255 (aref crc 0))
498 (logand 255 (aref crc 1))
499 (logand 255 (aref crc 2))
500 (logand 255 (aref crc 3))
501 (logand 255 (aref crc 4))
502 (logand 255 (aref crc 5))
503 (logand 255 (aref crc 6)))))
505 ;; #### It is unclear to me how the following function is useful. It
506 ;; should be used in `auto-save-name-in-same-directory', if anywhere.
509 ;; This leaves two characters that could be used to wrap it in `#' or
510 ;; make two filenames from it: one for autosaving, and another for a
511 ;; file containing the name of the autosaved file, to make hashing
513 ;(defun auto-save-cyclic-hash-12 (s)
514 ; "Outputs the 12-characters ascii hex representation of a 6-bytes
515 ;cyclic code for burst correction calculated on STRING on a
516 ;byte-by-byte basis. The used polynomial is D^6 + D^5 + D^4 + D^3 +1."
517 ; (let ((crc (make-string 6 0)))
520 ; (setq new (+ new (aref crc 5)))
521 ; (aset crc 5 (+ (aref crc 4) new))
522 ; (aset crc 4 (+ (aref crc 3) new))
523 ; (aset crc 3 (+ (aref crc 2) new))
524 ; (aset crc 2 (aref crc 1))
525 ; (aset crc 1 (aref crc 0))
528 ; (format "%02x%02x%02x%02x%02x%02x"
540 (defun recover-all-files (&optional silent)
541 "Do recover-file for all autosave files which are current.
542 Only works if you have a non-nil `auto-save-directory'.
544 Optional prefix argument SILENT means to be silent about non-current
545 autosave files. This is useful if invoked automatically at Emacs
548 If `auto-save-offer-delete' is t, this function will offer to delete
549 old or rejected autosave files.
551 Hashed files (see `auto-save-hash-p') are not understood, use
552 `recover-file' to recover them individually."
554 (let ((savefiles (directory-files auto-save-directory
556 afile ; the auto save file
557 file ; its original file
558 (total 0) ; # of files offered to recover
559 (count 0)) ; # of files actually recovered
560 (or (equal (expand-file-name auto-save-directory)
561 (expand-file-name auto-save-directory-fallback))
564 (directory-files auto-save-directory-fallback
567 (setq afile (car savefiles)
568 file (auto-save-original-name afile)
569 savefiles (cdr savefiles))
570 (cond ((and file (not (file-newer-than-file-p afile file)))
571 (warn "Autosave file \"%s\" is not current." afile))
574 (with-output-to-temp-buffer "*Directory*"
575 (buffer-disable-undo standard-output)
577 (set-buffer "*Directory*")
578 (setq default-directory (file-name-directory afile))
579 (insert-directory afile "-l")
581 (setq default-directory (file-name-directory file))
582 (insert-directory file "-l"))))
583 (if (yes-or-no-p (format "Recover %s from auto save file? "
584 (or file "non-file buffer")))
585 (let* ((obuf (current-buffer)))
587 (find-file-noselect file t)
588 (generate-new-buffer "*recovered*")))
589 (setq buffer-read-only nil)
591 (insert-file-contents afile nil)
593 (after-find-file nil))
594 (setq buffer-auto-save-file-name nil)
596 (message "Auto-save off in buffer \"%s\" till you do M-x auto-save-mode."
600 ;; If not used for recovering, offer to delete
602 (and auto-save-offer-delete
603 (or (eq 'always auto-save-offer-delete)
605 (format "Delete autosave file for `%s'? " file)))
606 (delete-file afile))))))
608 (or silent (message "Nothing to recover."))
609 (message "%d/%d file%s recovered." count total (if (= count 1) "" "s"))))
610 (and (get-buffer "*Directory*")
611 (kill-buffer "*Directory*")))
613 ;;; auto-save.el ends here