XEmacs 21.2-b1
[chise/xemacs-chise.git.1] / lisp / auto-save.el
1 ;;; auto-save.el -- Safer autosaving for EFS and tmp.
2
3 ;; Copyright (C) 1997 Free Software Foundation, Inc.
4 ;; Copyright (C) 1992 by Sebastian Kremer <sk@thp.uni-koeln.de>
5
6 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>
7 ;; Maintainer: XEmacs Development Team
8 ;; Keywords: extensions, dumped
9 ;; Version: 1.26
10
11 ;; XEmacs is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 1, or (at your option)
14 ;; any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
23 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
24 ;; 02111-1307, USA.
25
26 ;;; Synched up with: Not in FSF
27
28 ;;; Commentary:
29
30 ;; This file is dumped with XEmacs.
31
32 ;; Combines autosaving for efs (to a local or remote directory)
33 ;; with the ability to do autosaves to a fixed directory on a local
34 ;; disk, in case NFS is slow.  The auto-save file used for
35 ;;     /usr/foo/bar/baz.txt
36 ;; will be
37 ;;     AUTOSAVE/#\!usr\!foo\!bar\!baz.txt#
38 ;; assuming AUTOSAVE is the non-nil value of the variable
39 ;; `auto-save-directory'.
40
41 ;; Takes care that autosave files for non-file-buffers (e.g. *mail*)
42 ;; from two simultaneous Emacses don't collide.
43
44 ;; Autosaves even if the current directory is not writable.
45
46 ;; Can limit autosave names to 14 characters using a hash function,
47 ;; see `auto-save-hash-p'.
48
49 ;; See `auto-save-directory' and `make-auto-save-file-name' and
50 ;; references therein for complete documentation.
51
52 ;; `M-x recover-all-files' will effectively do recover-file on all
53 ;; files whose autosave file is newer (one of the benefits of having
54 ;; all autosave files in the same place).
55
56 ;; This file is dumped with XEmacs.
57
58 ;; If you want to autosave in the fixed directory /tmp/USER-autosave/
59 ;; (setq auto-save-directory
60 ;;       (concat "/tmp/" (user-login-name) "-autosave/"))
61
62 ;; If you don't want to save in /tmp (e.g., because it is swap
63 ;; mounted) but rather in ~/autosave/
64 ;;   (setq auto-save-directory (expand-file-name "~/.autosave/"))
65
66 ;; If you want to save each file in its own directory (the default)
67 ;;   (setq auto-save-directory nil)
68 ;; You still can take advantage of autosaving efs remote files
69 ;; in a fixed local directory, `auto-save-directory-fallback' will
70 ;; be used.
71
72 ;; If you want to use 14 character hashed autosave filenames
73 ;;   (setq auto-save-hash-p t)
74
75 ;; Finally, put this line after the others in your ~/.emacs:
76 ;;   (require 'auto-save)
77
78
79 ;;; Acknowledgement:
80
81 ;; This code is loosely derived from autosave-in-tmp.el by Jamie
82 ;; Zawinski <jwz@netscape.com> (the version I had was last modified 22
83 ;; dec 90 jwz) and code submitted to ange-ftp-lovers on Sun, 5 Apr
84 ;; 92 23:20:47 EDT by drw@BOURBAKI.MIT.EDU (Dale R. Worley).
85 ;; auto-save.el tries to cover the functionality of those two
86 ;; packages.
87
88 ;; Valuable comments and help from Dale Worley, Andy Norman, Jamie
89 ;; Zawinski and Sandy Rutherford are gratefully acknowledged.
90
91 (defconst auto-save-version "1.26"
92   "Version number of auto-save.")
93
94 (provide 'auto-save)
95
96 \f
97 ;;; Customization:
98
99 (defgroup auto-save nil
100   "Autosaving with support for efs and /tmp."
101   :group 'data)
102
103 (put 'auto-save-interval 'custom-type 'integer)
104 (put 'auto-save-interval 'factory-value '(300))
105 (custom-add-to-group 'auto-save 'auto-save-interval 'custom-variable)
106
107 (defcustom auto-save-directory nil
108
109   ;; Don't make this user-variable-p, it should be set in .emacs and
110   ;; left at that.  In particular, it should remain constant across
111   ;; several Emacs session to make recover-all-files work.
112
113   ;; However, it's OK for it to be customizable, as most of the
114   ;; customizable variables are set at the time `.emacs' is read.
115   ;; -hniksic
116
117   "If non-nil, fixed directory for autosaving: all autosave files go
118 there.  If this directory does not yet exist at load time, it is
119 created and its mode is set to 0700 so that nobody else can read your
120 autosave files.
121
122 If nil, each autosave files goes into the same directory as its
123 corresponding visited file.
124
125 A non-nil `auto-save-directory' could be on a local disk such as in
126 /tmp, then auto-saves will always be fast, even if NFS or the
127 automounter is slow.  In the usual case of /tmp being locally mounted,
128 note that if you run emacs on two different machines, they will not
129 see each other's auto-save files.
130
131 The value \(expand-file-name \"~/.autosave/\"\) might be better if /tmp
132 is mounted from swap (possible in SunOS, type `df /tmp' to find out)
133 and thus vanishes after a reboot, or if your system is particularly
134 thorough when cleaning up /tmp, clearing even non-empty subdirectories.
135
136 It should never be an efs remote filename because that would
137 defeat `efs-auto-save-remotely'.
138
139 Unless you set `auto-save-hash-p', you shouldn't set this to a
140 directory in a filesystem that does not support long filenames, since
141 a file named
142
143     /home/sk/lib/emacs/lisp/auto-save.el
144
145 will have a longish filename like
146
147     AUTO-SAVE-DIRECTORY/#\\!home\\!sk\\!lib\\!emacs\\!lisp\\!auto-save.el#
148
149 as auto save file.
150
151 See also variables `auto-save-directory-fallback',
152 `efs-auto-save' and `efs-auto-save-remotely'."
153   :type '(choice (const :tag "Same as file" nil)
154                  directory)
155   :group 'auto-save)
156
157
158 (defcustom auto-save-hash-p nil
159   "If non-nil, hashed autosave names of length 14 are used.
160 This is to avoid autosave filenames longer than 14 characters.
161 The directory used is `auto-save-hash-directory' regardless of
162 `auto-save-directory'.
163 Hashing defeats `recover-all-files', you have to recover files
164 individually by doing `recover-file'."
165   :type 'boolean
166   :group 'auto-save)
167
168 ;;; This defvar is in efs.el now, but doesn't hurt to give it here as
169 ;;; well so that loading first auto-save.el does not abort.
170
171 ;; #### Now that `auto-save' is dumped, this is looks obnoxious.
172 (or (boundp 'efs-auto-save) (defvar efs-auto-save 0))
173 (or (boundp 'efs-auto-save-remotely) (defvar efs-auto-save-remotely nil))
174
175 (defcustom auto-save-offer-delete nil
176   "*If non-nil, `recover-all-files' offers to delete autosave files
177 that are out of date or were dismissed for recovering.
178 Special value 'always deletes those files silently."
179   :type '(choice (const :tag "on" t)
180                  (const :tag "off" nil)
181                  (const :tag "Delete silently" always))
182   :group 'auto-save)
183
184 ;;;; end of customization
185
186 \f
187 ;;; Preparations to be done at load time
188
189 (defvar auto-save-directory-fallback (expand-file-name "~/.autosave/")
190   ;; not user-variable-p, see above
191   "Directory used for local autosaving of remote files if
192 both `auto-save-directory' and `efs-auto-save-remotely' are nil.
193 Also used if a working directory to be used for autosaving is not writable.
194 This *must* always be the name of directory that exists or can be
195 created by you, never nil.")
196
197 (defvar auto-save-hash-directory
198   (expand-file-name "hash/" (or auto-save-directory
199                                 auto-save-directory-fallback))
200   "If non-nil, directory used for hashed autosave filenames.")
201
202 (defun auto-save-check-directory (var)
203   (let ((dir (symbol-value var)))
204     (if (null dir)
205         nil
206       ;; Expand and store back into the variable
207       (set var (setq dir (expand-file-name dir)))
208       ;; Make sure directory exists
209       (if (file-directory-p dir)
210           nil
211         ;; Else we create and chmod 0700 the directory
212         (setq dir (directory-file-name dir)) ; some systems need this
213         (make-directory dir)
214         (set-file-modes dir #o700)))))
215
216 (mapc #'auto-save-check-directory
217      '(auto-save-directory auto-save-directory-fallback))
218
219 (and auto-save-hash-p
220      (auto-save-check-directory 'auto-save-hash-directory))
221
222 \f
223 ;;; Computing an autosave name for a file and vice versa
224
225 ;; #### Now that this file is dumped, we should turn off the routine
226 ;; from files.el.  But it would make it harder to remove it!
227
228 (defun make-auto-save-file-name (&optional file-name);; redefines files.el
229   ;; auto-save-file-name-p need not be redefined.
230
231   "Return file name to use for auto-saves of current buffer.
232 Does not consider `auto-save-visited-file-name'; that is checked
233 before calling this function.
234
235 Offers to autosave all files in the same `auto-save-directory'.  All
236 autosave files can then be recovered at once with function
237 `recover-all-files'.
238
239 Takes care to make autosave files for files accessed through efs
240 be local files if variable `efs-auto-save-remotely' is nil.
241
242 Takes care of slashes in buffer names to prevent autosave errors.
243
244 Takes care that autosave files for buffers not visiting any file (such
245 as `*mail*') from two simultaneous Emacses don't collide by prepending
246 the Emacs pid.
247
248 Uses 14 character autosave names if `auto-save-hash-p' is true.
249
250 Autosaves even if the current directory is not writable, using
251 directory `auto-save-directory-fallback'.
252
253 You can redefine this for customization (he he :-).
254 See also function `auto-save-file-name-p'."
255
256   ;; We have to be very careful about not signalling an error in this
257   ;; function since files.el does not provide for this (e.g. find-file
258   ;; would fail for each new file).
259
260   (setq file-name (or file-name
261                       buffer-file-truename
262                       (and buffer-file-name
263                            (expand-file-name buffer-file-name))))
264   (condition-case error-data
265       (let (
266             ;; So autosavename looks like #%...#, roughly as with the
267             ;; old make-auto-save-file-name function.  The
268             ;; make-temp-name inserts the pid of this Emacs: this
269             ;; avoids autosaving from two Emacses into the same file.
270             ;; It cannot be recovered automatically then because in
271             ;; the next Emacs session (the one after the crash) the
272             ;; pid will be different, but file-less buffers like
273             ;; *mail* must be recovered manually anyway.
274
275             ;; jwz: putting the emacs PID in the auto-save file name is bad
276             ;; news, because that defeats auto-save-recovery of *mail*
277             ;; buffers -- the (sensible) code in sendmail.el calls
278             ;; (make-auto-save-file-name) to determine whether there is
279             ;; unsent, auto-saved mail to recover. If that mail came from a
280             ;; previous emacs process (far and away the most likely case)
281             ;; then this can never succeed as the pid differs.
282             ;;(name-prefix (if file-name nil (make-temp-name "#%")))
283             (name-prefix (if file-name nil "#%"))
284
285             (save-name (or file-name
286                            ;; Prevent autosave errors.  Buffername
287                            ;; (to become non-dir part of filename) will
288                            ;; be unslashified twice.  Don't care.
289                            (auto-save-unslashify-name (buffer-name))))
290             (remote-p (and (stringp file-name)
291                            (fboundp 'efs-ftp-path)
292                            (efs-ftp-path file-name))))
293         ;; Return the appropriate auto save file name:
294         (expand-file-name;; a buffername needs this, a filename not
295          (cond (remote-p
296                 (if efs-auto-save-remotely
297                     (auto-save-name-in-same-directory save-name)
298                   ;; We have to use the `fixed-directory' now since the
299                   ;; `same-directory' would be remote.
300                   ;; It will use the fallback if needed.
301                   (auto-save-name-in-fixed-directory save-name)))
302                ;; Else it is a local file (or a buffer without a file,
303                ;; hence the name-prefix).
304                ((or auto-save-directory auto-save-hash-p)
305                 ;; Hashed files always go into the special hash dir,
306                 ;; never in the same directory, to make recognizing
307                 ;; reliable.
308                 (auto-save-name-in-fixed-directory save-name name-prefix))
309                (t
310                 (auto-save-name-in-same-directory save-name name-prefix)))))
311
312     ;; If any error occurs in the above code, return what the old
313     ;; version of this function would have done.  It is not ok to
314     ;; return nil, e.g., when after-find-file tests
315     ;; file-newer-than-file-p, nil would bomb.
316
317     (error (warn "Error caught in `make-auto-save-file-name':\n%s"
318                  (error-message-string error-data))
319            (if buffer-file-name
320                (concat (file-name-directory buffer-file-name)
321                        "#"
322                        (file-name-nondirectory buffer-file-name)
323                        "#")
324              (expand-file-name (concat "#%" (buffer-name) "#"))))))
325
326 (defun auto-save-original-name (savename)
327   "Reverse of `make-auto-save-file-name'.
328 Returns nil if SAVENAME was not associated with a file (e.g., it came
329 from an autosaved `*mail*' buffer) or does not appear to be an
330 autosave file at all.
331 Hashed files are not understood, see `auto-save-hash-p'."
332   (let ((basename (file-name-nondirectory savename))
333         (savedir (file-name-directory savename)))
334     (cond ((or (not (auto-save-file-name-p basename))
335                (string-match "^#%" basename))
336            nil)
337           ;; now we know it looks like #...# thus substring is safe to use
338           ((or (equal savedir auto-save-directory) ; 2nd arg may be nil
339                (equal savedir auto-save-directory-fallback))
340            ;; it is of the `-fixed-directory' type
341            (auto-save-slashify-name (substring basename 1 -1)))
342           (t
343            ;; else it is of `-same-directory' type
344            (concat savedir (substring basename 1 -1))))))
345
346 (defun auto-save-name-in-fixed-directory (filename &optional prefix)
347   ;; Unslashify and enclose the whole FILENAME in `#' to make an auto
348   ;; save file in the auto-save-directory, or if that is nil, in
349   ;; auto-save-directory-fallback (which must be the name of an
350   ;; existing directory).  If the results would be too long for 14
351   ;; character filenames, and `auto-save-hash-p' is set, hash FILENAME
352   ;; into a shorter name.
353   ;; Optional PREFIX is string to use instead of "#" to prefix name.
354   (let ((base-name (concat (or prefix "#")
355                            (auto-save-unslashify-name filename)
356                            "#")))
357     (if (and auto-save-hash-p
358              auto-save-hash-directory
359              (> (length base-name) 14))
360         (expand-file-name (auto-save-cyclic-hash-14 filename)
361                           auto-save-hash-directory)
362       (expand-file-name base-name
363                         (or auto-save-directory
364                             auto-save-directory-fallback)))))
365
366 (defun auto-save-name-in-same-directory (filename &optional prefix)
367   ;; Enclose the non-directory part of FILENAME in `#' to make an auto
368   ;; save file in the same directory as FILENAME.  But if this
369   ;; directory is not writable, use auto-save-directory-fallback.
370   ;; FILENAME is assumed to be in non-directory form (no trailing slash).
371   ;; It may be a name without a directory part (pesumably it really
372   ;; comes from a buffer name then), the fallback is used then.
373   ;; Optional PREFIX is string to use instead of "#" to prefix name.
374   (let ((directory (file-name-directory filename)))
375     (or (null directory)
376         (file-writable-p directory)
377         (setq directory auto-save-directory-fallback))
378     (concat directory                   ; (concat nil) is ""
379             (or prefix "#")
380             (file-name-nondirectory filename)
381             "#")))
382
383 ;; #### The following two should probably use `replace-in-string'.
384
385 (defun auto-save-unslashify-name (s)
386   ;;  "Quote any slashes in string S by replacing them with the two
387   ;;characters `\\!'.
388   ;;Also, replace any backslash by double backslash, to make it one-to-one."
389   (let ((limit 0))
390     (while (string-match "[/\\]" s limit)
391       (setq s (concat (substring s 0 (match-beginning 0))
392                       (if (string= (substring s
393                                               (match-beginning 0)
394                                               (match-end 0))
395                                    "/")
396                           "\\!"
397                         "\\\\")
398                       (substring s (match-end 0))))
399       (setq limit (1+ (match-end 0)))))
400   s)
401
402 (defun auto-save-slashify-name (s)
403   ;;"Reverse of `auto-save-unslashify-name'."
404   (let (pos)
405     (while (setq pos (string-match "\\\\[\\!]" s pos))
406       (setq s (concat (substring s 0 pos)
407                       (if (eq ?! (aref s (1+ pos))) "/" "\\")
408                       (substring s (+ pos 2)))
409             pos (1+ pos))))
410   s)
411
412 \f
413 ;;; Hashing for autosave names
414
415 ;;; Hashing function contributed by Andy Norman <ange@hplb.hpl.hp.com>
416 ;;; based upon C code from pot@fly.cnuce.cnr.IT (Francesco Potorti`).
417
418 (defun auto-save-cyclic-hash-14 (s)
419   ;;   "Hash string S into a string of length 14.
420   ;; A 7-bytes cyclic code for burst correction is calculated on a
421   ;; byte-by-byte basis. The polynomial used is D^7 + D^6 + D^3 +1.
422   ;; The resulting string consists of hexadecimal digits [0-9a-f].
423   ;; In particular, it contains no slash, so it can be used as autosave name."
424   (let ((crc (make-vector 7 ?\0)))
425     (mapc
426      (lambda (new)
427        (setq new (+ new (aref crc 6)))
428        (aset crc 6 (+ (aref crc 5) new))
429        (aset crc 5 (aref crc 4))
430        (aset crc 4 (aref crc 3))
431        (aset crc 3 (+ (aref crc 2) new))
432        (aset crc 2 (aref crc 1))
433        (aset crc 1 (aref crc 0))
434        (aset crc 0 new))
435      s)
436     (format "%02x%02x%02x%02x%02x%02x%02x"
437             (logand 255 (aref crc 0))
438             (logand 255 (aref crc 1))
439             (logand 255 (aref crc 2))
440             (logand 255 (aref crc 3))
441             (logand 255 (aref crc 4))
442             (logand 255 (aref crc 5))
443             (logand 255 (aref crc 6)))))
444
445 ;; #### It is unclear to me how the following function is useful.  It
446 ;; should be used in `auto-save-name-in-same-directory', if anywhere.
447 ;; -hniksic
448
449 ;; This leaves two characters that could be used to wrap it in `#' or
450 ;; make two filenames from it: one for autosaving, and another for a
451 ;; file containing the name of the autosaved filed, to make hashing
452 ;; reversible.
453 ;(defun auto-save-cyclic-hash-12 (s)
454 ;  "Outputs the 12-characters ascii hex representation of a 6-bytes
455 ;cyclic code for burst correction calculated on STRING on a
456 ;byte-by-byte basis. The used polynomial is D^6 + D^5 + D^4 + D^3 +1."
457 ;  (let ((crc (make-string 6 0)))
458 ;    (mapc
459 ;     (lambda (new)
460 ;       (setq new (+ new (aref crc 5)))
461 ;       (aset crc 5 (+ (aref crc 4) new))
462 ;       (aset crc 4 (+ (aref crc 3) new))
463 ;       (aset crc 3 (+ (aref crc 2) new))
464 ;       (aset crc 2 (aref crc 1))
465 ;       (aset crc 1 (aref crc 0))
466 ;       (aset crc 0 new))
467 ;     s)
468 ;    (format "%02x%02x%02x%02x%02x%02x"
469 ;            (aref crc 0)
470 ;            (aref crc 1)
471 ;            (aref crc 2)
472 ;            (aref crc 3)
473 ;            (aref crc 4)
474 ;            (aref crc 5))))
475
476 \f
477
478 ;;; Recovering files
479
480 (defun recover-all-files (&optional silent)
481   "Do recover-file for all autosave files which are current.
482 Only works if you have a non-nil `auto-save-directory'.
483
484 Optional prefix argument SILENT means to be silent about non-current
485 autosave files.  This is useful if invoked automatically at Emacs
486 startup.
487
488 If `auto-save-offer-delete' is t, this function will offer to delete
489 old or rejected autosave files.
490
491 Hashed files (see `auto-save-hash-p') are not understood, use
492 `recover-file' to recover them individually."
493   (interactive "P")
494   (let ((savefiles (directory-files auto-save-directory
495                                     t "\\`#" nil t))
496         afile                           ; the auto save file
497         file                            ; its original file
498         (total 0)                       ; # of files offered to recover
499         (count 0))                      ; # of files actually recovered
500     (or (equal auto-save-directory auto-save-directory-fallback)
501         (setq savefiles
502               (nconc savefiles
503                      (directory-files auto-save-directory-fallback
504                                       t "\\`#" nil t))))
505     (while savefiles
506       (setq afile (car savefiles)
507             file (auto-save-original-name afile)
508             savefiles (cdr savefiles))
509       (cond ((and file (not (file-newer-than-file-p afile file)))
510              (warn "Autosave file \"%s\" is not current." afile))
511             (t
512              (incf total)
513              (with-output-to-temp-buffer "*Directory*"
514                (apply 'call-process "ls" nil standard-output nil
515                       "-l" afile (if file (list file))))
516              (if (yes-or-no-p (format "Recover %s from auto save file? "
517                                       (or file "non-file buffer")))
518                  (let* ((obuf (current-buffer)))
519                    (set-buffer (if file
520                                    (find-file-noselect file t)
521                                  (generate-new-buffer "*recovered*")))
522                    (setq buffer-read-only nil)
523                    (erase-buffer)
524                    (insert-file-contents afile nil)
525                    (ignore-errors
526                      (after-find-file nil))
527                    (setq buffer-auto-save-file-name nil)
528                    (incf count)
529                    (message "\
530 Auto-save off in buffer \"%s\" till you do M-x auto-save-mode."
531                             (buffer-name))
532                    (set-buffer obuf)
533                    (sit-for 1))
534                ;; If not used for recovering, offer to delete
535                ;; autosave file
536                (and auto-save-offer-delete
537                     (or (eq 'always auto-save-offer-delete)
538                         (yes-or-no-p
539                          (format "Delete autosave file for `%s'? " file)))
540                     (delete-file afile))))))
541     (if (zerop total)
542         (or silent (message "Nothing to recover."))
543       (message "%d/%d file%s recovered." count total (if (= count 1) "" "s"))))
544   (and (get-buffer "*Directory*")
545        (kill-buffer "*Directory*")))
546
547 ;;; auto-save.el ends here