Merge branch 'master' into dbus
[sxemacs] / lisp / files.el
1 ;;; files.el --- file input and output commands for SXEmacs.
2
3 ;; Copyright (C) 1985-1987, 1992-1995, 1997 Free Software Foundation, Inc.
4 ;; Copyright (C) 1995 Sun Microsystems.
5
6 ;; Maintainer: SXEmacs Development Team
7 ;; Keywords: extensions, dumped
8
9 ;; This file is part of SXEmacs.
10
11 ;; SXEmacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; SXEmacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Synched up with: FSF 20.3 (but diverging)
25 ;;; Warning: Merging this file is tough.  Beware.
26
27 ;;; Commentary:
28
29 ;; This file is dumped with SXEmacs.
30
31 ;; Defines most of XEmacs's file- and directory-handling functions,
32 ;; including basic file visiting, backup generation, link handling,
33 ;; ITS-id version control, load- and write-hook handling, and the like.
34
35 ;;; Code:
36
37 ;; XEmacs: Avoid compilation warnings.
38 (defvar coding-system-for-read)
39 (defvar buffer-file-coding-system)
40 (eval-when-compile
41   (globally-declare-fboundp '(dired-noselect dired)))
42
43
44 (defgroup files nil
45   "Support editing files."
46   :group 'emacs)
47
48 (defgroup backup nil
49   "Backups of edited data files."
50   :group 'files)
51
52 (defgroup find-file nil
53   "Finding and editing files."
54   :group 'files)
55
56
57 ;; XEmacs: In buffer.c
58 ;(defconst delete-auto-save-files t
59 ;  "*Non-nil means delete auto-save file when a buffer is saved or killed.")
60
61 ;; FSF has automount-dir-prefix.  Our directory-abbrev-alist is more general.
62 ;; note: tmp_mnt bogosity conversion is established in paths.el.
63 (defcustom directory-abbrev-alist nil
64   "*Alist of abbreviations for file directories.
65 A list of elements of the form (FROM . TO), each meaning to replace
66 FROM with TO when it appears in a directory name.
67 This replacement is done when setting up the default directory of a
68 newly visited file.  *Every* FROM string should start with \\\\` or ^.
69
70 Use this feature when you have directories which you normally refer to
71 via absolute symbolic links or to eliminate automounter mount points
72 from the beginning of your filenames.  Make TO the name of the link,
73 and FROM the name it is linked to."
74   :type '(repeat (cons :format "%v"
75                        :value ("\\`" . "")
76                        (regexp :tag "From")
77                        (regexp :tag "To")))
78   :group 'find-file)
79
80 (defcustom make-backup-files t
81   "*Non-nil means make a backup of a file the first time it is saved.
82 This can be done by renaming the file or by copying.
83
84 Renaming means that XEmacs renames the existing file so that it is a
85 backup file, then writes the buffer into a new file.  Any other names
86 that the old file had will now refer to the backup file.  The new file
87 is owned by you and its group is defaulted.
88
89 Copying means that XEmacs copies the existing file into the backup
90 file, then writes the buffer on top of the existing file.  Any other
91 names that the old file had will now refer to the new (edited) file.
92 The file's owner and group are unchanged.
93
94 The choice of renaming or copying is controlled by the variables
95 `backup-by-copying', `backup-by-copying-when-linked' and
96 `backup-by-copying-when-mismatch'.  See also `backup-inhibited'."
97   :type 'boolean
98   :group 'backup)
99
100 ;; Do this so that local variables based on the file name
101 ;; are not overridden by the major mode.
102 (defvar backup-inhibited nil
103   "Non-nil means don't make a backup, regardless of the other parameters.
104 This variable is intended for use by making it local to a buffer.
105 But it is local only if you make it local.")
106 (put 'backup-inhibited 'permanent-local t)
107
108 (defcustom backup-by-copying nil
109  "*Non-nil means always use copying to create backup files.
110 See documentation of variable `make-backup-files'."
111  :type 'boolean
112  :group 'backup)
113
114 (defcustom backup-by-copying-when-linked nil
115  "*Non-nil means use copying to create backups for files with multiple names.
116 This causes the alternate names to refer to the latest version as edited.
117 This variable is relevant only if `backup-by-copying' is nil."
118  :type 'boolean
119  :group 'backup)
120
121 (defcustom backup-by-copying-when-mismatch nil
122   "*Non-nil means create backups by copying if this preserves owner or group.
123 Renaming may still be used (subject to control of other variables)
124 when it would not result in changing the owner or group of the file;
125 that is, for files which are owned by you and whose group matches
126 the default for a new file created there by you.
127 This variable is relevant only if `backup-by-copying' is nil."
128   :type 'boolean
129   :group 'backup)
130
131 (defvar backup-enable-predicate
132   #'(lambda (name)
133      (not (or (null name)
134               (string-match "^/tmp/" name)
135               (let ((tmpdir (temp-directory)))
136                 (and tmpdir
137                      (string-match (concat "\\`" (regexp-quote tmpdir) "/")
138                                    tmpdir))))))
139   "Predicate that looks at a file name and decides whether to make backups.
140 Called with an absolute file name as argument, it returns t to enable backup.")
141
142 (defcustom buffer-offer-save nil
143   "*Non-nil in a buffer means offer to save the buffer on exit
144 even if the buffer is not visiting a file.
145 Automatically local in all buffers."
146   :type 'boolean
147   :group 'find-file)
148 (make-variable-buffer-local 'buffer-offer-save)
149
150 ;; FSF uses normal defconst
151 (defvaralias 'find-file-visit-truename 'find-file-use-truenames)
152 (defvaralias 'find-file-existing-other-name 'find-file-compare-truenames)
153
154 (defcustom revert-without-query nil
155   "*Specify which files should be reverted without query.
156 The value is a list of regular expressions.
157 If the file name matches one of these regular expressions,
158 then `revert-buffer' reverts the file without querying
159 if the file has changed on disk and you have not edited the buffer."
160   :type '(repeat (regexp ""))
161   :group 'find-file)
162
163 (defvar buffer-file-number nil
164   "The device number and file number of the file visited in the current buffer.
165 The value is a list of the form (FILENUM DEVNUM).
166 This pair of numbers uniquely identifies the file.
167 If the buffer is visiting a new file, the value is nil.")
168 (make-variable-buffer-local 'buffer-file-number)
169 (put 'buffer-file-number 'permanent-local t)
170
171 (defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
172   "Non-nil means that buffer-file-number uniquely identifies files.")
173
174 (defcustom file-precious-flag nil
175   "*Non-nil means protect against I/O errors while saving files.
176 Some modes set this non-nil in particular buffers.
177
178 This feature works by writing the new contents into a temporary file
179 and then renaming the temporary file to replace the original.
180 In this way, any I/O error in writing leaves the original untouched,
181 and there is never any instant where the file is nonexistent.
182
183 Note that this feature forces backups to be made by copying.
184 Yet, at the same time, saving a precious file
185 breaks any hard links between it and other files."
186   :type 'boolean
187   :group 'backup)
188
189 (defcustom version-control nil
190   "*Control use of version numbers for backup files.
191 t means make numeric backup versions unconditionally.
192 nil means make them for files that have some already.
193 `never' means do not make them."
194   :type 'boolean
195   :group 'backup
196   :group 'vc)
197
198 ;; This is now defined in efs.
199 ;(defvar dired-kept-versions 2
200 ;  "*When cleaning directory, number of versions to keep.")
201
202 (defcustom delete-old-versions (when noninteractive 'leave)
203   "*If t, delete excess backup versions silently.
204 If nil, ask confirmation.  Any other value prevents any trimming."
205   :type '(choice (const :tag "Delete" t)
206                  (const :tag "Ask" nil)
207                  (sexp :tag "Leave" :format "%t\n" other))
208   :group 'backup)
209
210 (defcustom kept-old-versions 2
211   "*Number of oldest versions to keep when a new numbered backup is made."
212   :type 'integer
213   :group 'backup)
214
215 (defcustom kept-new-versions 2
216   "*Number of newest versions to keep when a new numbered backup is made.
217 Includes the new backup.  Must be > 0"
218   :type 'integer
219   :group 'backup)
220
221 (defcustom require-final-newline nil
222   "*Value of t says silently ensure a file ends in a newline when it is saved.
223 Non-nil but not t says ask user whether to add a newline when there isn't one.
224 nil means don't add newlines."
225   :type '(choice (const :tag "Off" nil)
226                  (const :tag "Add" t)
227                  (sexp :tag "Ask" :format "%t\n" ask))
228   :group 'editing-basics)
229
230 (defcustom auto-save-default t
231   "*Non-nil says by default do auto-saving of every file-visiting buffer."
232   :type 'boolean
233   :group 'auto-save)
234
235 (defcustom auto-save-visited-file-name nil
236   "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
237 Normally auto-save files are written under other names."
238   :type 'boolean
239   :group 'auto-save)
240
241 (defcustom save-abbrevs nil
242   "*Non-nil means save word abbrevs too when files are saved.
243 Loading an abbrev file sets this to t."
244   :type 'boolean
245   :group 'abbrev)
246
247 (defcustom find-file-run-dired t
248   "*Non-nil says run dired if `find-file' is given the name of a directory."
249   :type 'boolean
250   :group 'find-file)
251
252 ;;;It is not useful to make this a local variable.
253 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
254 (defvar find-file-not-found-hooks nil
255   "List of functions to be called for `find-file' on nonexistent file.
256 These functions are called as soon as the error is detected.
257 `buffer-file-name' is already set up.
258 The functions are called in the order given until one of them returns non-nil.")
259
260 ;;;It is not useful to make this a local variable.
261 ;;;(put 'find-file-hooks 'permanent-local t)
262 (defvar find-file-hooks nil
263   "List of functions to be called after a buffer is loaded from a file.
264 The buffer's local variables (if any) will have been processed before the
265 functions are called.")
266
267 (defvar write-file-hooks nil
268   "List of functions to be called before writing out a buffer to a file.
269 If one of them returns non-nil, the file is considered already written
270 and the rest are not called.
271 These hooks are considered to pertain to the visited file.
272 So this list is cleared if you change the visited file name.
273 See also `write-contents-hooks' and `continue-save-buffer'.")
274 ;;; However, in case someone does make it local...
275 (put 'write-file-hooks 'permanent-local t)
276
277 (defvar local-write-file-hooks nil
278   "Just like `write-file-hooks', except intended for per-buffer use.
279 The functions in this list are called before the ones in
280 `write-file-hooks'.
281
282 This variable is meant to be used for hooks that have to do with a
283 particular visited file.  Therefore, it is a permanent local, so that
284 changing the major mode does not clear it.  However, calling
285 `set-visited-file-name' does clear it.")
286 (make-variable-buffer-local 'local-write-file-hooks)
287 (put 'local-write-file-hooks 'permanent-local t)
288
289
290 ;; #### think about this (added by Sun).
291 (put 'after-set-visited-file-name-hooks 'permanent-local t)
292 (defvar after-set-visited-file-name-hooks nil
293   "List of functions to be called after \\[set-visited-file-name]
294 or during \\[write-file].
295 You can use this hook to restore local values of `write-file-hooks',
296 `after-save-hook', and `revert-buffer-function', which pertain
297 to a specific file and therefore are normally killed by a rename.
298 Put hooks pertaining to the buffer contents on `write-contents-hooks'
299 and `revert-buffer-insert-file-contents-function'.")
300
301 (defvar write-contents-hooks nil
302   "List of functions to be called before writing out a buffer to a file.
303 If one of them returns non-nil, the file is considered already written
304 and the rest are not called.
305 These hooks are considered to pertain to the buffer's contents,
306 not to the particular visited file; thus, `set-visited-file-name' does
307 not clear this variable, but changing the major mode does clear it.
308 See also `write-file-hooks' and `continue-save-buffer'.")
309
310 ;;  XEmacs addition
311 ;;  Energize needed this to hook into save-buffer at a lower level; we need
312 ;;  to provide a new output method, but don't want to have to duplicate all
313 ;;  of the backup file and file modes logic.that does not occur if one uses
314 ;;  a write-file-hook which returns non-nil.
315 (put 'write-file-data-hooks 'permanent-local t)
316 (defvar write-file-data-hooks nil
317   "List of functions to be called to put the bytes on disk.
318 These functions receive the name of the file to write to as argument.
319 The default behavior is to call
320   (write-region (point-min) (point-max) filename nil t)
321 If one of them returns non-nil, the file is considered already written
322 and the rest are not called.
323 These hooks are considered to pertain to the visited file.
324 So this list is cleared if you change the visited file name.
325 See also `write-file-hooks'.")
326
327 (defcustom enable-local-variables t
328   "*Control use of local-variables lists in files you visit.
329 The value can be t, nil or something else.
330 A value of t means local-variables lists are obeyed;
331 nil means they are ignored; anything else means query.
332
333 The command \\[normal-mode] always obeys local-variables lists
334 and ignores this variable."
335   :type '(choice (const :tag "Obey" t)
336                  (const :tag "Ignore" nil)
337                  (sexp :tag "Query" :format "%t\n" other))
338   :group 'find-file)
339
340 (defcustom enable-local-eval 'maybe
341   "*Control processing of the \"variable\" `eval' in a file's local variables.
342 The value can be t, nil or something else.
343 A value of t means obey `eval' variables;
344 nil means ignore them; anything else means query.
345
346 The command \\[normal-mode] always obeys local-variables lists
347 and ignores this variable."
348   :type '(choice (const :tag "Obey" t)
349                  (const :tag "Ignore" nil)
350                  (sexp :tag "Query" :format "%t\n" other))
351   :group 'find-file)
352
353 ;;; SXEmacs addition
354 (defcustom find-file-magic-files-alist
355   '((file-directory-p . find-file-try-dired-noselect))
356   "Alist where each element is in form \(PREDICATE . FUNCTION-OF-ONE-ARGUMENT\).
357 FUNCTION-OF-ONE-ARGUMENT must return some buffer."
358   :type 'alist
359   :group 'find-file)
360
361 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
362 (or (fboundp 'lock-buffer)
363     (defalias 'lock-buffer 'ignore))
364 (or (fboundp 'unlock-buffer)
365     (defalias 'unlock-buffer 'ignore))
366 \f
367 ;;FSFmacs bastardized ange-ftp cruft
368 ;; This hook function provides support for ange-ftp host name
369 ;; completion.  It runs the usual ange-ftp hook, but only for
370 ;; completion operations.  Having this here avoids the need
371 ;; to load ange-ftp when it's not really in use.
372 ;(defun ange-ftp-completion-hook-function (op &rest args)
373 ;  (if (memq op '(file-name-completion file-name-all-completions))
374 ;      (apply 'ange-ftp-hook-function op args)
375 ;    (let ((inhibit-file-name-handlers
376 ;          (cons 'ange-ftp-completion-hook-function
377 ;                (and (eq inhibit-file-name-operation op)
378 ;                     inhibit-file-name-handlers)))
379 ;         (inhibit-file-name-operation op))
380 ;      (apply op args))
381
382 (defun convert-standard-filename (filename)
383   "Convert a standard file's name to something suitable for the current OS."
384   (if (eq system-type 'windows-nt)
385       (let ((name (copy-sequence filename))
386             (start 0))
387         ;; leave ':' if part of drive specifier
388         (if (and (> (length name) 1)
389                  (eq (aref name 1) ?:))
390             (setq start 2))
391         ;; destructively replace invalid filename characters with !
392         (while (string-match "[?*:<>|\"\000-\037]" name start)
393           (aset name (match-beginning 0) ?!)
394           (setq start (match-end 0)))
395         ;; FSF: [convert directory separators to Windows format ...]
396         ;; unneeded in XEmacs.
397         name)
398     filename))
399
400 \f
401 (defun pwd ()
402   "Show the current default directory."
403   (interactive nil)
404   (message "Directory %s" default-directory))
405
406 (defvar cd-path nil
407   "Value of the CDPATH environment variable, as a list.
408 Not actually set up until the first time you use it.")
409
410 (defvar cdpath-previous nil
411   "Prior value of the CDPATH environment variable.")
412
413 (defun parse-colon-path (cd-path)
414   "Explode a colon-separated search path into a list of directory names.
415
416 If you think you want to use this, you probably don't.  This function
417 is provided for backward compatibility.  A more robust implementation
418 of the same functionality is available as `split-path', which see."
419   (and cd-path
420        (let (cd-list (cd-start 0) cd-colon)
421          (setq cd-path (concat cd-path path-separator))
422          (while (setq cd-colon (string-match path-separator cd-path cd-start))
423            (setq cd-list
424                  (nconc cd-list
425                         (list (if (= cd-start cd-colon)
426                                    nil
427                                 (substitute-in-file-name
428                                  (file-name-as-directory
429                                   (substring cd-path cd-start cd-colon)))))))
430            (setq cd-start (+ cd-colon 1)))
431          cd-list)))
432
433 (defun cd-absolute (dir)
434   "Change current directory to given absolute file name DIR."
435   ;; Put the name into directory syntax now,
436   ;; because otherwise expand-file-name may give some bad results.
437   (setq dir (file-name-as-directory dir))
438   ;; XEmacs change: stig@hackvan.com
439   (if find-file-use-truenames
440       (setq dir (file-truename dir)))
441   (setq dir (abbreviate-file-name (expand-file-name dir)))
442   (cond ((not (file-directory-p dir))
443          (error "%s is not a directory" dir))
444         ;; this breaks ange-ftp, which doesn't (can't?) overload `file-executable-p'.
445         ;;((not (file-executable-p dir))
446         ;; (error "Cannot cd to %s:  Permission denied" dir))
447         (t
448          (setq default-directory dir))))
449
450 (defun cd (dir)
451   "Make DIR become the current buffer's default directory.
452 If your environment includes a `CDPATH' variable, try each one of that
453 colon-separated list of directories when resolving a relative directory name."
454   (interactive
455    ;; XEmacs change? (read-file-name => read-directory-name)
456    (list (read-directory-name "Change default directory: "
457                               default-directory default-directory
458                               (and (member cd-path '(nil ("./")))
459                                    (null (getenv "CDPATH"))))))
460   (if (file-name-absolute-p dir)
461       (cd-absolute (expand-file-name dir))
462     ;; XEmacs
463     (unless (and cd-path (equal (getenv "CDPATH") cdpath-previous))
464       ;;#### Unix-specific
465       (let ((trypath (parse-colon-path
466                       (setq cdpath-previous (getenv "CDPATH")))))
467         (setq cd-path (or trypath (list "./")))))
468     (or (catch 'found
469           (mapcar #'(lambda (x)
470                         (let ((f (expand-file-name (concat x dir))))
471                           (if (file-directory-p f)
472                               (progn
473                                 (cd-absolute f)
474                                 (throw 'found t)))))
475                   cd-path)
476           nil)
477         ;; jwz: give a better error message to those of us with the
478         ;; good taste not to use a kludge like $CDPATH.
479         (if (equal cd-path '("./"))
480             (error "No such directory: %s" (expand-file-name dir))
481           (error "Directory not found in $CDPATH: %s" dir)))))
482
483 (defun load-file (file)
484   "Load the Lisp file named FILE."
485   (interactive "fLoad file: ")
486   (load (expand-file-name file) nil nil t))
487
488 ; We now dump utils/lib-complete.el which has improved versions of this.
489 ;(defun load-library (library)
490 ;  "Load the library named LIBRARY.
491 ;This is an interface to the function `load'."
492 ;  (interactive "sLoad library: ")
493 ;  (load library))
494 ;
495 ;(defun find-library (library)
496 ;  "Find the library of Lisp code named LIBRARY.
497 ;This searches `load-path' for a file named either \"LIBRARY\" or \"LIBRARY.el\"."
498 ;  (interactive "sFind library file: ")
499 ;  (let ((f (locate-file library load-path ":.el:")))
500 ;    (if f
501 ;        (find-file f)
502 ;        (error "Couldn't locate library %s" library))))
503
504 (defun file-local-copy (file &optional buffer)
505   "Copy the file FILE into a temporary file on this machine.
506 Returns the name of the local copy, or nil, if FILE is directly
507 accessible."
508   (let ((handler (find-file-name-handler file 'file-local-copy)))
509     (if handler
510         (funcall handler 'file-local-copy file)
511       nil)))
512
513 ;; XEmacs change block
514 ; We have this in C and use the realpath() system call.
515
516 ;(defun file-truename (filename &optional counter prev-dirs)
517 ; [... lots of code snipped ...]
518 ;    filename))
519
520 ;; XEmacs addition.  Called from `insert-file-contents-internal'
521 ;; at the appropriate time.
522 (defun compute-buffer-file-truename (&optional buffer)
523   "Recompute BUFFER's value of `buffer-file-truename'
524 based on the current value of `buffer-file-name'.
525 BUFFER defaults to the current buffer if unspecified."
526   (save-excursion
527     (set-buffer (or buffer (current-buffer)))
528     (cond ((null buffer-file-name)
529            (setq buffer-file-truename nil))
530           ((setq buffer-file-truename (file-truename buffer-file-name))
531            ;; it exists, we're done.
532            nil)
533           (t
534            ;; the file doesn't exist, but maybe the directory does.
535            (let* ((dir (file-name-directory buffer-file-name))
536                   (truedir (file-truename dir)))
537              (if truedir (setq dir truedir))
538              (setq buffer-file-truename
539                    (expand-file-name (file-name-nondirectory buffer-file-name)
540                                      dir)))))
541     (if (and find-file-use-truenames buffer-file-truename)
542         (setq buffer-file-name (abbreviate-file-name buffer-file-truename)
543               default-directory (file-name-directory buffer-file-name)))
544     buffer-file-truename))
545 ;; End XEmacs change block
546
547 (defun file-chase-links (filename)
548   "Chase links in FILENAME until a name that is not a link.
549 Does not examine containing directories for links,
550 unlike `file-truename'."
551   (let (tem (count 100) (newname filename))
552     (while (setq tem (file-symlink-p newname))
553       (save-match-data
554         (if (= count 0)
555             (error "Apparent cycle of symbolic links for %s" filename))
556         ;; In the context of a link, `//' doesn't mean what XEmacs thinks.
557         (while (string-match "//+" tem)
558           (setq tem (concat (substring tem 0 (1+ (match-beginning 0)))
559                             (substring tem (match-end 0)))))
560         ;; Handle `..' by hand, since it needs to work in the
561         ;; target of any directory symlink.
562         ;; This code is not quite complete; it does not handle
563         ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
564         (while (string-match #r"\`\.\./" tem) ;#### Unix specific
565           (setq tem (substring tem 3))
566           (setq newname (file-name-as-directory
567                          ;; Do the .. by hand.
568                          (directory-file-name
569                           (file-name-directory
570                            ;; Chase links in the default dir of the symlink.
571                            (file-chase-links
572                             (directory-file-name
573                              (file-name-directory newname))))))))
574         (setq newname (expand-file-name tem (file-name-directory newname)))
575         (setq count (1- count))))
576     newname))
577 \f
578 (defun switch-to-other-buffer (arg)
579   "Switch to the previous buffer.  With a numeric arg, n, switch to the nth
580 most recent buffer.  With an arg of 0, buries the current buffer at the
581 bottom of the buffer stack."
582   (interactive "p")
583   (if (eq arg 0)
584       (bury-buffer (current-buffer)))
585   (switch-to-buffer
586    (if (<= arg 1) (other-buffer (current-buffer))
587      (nth (1+ arg) (buffer-list)))))
588
589 (defun switch-to-buffer-other-window (buffer)
590   "Select buffer BUFFER in another window."
591   (interactive "BSwitch to buffer in other window: ")
592   (let ((pop-up-windows t))
593     ;; XEmacs: this used to have (selected-frame) as the third argument,
594     ;; but this is obnoxious.  If the user wants the buffer in a
595     ;; different frame, then it should be this way.
596
597     ;; Change documented above undone --mrb
598     (pop-to-buffer buffer t (selected-frame))))
599
600 (defun switch-to-buffer-other-frame (buffer)
601   "Switch to buffer BUFFER in a newly-created frame."
602   (interactive "BSwitch to buffer in other frame: ")
603   (let* ((name (get-frame-name-for-buffer buffer))
604          (frame (make-frame (if name
605                                   (list (cons 'name (symbol-name name)))))))
606     (pop-to-buffer buffer t frame)
607     (make-frame-visible frame)
608     buffer))
609
610 (defun find-file (filename &optional codesys)
611   "Edit file FILENAME.
612 Switch to a buffer visiting file FILENAME,
613 creating one if none already exists.
614 Under XEmacs/Mule, optional second argument specifies the
615 coding system to use when decoding the file.  Interactively,
616 with a prefix argument, you will be prompted for the coding system."
617   (interactive "FFind file: \nZCoding system: ")
618   (if codesys
619       (let ((coding-system-for-read
620              (get-coding-system codesys)))
621         (switch-to-buffer (find-file-noselect filename)))
622     (switch-to-buffer (find-file-noselect filename))))
623
624 (defun find-file-other-window (filename &optional codesys)
625   "Edit file FILENAME, in another window.
626 May create a new window, or reuse an existing one.
627 See the function `display-buffer'.
628 Under XEmacs/Mule, optional second argument specifies the
629 coding system to use when decoding the file.  Interactively,
630 with a prefix argument, you will be prompted for the coding system."
631   (interactive "FFind file in other window: \nZCoding system: ")
632   (if codesys
633       (let ((coding-system-for-read
634              (get-coding-system codesys)))
635         (switch-to-buffer-other-window (find-file-noselect filename)))
636     (switch-to-buffer-other-window (find-file-noselect filename))))
637
638 (defun find-file-other-frame (filename &optional codesys)
639   "Edit file FILENAME, in a newly-created frame.
640 Under XEmacs/Mule, optional second argument specifies the
641 coding system to use when decoding the file.  Interactively,
642 with a prefix argument, you will be prompted for the coding system."
643   (interactive "FFind file in other frame: \nZCoding system: ")
644   (if codesys
645       (let ((coding-system-for-read
646              (get-coding-system codesys)))
647         (switch-to-buffer-other-frame (find-file-noselect filename)))
648     (switch-to-buffer-other-frame (find-file-noselect filename))))
649
650 (defun find-file-read-only (filename &optional codesys)
651   "Edit file FILENAME but don't allow changes.
652 Like \\[find-file] but marks buffer as read-only.
653 Use \\[toggle-read-only] to permit editing.
654 Under XEmacs/Mule, optional second argument specifies the
655 coding system to use when decoding the file.  Interactively,
656 with a prefix argument, you will be prompted for the coding system."
657   (interactive "fFind file read-only: \nZCoding system: ")
658   (if codesys
659       (let ((coding-system-for-read
660              (get-coding-system codesys)))
661         (find-file filename))
662     (find-file filename))
663   (setq buffer-read-only t)
664   (current-buffer))
665
666 (defun find-file-read-only-other-window (filename &optional codesys)
667   "Edit file FILENAME in another window but don't allow changes.
668 Like \\[find-file-other-window] but marks buffer as read-only.
669 Use \\[toggle-read-only] to permit editing.
670 Under XEmacs/Mule, optional second argument specifies the
671 coding system to use when decoding the file.  Interactively,
672 with a prefix argument, you will be prompted for the coding system."
673   (interactive "fFind file read-only other window: \nZCoding system: ")
674   (if codesys
675       (let ((coding-system-for-read
676              (get-coding-system codesys)))
677         (find-file-other-window filename))
678     (find-file-other-window filename))
679   (setq buffer-read-only t)
680   (current-buffer))
681
682 (defun find-file-read-only-other-frame (filename &optional codesys)
683   "Edit file FILENAME in another frame but don't allow changes.
684 Like \\[find-file-other-frame] but marks buffer as read-only.
685 Use \\[toggle-read-only] to permit editing.
686 Under XEmacs/Mule, optional second argument specifies the
687 coding system to use when decoding the file.  Interactively,
688 with a prefix argument, you will be prompted for the coding system."
689   (interactive "fFind file read-only other frame: \nZCoding system: ")
690   (if codesys
691       (let ((coding-system-for-read
692              (get-coding-system codesys)))
693         (find-file-other-frame filename))
694     (find-file-other-frame filename))
695   (setq buffer-read-only t)
696   (current-buffer))
697
698 (defun find-alternate-file-other-window (filename &optional codesys)
699   "Find file FILENAME as a replacement for the file in the next window.
700 This command does not select that window.
701 Under XEmacs/Mule, optional second argument specifies the
702 coding system to use when decoding the file.  Interactively,
703 with a prefix argument, you will be prompted for the coding system."
704   (interactive
705    (save-selected-window
706      (other-window 1)
707      (let ((file buffer-file-name)
708            (file-name nil)
709            (file-dir nil))
710        (and file
711             (setq file-name (file-name-nondirectory file)
712                   file-dir (file-name-directory file)))
713        (list (read-file-name
714               "Find alternate file: " file-dir nil nil file-name)
715              (if (and current-prefix-arg (featurep 'mule))
716                  (read-coding-system "Coding-system: "))))))
717   (if (one-window-p)
718       (find-file-other-window filename)
719     (save-selected-window
720       (other-window 1)
721       (find-alternate-file filename codesys))))
722
723 (defun find-alternate-file (filename &optional codesys)
724   "Find file FILENAME, select its buffer, kill previous buffer.
725 If the current buffer now contains an empty file that you just visited
726 \(presumably by mistake), use this command to visit the file you really want.
727 Under XEmacs/Mule, optional second argument specifies the
728 coding system to use when decoding the file.  Interactively,
729 with a prefix argument, you will be prompted for the coding system."
730   (interactive
731    (let ((file buffer-file-name)
732          (file-name nil)
733          (file-dir nil))
734      (and file
735           (setq file-name (file-name-nondirectory file)
736                 file-dir (file-name-directory file)))
737      (list (read-file-name
738             "Find alternate file: " file-dir nil nil file-name)
739            (if (and current-prefix-arg (featurep 'mule))
740                (read-coding-system "Coding-system: ")))))
741   (and (buffer-modified-p) (buffer-file-name)
742        ;; (not buffer-read-only)
743        (not (yes-or-no-p (format
744                           "Buffer %s is modified; kill anyway? "
745                           (buffer-name))))
746        (error "Aborted"))
747   (let ((obuf (current-buffer))
748         (ofile buffer-file-name)
749         (onum buffer-file-number)
750         (otrue buffer-file-truename)
751         (oname (buffer-name)))
752     (if (get-buffer " **lose**")
753         (kill-buffer " **lose**"))
754     (rename-buffer " **lose**")
755     (setq buffer-file-name nil)
756     (setq buffer-file-number nil)
757     (setq buffer-file-truename nil)
758     (unwind-protect
759         (progn
760           (unlock-buffer)
761           (if codesys
762               (let ((coding-system-for-read
763                      (get-coding-system codesys)))
764                 (find-file filename))
765             (find-file filename)))
766       (cond ((eq obuf (current-buffer))
767              (setq buffer-file-name ofile)
768              (setq buffer-file-number onum)
769              (setq buffer-file-truename otrue)
770              (lock-buffer)
771              (rename-buffer oname))))
772     (or (eq (current-buffer) obuf)
773         (kill-buffer obuf))))
774
775 (defun create-file-buffer (filename)
776   "Create a suitably named buffer for visiting FILENAME, and return it.
777 FILENAME (sans directory) is used unchanged if that name is free;
778 otherwise a string <2> or <3> or ... is appended to get an unused name."
779     (let ((handler (find-file-name-handler filename 'create-file-buffer)))
780       (if handler
781           (funcall handler 'create-file-buffer filename)
782         (let ((lastname (file-name-nondirectory filename)))
783           (if (string= lastname "")
784               (setq lastname filename))
785           (generate-new-buffer lastname)))))
786
787 (defun generate-new-buffer (name)
788   "Create and return a buffer with a name based on NAME.
789 Choose the buffer's name using `generate-new-buffer-name'."
790   (get-buffer-create (generate-new-buffer-name name)))
791
792 (defvar abbreviated-home-dir nil
793   "The user's homedir abbreviated according to `directory-abbrev-alist'.")
794
795 (defun abbreviate-file-name (filename &optional hack-homedir)
796   "Return a version of FILENAME shortened using `directory-abbrev-alist'.
797 See documentation of variable `directory-abbrev-alist' for more information.
798 If optional argument HACK-HOMEDIR is non-nil, then this also substitutes
799 \"~\" for the user's home directory."
800   (let ((handler (find-file-name-handler filename 'abbreviate-file-name)))
801     (if handler
802         (funcall handler 'abbreviate-file-name filename hack-homedir)
803       ;; Get rid of the prefixes added by the automounter.
804       ;;(if (and (string-match automount-dir-prefix filename)
805       ;;         (file-exists-p (file-name-directory
806       ;;                         (substring filename (1- (match-end 0))))))
807       ;;    (setq filename (substring filename (1- (match-end 0)))))
808       (let ((tail directory-abbrev-alist))
809         ;; If any elt of directory-abbrev-alist matches this name,
810         ;; abbreviate accordingly.
811         (while tail
812           (when (string-match (car (car tail)) filename)
813             (setq filename
814                   (concat (cdr (car tail)) (substring filename (match-end 0)))))
815           (setq tail (cdr tail))))
816       (when hack-homedir
817         ;; Compute and save the abbreviated homedir name.
818         ;; We defer computing this until the first time it's needed,
819         ;; to give time for directory-abbrev-alist to be set properly.
820         ;; We include the separator at the end, to avoid spurious
821         ;; matches such as `/usr/foobar' when the home dir is
822         ;; `/usr/foo'.
823         (or abbreviated-home-dir
824             (setq abbreviated-home-dir
825                   (let ((abbreviated-home-dir "$foo"))
826                     (concat "\\`"
827                             (regexp-quote
828                              (abbreviate-file-name (expand-file-name "~")))
829                             "\\("
830                             (regexp-quote (string directory-sep-char))
831                             #r"\|\'\)"))))
832         ;; If FILENAME starts with the abbreviated homedir,
833         ;; make it start with `~' instead.
834         (if (and (string-match abbreviated-home-dir filename)
835                  ;; If the home dir is just /, don't change it.
836                  (not (and (= (match-end 0) 1)
837                            (= (aref filename 0) directory-sep-char)))
838                  (not (and (eq system-type 'windows-nt)
839                            (save-match-data
840                              (string-match (concat "\\`[a-zA-Z]:"
841                                                    (regexp-quote
842                                                     (string directory-sep-char))
843                                                    "\\'")
844                                            filename)))))
845             (setq filename
846                   (concat "~"
847                           (match-string 1 filename)
848                           (substring filename (match-end 0))))))
849       filename)))
850
851 (defcustom find-file-not-true-dirname-list nil
852   "*List of logical names for which visiting shouldn't save the true dirname."
853   :type '(repeat (string :tag "Name"))
854   :group 'find-file)
855
856 ;; This function is needed by FSF vc.el.  I hope somebody can make it
857 ;; work for XEmacs.  -sb.
858 ;; #### In what way does it not work?  --hniksic
859 (defun find-buffer-visiting (filename)
860   "Return the buffer visiting file FILENAME (a string).
861 This is like `get-file-buffer', except that it checks for any buffer
862 visiting the same file, possibly under a different name.
863 If there is no such live buffer, return nil."
864   (let ((buf (get-file-buffer filename))
865         (truename (abbreviate-file-name (file-truename filename))))
866     (or buf
867         (let ((list (buffer-list)) found)
868           (while (and (not found) list)
869             (save-excursion
870               (set-buffer (car list))
871               (if (and buffer-file-name
872                        (string= buffer-file-truename truename))
873                   (setq found (car list))))
874             (setq list (cdr list)))
875           found)
876         (let ((number (nthcdr 10 (file-attributes truename)))
877               (list (buffer-list)) found)
878           (and buffer-file-numbers-unique
879                number
880                (while (and (not found) list)
881                  (save-excursion
882                    (set-buffer (car list))
883                    (if (and buffer-file-number
884                            (equal buffer-file-number number)
885                             ;; Verify this buffer's file number
886                             ;; still belongs to its file.
887                             (file-exists-p buffer-file-name)
888                             (equal (nthcdr 10 (file-attributes buffer-file-name))
889                                    number))
890                        (setq found (car list))))
891                  (setq list (cdr list))))
892           found))))
893
894 (defun insert-file-contents-literally (filename &optional visit start end replace)
895   "Like `insert-file-contents', q.v., but only reads in the file.
896 A buffer may be modified in several ways after reading into the buffer due
897 to advanced Emacs features, such as format decoding, character code
898 conversion, find-file-hooks, automatic uncompression, etc.
899
900   This function ensures that none of these modifications will take place."
901   (let ((wrap-func (find-file-name-handler filename
902                                            'insert-file-contents-literally)))
903     (if wrap-func
904         (funcall wrap-func 'insert-file-contents-literally filename
905                  visit start end replace)
906       (let ((file-name-handler-alist nil)
907             (format-alist nil)
908             (after-insert-file-functions nil)
909             (coding-system-for-read 'binary)
910             (coding-system-for-write 'binary)
911             (find-buffer-file-type-function
912              (if (fboundp 'find-buffer-file-type)
913                  (symbol-function 'find-buffer-file-type)
914                nil)))
915         (unwind-protect
916             (progn
917               (fset 'find-buffer-file-type (lambda (filename) t))
918               (insert-file-contents filename visit start end replace))
919           (if find-buffer-file-type-function
920               (fset 'find-buffer-file-type find-buffer-file-type-function)
921             (fmakunbound 'find-buffer-file-type)))))))
922
923 (defun find-file-try-dired-noselect (filename)
924   "Try to use dired to open FILENAME, which is directory."
925   (if (and (fboundp 'dired-noselect) find-file-run-dired)
926       (dired-noselect (if find-file-use-truenames
927                           (abbreviate-file-name (file-truename filename))
928                         filename))
929     (error "%s is a directory" filename)))
930
931 (defun find-file-find-magic (filename)
932   "Find entry in `find-file-magic-files-alist' that matches FILENAME."
933   (find filename find-file-magic-files-alist :key #'car
934         :test #'(lambda (fn predicate)
935                   (funcall predicate fn))))
936
937 (defun find-file-noselect (filename &optional nowarn rawfile)
938   "Read file FILENAME into a buffer and return the buffer.
939 If a buffer exists visiting FILENAME, return that one, but
940 verify that the file has not changed since visited or saved.
941 The buffer is not selected, just returned to the caller.
942 If NOWARN is non-nil, warning messages will be suppressed.
943 If RAWFILE is non-nil, the file is read literally."
944   (setq filename (abbreviate-file-name (expand-file-name filename)))
945   ;; Try magic files first
946   (let ((mfa-item (find-file-find-magic filename)))
947     (if mfa-item
948         (funcall (cdr mfa-item) filename)
949
950       (let* ((buf (get-file-buffer filename))
951              (truename (abbreviate-file-name (file-truename filename)))
952              (number (nthcdr 10 (file-attributes truename)))
953 ;          ;; Find any buffer for a file which has same truename.
954 ;          (other (and (not buf) (find-buffer-visiting filename)))
955              (error nil))
956
957 ;     ;; Let user know if there is a buffer with the same truename.
958 ;      (if (and (not buf) same-truename (not nowarn))
959 ;         (message "%s and %s are the same file (%s)"
960 ;                  filename (buffer-file-name same-truename)
961 ;                  truename)
962 ;       (if (and (not buf) same-number (not nowarn))
963 ;         (message "%s and %s are the same file"
964 ;                  filename (buffer-file-name same-number))))
965 ;      ;; Optionally also find that buffer.
966 ;      (if (or find-file-existing-other-name find-file-visit-truename)
967 ;         (setq buf (or same-truename same-number)))
968
969         (when (and buf
970                    (or find-file-compare-truenames find-file-use-truenames)
971                    (not nowarn))
972           (save-excursion
973             (set-buffer buf)
974             (if (not (string-equal buffer-file-name filename))
975                 (message "%s and %s are the same file (%s)"
976                          filename buffer-file-name
977                          buffer-file-truename))))
978
979         (if buf
980             (or nowarn
981                 (verify-visited-file-modtime buf)
982                 (cond ((not (file-exists-p filename))
983                        (error "File %s no longer exists!" filename))
984                       ;; Certain files should be reverted automatically
985                       ;; if they have changed on disk and not in the buffer.
986                       ((and (not (buffer-modified-p buf))
987                             (dolist (rx revert-without-query nil)
988                               (when (string-match rx filename)
989                                 (return t))))
990                        (with-current-buffer buf
991                          (message "Reverting file %s..." filename)
992                          (revert-buffer t t)
993                          (message "Reverting file %s... done" filename)))
994                       ((yes-or-no-p
995                         (if (string= (file-name-nondirectory filename)
996                                      (buffer-name buf))
997                             (format
998                              (if (buffer-modified-p buf)
999                                  (gettext "File %s changed on disk.  Discard your edits? ")
1000                                (gettext "File %s changed on disk.  Reread from disk? "))
1001                              (file-name-nondirectory filename))
1002                           (format
1003                            (if (buffer-modified-p buf)
1004                                (gettext "File %s changed on disk.  Discard your edits in %s? ")
1005                              (gettext "File %s changed on disk.  Reread from disk into %s? "))
1006                            (file-name-nondirectory filename)
1007                            (buffer-name buf))))
1008                        (with-current-buffer buf
1009                          (revert-buffer t t)))))
1010           ;; Else: we must create a new buffer for filename
1011           (save-excursion
1012 ;;; The truename stuff makes this obsolete.
1013 ;;;       (let* ((link-name (car (file-attributes filename)))
1014 ;;;              (linked-buf (and (stringp link-name)
1015 ;;;                               (get-file-buffer link-name))))
1016 ;;;         (if (bufferp linked-buf)
1017 ;;;             (message "Symbolic link to file in buffer %s"
1018 ;;;                      (buffer-name linked-buf))))
1019             (setq buf (create-file-buffer filename))
1020             ;; Catch various signals, such as QUIT, and kill the buffer
1021             ;; in that case.
1022             (condition-case data
1023                 (progn
1024                   (set-buffer-major-mode buf)
1025                   (set-buffer buf)
1026                   (erase-buffer)
1027                   (condition-case ()
1028                       (if rawfile
1029                           (insert-file-contents-literally filename t)
1030                         (insert-file-contents filename t))
1031                     (file-error
1032                      (when (and (file-exists-p filename)
1033                                 (not (file-readable-p filename)))
1034                        (signal 'file-error (list "File is not readable" filename)))
1035                      (if rawfile
1036                          ;; Unconditionally set error
1037                          (setq error t)
1038                        (or
1039                         ;; Run find-file-not-found-hooks until one returns non-nil.
1040                         (run-hook-with-args-until-success 'find-file-not-found-hooks)
1041                         ;; If they fail too, set error.
1042                         (setq error t)))))
1043                   ;; Find the file's truename, and maybe use that as visited name.
1044                   ;; automatically computed in XEmacs, unless jka-compr was used!
1045                   (unless buffer-file-truename
1046                     (setq buffer-file-truename truename))
1047                   (setq buffer-file-number number)
1048                   (and find-file-use-truenames
1049                        ;; This should be in C.  Put pathname
1050                        ;; abbreviations that have been explicitly
1051                        ;; requested back into the pathname.  Most
1052                        ;; importantly, strip out automounter /tmp_mnt
1053                        ;; directories so that auto-save will work
1054                        (setq buffer-file-name (abbreviate-file-name buffer-file-name)))
1055                   ;; Set buffer's default directory to that of the file.
1056                   (setq default-directory (file-name-directory buffer-file-name))
1057                   ;; Turn off backup files for certain file names.  Since
1058                   ;; this is a permanent local, the major mode won't eliminate it.
1059                   (and (not (funcall backup-enable-predicate buffer-file-name))
1060                        (progn
1061                          (make-local-variable 'backup-inhibited)
1062                          (setq backup-inhibited t)))
1063                   (if rawfile
1064                       ;; #### FSF 20.3 sets buffer-file-coding-system to
1065                       ;; `no-conversion' here.  Should we copy?  It also
1066                       ;; makes `find-file-literally' a local variable
1067                       ;; and sets it to t.
1068                       nil
1069                     (after-find-file error (not nowarn))
1070                     (setq buf (current-buffer))))
1071               (t
1072                (kill-buffer buf)
1073                (signal (car data) (cdr data))))
1074             ))
1075         buf))))
1076 \f
1077 ;; FSF has `insert-file-literally' and `find-file-literally' here.
1078
1079 (defvar after-find-file-from-revert-buffer nil)
1080
1081 (defun after-find-file (&optional error warn noauto
1082                                   after-find-file-from-revert-buffer
1083                                   nomodes)
1084   "Called after finding a file and by the default revert function.
1085 Sets buffer mode, parses local variables.
1086 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
1087 error in reading the file.  WARN non-nil means warn if there
1088 exists an auto-save file more recent than the visited file.
1089 NOAUTO means don't mess with auto-save mode.
1090 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1091  means this call was from `revert-buffer'.
1092 Fifth arg NOMODES non-nil means don't alter the file's modes.
1093 Finishes by calling the functions in `find-file-hooks'."
1094   (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1095   (if noninteractive
1096       nil
1097     (let* (not-serious
1098            (msg
1099             (cond ((and error (file-attributes buffer-file-name))
1100                    (setq buffer-read-only t)
1101                    (gettext "File exists, but cannot be read."))
1102                   ((not buffer-read-only)
1103                    (if (and warn
1104                             (file-newer-than-file-p (make-auto-save-file-name)
1105                                                     buffer-file-name))
1106                        (format "%s has auto save data; consider M-x recover-file"
1107                                (file-name-nondirectory buffer-file-name))
1108                      (setq not-serious t)
1109                      (if error (gettext "(New file)") nil)))
1110                   ((not error)
1111                    (setq not-serious t)
1112                    (gettext "Note: file is write protected"))
1113                   ((file-attributes (directory-file-name default-directory))
1114                    (gettext "File not found and directory write-protected"))
1115                   ((file-exists-p (file-name-directory buffer-file-name))
1116                    (setq buffer-read-only nil))
1117                   (t
1118                    ;; If the directory the buffer is in doesn't exist,
1119                    ;; offer to create it.  It's better to do this now
1120                    ;; than when we save the buffer, because we want
1121                    ;; autosaving to work.
1122                    (setq buffer-read-only nil)
1123                    ;; XEmacs
1124                    (or (file-exists-p (file-name-directory buffer-file-name))
1125                        (condition-case nil
1126                            (if (yes-or-no-p
1127                                 (format
1128                                  "The directory containing %s does not exist.  Create? "
1129                                  (abbreviate-file-name buffer-file-name)))
1130                                (make-directory (file-name-directory
1131                                                 buffer-file-name)
1132                                                t))
1133                          (quit
1134                           (kill-buffer (current-buffer))
1135                           (signal 'quit nil))))
1136                    nil))))
1137       (when msg
1138         (message "%s" msg)
1139         (unless not-serious
1140           (save-excursion (sit-for 1 t)))))
1141     (if (and auto-save-default (not noauto))
1142         (auto-save-mode t)))
1143   (unless nomodes
1144     (normal-mode t)
1145     (run-hooks 'find-file-hooks)))
1146
1147 (defun normal-mode (&optional find-file)
1148   "Choose the major mode for this buffer automatically.
1149 Also sets up any specified local variables of the file.
1150 Uses the visited file name, the -*- line, and the local variables spec.
1151
1152 This function is called automatically from `find-file'.  In that case,
1153 we may set up specified local variables depending on the value of
1154 `enable-local-variables': if it is t, we do; if it is nil, we don't;
1155 otherwise, we query.  `enable-local-variables' is ignored if you
1156 run `normal-mode' explicitly."
1157   (interactive)
1158   (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1159   (and (condition-case err
1160            (progn (set-auto-mode)
1161                   t)
1162          (error (message "File mode specification error: %s"
1163                          (prin1-to-string err))
1164                 nil))
1165        (condition-case err
1166            (hack-local-variables (not find-file))
1167          (error (lwarn 'local-variables 'warning
1168                   "File local-variables error: %s"
1169                   (error-message-string err))))))
1170
1171 ;; `auto-mode-alist' used to contain entries for modes in core and in packages.
1172 ;; The applicable entries are now located in the corresponding modes in
1173 ;; packages, the ones here are for core modes.  Ditto for
1174 ;; `interpreter-mode-alist' below.
1175 ;; Per Abrahamsen suggested splitting auto-mode-alist to
1176 ;; several distinct variables such as, in order of precedence,
1177 ;; `user-auto-mode-alist' for users, `package-auto-mode-alist' for
1178 ;; packages and `auto-mode-alist' (which might also be called
1179 ;; `default-auto-mode-alist') for default stuff, such as some of the
1180 ;; entries below.
1181
1182 (defvar auto-mode-alist
1183   '((#r"\.te?xt\'" . text-mode)
1184     (#r"\.el\'" . emacs-lisp-mode)
1185     (#r"\.c?l\(?:i?sp\)?\'" . lisp-mode)
1186     (#r"\.article\'" . text-mode)
1187     (#r"\.letter\'" . text-mode)
1188     ;; Mailer puts message to be edited in /tmp/Re.... or Message
1189     ;; #### Unix-specific!
1190     ("\\`/tmp/Re" . text-mode)
1191     ("/Message[0-9]*\\'" . text-mode)
1192     ;; some news reader is reported to use this
1193     ("^/tmp/fol/" . text-mode)
1194     ;; .emacs following a directory delimiter in either Unix or
1195     ;; Windows syntax.
1196     (#r"[/\][._].*emacs\'" . emacs-lisp-mode)
1197     (#r"\.ml\'" . lisp-mode)
1198     )
1199 "Alist of filename patterns vs. corresponding major mode functions.
1200 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1201 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1202 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1203 mode function to use.  FUNCTION will be called, unless it is nil.
1204
1205 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1206 calling FUNCTION (if it's not nil), we delete the suffix that matched
1207 REGEXP and search the list again for another match.")
1208
1209 (defvar interpreter-mode-alist
1210   '(("emacs" . emacs-lisp-mode))
1211   "Alist mapping interpreter names to major modes.
1212 This alist is used to guess the major mode of a file based on the
1213 contents of the first line.  This line often contains something like:
1214 #!/bin/sh
1215 but may contain something more imaginative like
1216 #! /bin/env python
1217 or
1218 eval 'exec perl -w -S $0 ${1+\"$@\"}'.
1219
1220 Each alist element looks like (INTERPRETER . MODE).
1221 The car of each element is a regular expression which is compared
1222 with the name of the interpreter specified in the first line.
1223 If it matches, mode MODE is selected.")
1224
1225 (defvar binary-file-regexps
1226   '(#r"\.\(?:7[Zz]\|ARC\|E\(?:AR\|XE\)\|GIF\|J\(?:AR\|P\(?:E?G\)\)\|LZH\|PDF\|RAR\|WAR\|XPI\|Z\(?:IP\|OO\)\|arc\|bz2\|doc\|e\(?:ar\|lc\|xe\)\|g\(?:if\|z\)\|j\(?:ar\|p\(?:e?g\)\)\|l\(?:ha\|z\(?:h\|ma\)\)\|odt\|p\(?:bm\|df\|gm\|n[gm]\|pm\)\|s\(?:o\|x[cdimw]\)\|t\(?:ar\|gz\|iff\)\|war\|x\(?:pi\|z\)\|z\(?:ip\|oo\)\|[Zao]\)\'")
1227   "List of regexps of filenames containing binary (non-text) data.")
1228
1229 ;(eval-when-compile
1230 ;  (require 'regexp-opt)
1231 ;  (list
1232 ;   (format "\\.\\(?:%s\\)\\'"
1233 ;          (regexp-opt
1234 ;           '(
1235 ;             ;; Compressed files
1236 ;             "7Z" "7z" "ARC" "EAR" "JAR" "LZH" "RAR" "WAR"
1237 ;             "XPI" "Z" "ZIP" "ZOO" "arc" "bz2" "ear" "gz"
1238 ;             "jar" "tar" "tgz" "tiff" "war" "xpi" "zip" "zoo"
1239 ;             "zoo" "lha" "lzh" "lzma" "xz"
1240 ;             ;; Code
1241 ;             "EXE" "exe" "elc" "o" "so" "a"
1242 ;             ;; Images
1243 ;             "gif" "jpeg" "jpg" "pbm" "pgm" "png" "pnm" "ppm"
1244 ;             "GIF" "JPEG" "JPG"
1245 ;             ;; Documents
1246 ;             "PDF" "odt" "pdf" "sxc" "sxd" "sxi" "sxm" "sxw" "doc")))))
1247
1248 (defvar inhibit-first-line-modes-regexps
1249   binary-file-regexps
1250   "List of regexps; if one matches a file name, don't look for `-*-'.")
1251
1252 (defvar inhibit-first-line-modes-suffixes nil
1253   "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1254 When checking `inhibit-first-line-modes-regexps', we first discard
1255 from the end of the file name anything that matches one of these regexps.")
1256
1257 (defvar user-init-file
1258   nil ; set by command-line
1259   "File name including directory of user's initialization file.
1260
1261 This normally defaults to \"~/.sxemacs/init.el\", if you are a XEmacs
1262 user you can get up and running quickly by symlinking \"~/.sxemacs\"
1263 to your old \"~/.xemacs\" directory.")
1264
1265 (defun set-auto-mode (&optional just-from-file-name)
1266   "Select major mode appropriate for current buffer.
1267 This checks for a -*- mode tag in the buffer's text,
1268 compares the filename against the entries in `auto-mode-alist',
1269 or checks the interpreter that runs this file against
1270 `interpreter-mode-alist'.
1271
1272 It does not check for the `mode:' local variable in the
1273 Local Variables section of the file; for that, use `hack-local-variables'.
1274
1275 If `enable-local-variables' is nil, this function does not check for a
1276 -*- mode tag.
1277
1278 If the optional argument JUST-FROM-FILE-NAME is non-nil,
1279 then we do not set anything but the major mode,
1280 and we don't even do that unless it would come from the file name."
1281   (save-excursion
1282     ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1283     ;; Do this by calling the hack-local-variables helper to avoid redundancy.
1284     ;; We bind enable-local-variables to nil this time because we're going to
1285     ;; call hack-local-variables-prop-line again later, "for real."  Note that
1286     ;; this temporary binding does not prevent hack-local-variables-prop-line
1287     ;; from setting the major mode.
1288     (or (and enable-local-variables
1289              (let ((enable-local-variables nil))
1290                (hack-local-variables-prop-line nil))
1291              )
1292         ;; It's not in the -*- line, so check the auto-mode-alist, unless
1293         ;; this buffer isn't associated with a file.
1294         (null buffer-file-name)
1295         (let ((name (file-name-sans-versions buffer-file-name))
1296               (keep-going t))
1297           (while keep-going
1298             (setq keep-going nil)
1299             (let ((alist auto-mode-alist)
1300                   (mode nil))
1301
1302               ;; Find first matching alist entry.
1303
1304               ;; #### This is incorrect. In NT, case sensitivity is a volume
1305               ;; property. For instance, NFS mounts *are* case sensitive.
1306               ;; Need internal function (file-name-case-sensitive f), F
1307               ;; being file or directory name. - kkm
1308               (let ((case-fold-search
1309                      (eq system-type 'windows-nt)))
1310                 (while (and (not mode) alist)
1311                   (if (string-match (car (car alist)) name)
1312                       (if (and (consp (cdr (car alist)))
1313                                (nth 2 (car alist)))
1314                           (progn
1315                             (setq mode (car (cdr (car alist)))
1316                                   name (substring name 0 (match-beginning 0))
1317                                   keep-going t))
1318                         (setq mode (cdr (car alist))
1319                               keep-going nil)))
1320                   (setq alist (cdr alist))))
1321               (unless just-from-file-name
1322                 ;; If we can't deduce a mode from the file name,
1323                 ;; look for an interpreter specified in the first line.
1324                 (if (and (null mode)
1325                          (save-excursion ; XEmacs
1326                            (goto-char (point-min))
1327                            (looking-at "#!")))
1328                     (let ((firstline
1329                            (buffer-substring
1330                             (point-min)
1331                             (save-excursion
1332                               (goto-char (point-min)) (end-of-line) (point)))))
1333                       (setq alist interpreter-mode-alist)
1334                       (while alist
1335                         (if (string-match (car (car alist)) firstline)
1336                             (progn
1337                               (setq mode (cdr (car alist)))
1338                               (setq alist nil))
1339                           (setq alist (cdr alist)))))))
1340               (if mode
1341                   (if (not (fboundp mode))
1342                       (let ((name (declare-fboundp (package-get-package-provider mode))))
1343                         (if name
1344                             (message "Mode %s is not installed.  Download package %s" mode name)
1345                           (message "Mode %s either doesn't exist or is not a known package" mode))
1346                         (sit-for 2)
1347                         (error "%s" mode))
1348                     (unless (and just-from-file-name
1349                                  (or
1350                                   ;; Don't reinvoke major mode.
1351                                   (eq mode major-mode)
1352                                   ;; Don't lose on minor modes.
1353                                   (assq mode minor-mode-alist)))
1354                       (funcall mode))))))))))
1355
1356 (defvar hack-local-variables-hook nil
1357   "Normal hook run after processing a file's local variables specs.
1358 Major modes can use this to examine user-specified local variables
1359 in order to initialize other data structure based on them.
1360
1361 This hook runs even if there were no local variables or if their
1362 evaluation was suppressed.  See also `enable-local-variables' and
1363 `enable-local-eval'.")
1364
1365 (defun hack-local-variables (&optional force)
1366   "Parse, and bind or evaluate as appropriate, any local variables
1367 for current buffer."
1368   ;; Don't look for -*- if this file name matches any
1369   ;; of the regexps in inhibit-first-line-modes-regexps.
1370   (if (or (null buffer-file-name) ; don't lose if buffer has no file!
1371           (not (let ((temp inhibit-first-line-modes-regexps)
1372                      (name (if buffer-file-name
1373                                (file-name-sans-versions buffer-file-name)
1374                              (buffer-name))))
1375                  (while (let ((sufs inhibit-first-line-modes-suffixes))
1376                           (while (and sufs (not
1377                                             (string-match (car sufs) name)))
1378                             (setq sufs (cdr sufs)))
1379                           sufs)
1380                    (setq name (substring name 0 (match-beginning 0))))
1381                  (while (and temp
1382                              (not (string-match (car temp) name)))
1383                    (setq temp (cdr temp))
1384                    temp))))
1385       (progn
1386         ;; Look for variables in the -*- line.
1387         (hack-local-variables-prop-line force)
1388         ;; Look for "Local variables:" block in last page.
1389         (hack-local-variables-last-page force)))
1390   (run-hooks 'hack-local-variables-hook))
1391
1392 ;;; Local variables may be specified in the last page of the file (within 3k
1393 ;;; from the end of the file and after the last ^L) in the form
1394 ;;;
1395 ;;;   Local variables:
1396 ;;;   variable-name: variable-value
1397 ;;;   end:
1398 ;;;
1399 ;;; The lines may begin with a common prefix, like ";;;   " in the above
1400 ;;; example.  They may also have a common suffix (" */" for example).  In
1401 ;;; this form, the local variable "mode" can be used to change the major
1402 ;;; mode, and the local variable "eval" can be used to evaluate an arbitrary
1403 ;;; form.
1404 ;;;
1405 ;;; Local variables may also be specified in the first line of the file.
1406 ;;; Embedded in this line are a pair of "-*-" sequences.  What lies between
1407 ;;; them are variable-name/variable-value pairs, like:
1408 ;;;
1409 ;;;      -*- mode: emacs-lisp -*-
1410 ;;; or   -*- mode: postscript; version-control: never -*-
1411 ;;; or   -*- tags-file-name: "/foo/bar/TAGS" -*-
1412 ;;;
1413 ;;; The local variable "eval" is not used with this form. For hysterical
1414 ;;; reasons, the syntax "-*- modename -*-" is allowed as well.
1415 ;;;
1416
1417 (defun hack-local-variables-p (modeline)
1418   (or (eq enable-local-variables t)
1419       (and enable-local-variables
1420            (save-window-excursion
1421              (condition-case nil
1422                  (switch-to-buffer (current-buffer))
1423                (error
1424                 ;; If we fail to switch in the selected window,
1425                 ;; it is probably a minibuffer.
1426                 ;; So try another window.
1427                 (condition-case nil
1428                     (switch-to-buffer-other-window (current-buffer))
1429                   (error
1430                    (switch-to-buffer-other-frame (current-buffer))))))
1431              (or modeline (save-excursion
1432                              (beginning-of-line)
1433                              (set-window-start (selected-window) (point))))
1434              (y-or-n-p (format
1435                         "Set local variables as specified %s of %s? "
1436                         (if modeline "in -*- line" "at end")
1437                         (if buffer-file-name
1438                             (file-name-nondirectory buffer-file-name)
1439                             (concat "buffer " (buffer-name)))))))))
1440
1441 (defun hack-local-variables-last-page (&optional force)
1442   ;; Set local variables set in the "Local Variables:" block of the last page.
1443   (save-excursion
1444     (goto-char (point-max))
1445     (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1446     (if (let ((case-fold-search t))
1447           (and (search-forward "Local Variables:" nil t)
1448                (or force
1449                    (hack-local-variables-p nil))))
1450         (let ((continue t)
1451               prefix prefixlen suffix start
1452               (enable-local-eval enable-local-eval))
1453           ;; The prefix is what comes before "local variables:" in its line.
1454           ;; The suffix is what comes after "local variables:" in its line.
1455           (skip-chars-forward " \t")
1456           (or (eolp)
1457               (setq suffix (buffer-substring (point)
1458                                              (progn (end-of-line) (point)))))
1459           (goto-char (match-beginning 0))
1460           (or (bolp)
1461               (setq prefix
1462                     (buffer-substring (point)
1463                                       (progn (beginning-of-line) (point)))))
1464           (if prefix (setq prefixlen (length prefix)
1465                            prefix (regexp-quote prefix)))
1466           (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1467           (while continue
1468             ;; Look at next local variable spec.
1469             (if selective-display (re-search-forward "[\n\C-m]")
1470               (forward-line 1))
1471             ;; Skip the prefix, if any.
1472             (if prefix
1473                 (if (looking-at prefix)
1474                     (forward-char prefixlen)
1475                   (error "Local variables entry is missing the prefix")))
1476             ;; Find the variable name; strip whitespace.
1477             (skip-chars-forward " \t")
1478             (setq start (point))
1479             (skip-chars-forward "^:\n")
1480             (if (eolp) (error "Missing colon in local variables entry"))
1481             (skip-chars-backward " \t")
1482             (let* ((str (buffer-substring start (point)))
1483                    (var (read str))
1484                   val)
1485               ;; Setting variable named "end" means end of list.
1486               (if (string-equal (downcase str) "end")
1487                   (setq continue nil)
1488                 ;; Otherwise read the variable value.
1489                 (skip-chars-forward "^:")
1490                 (forward-char 1)
1491                 (setq val (read (current-buffer)))
1492                 (skip-chars-backward "\n")
1493                 (skip-chars-forward " \t")
1494                 (or (if suffix (looking-at suffix) (eolp))
1495                     (error "Local variables entry is terminated incorrectly"))
1496                 ;; Set the variable.  "Variables" mode and eval are funny.
1497                 (hack-one-local-variable var val))))))))
1498
1499 ;; jwz - New Version 20.1/19.15
1500 (defun hack-local-variables-prop-line (&optional force)
1501   ;; Set local variables specified in the -*- line.
1502   ;; Returns t if mode was set.
1503   (let ((result nil))
1504     (save-excursion
1505       (goto-char (point-min))
1506       (skip-chars-forward " \t\n\r")
1507       (let ((end (save-excursion
1508                    ;; If the file begins with "#!"
1509                    ;; (un*x exec interpreter magic), look
1510                    ;; for mode frobs in the first two
1511                    ;; lines.  You cannot necessarily
1512                    ;; put them in the first line of
1513                    ;; such a file without screwing up
1514                    ;; the interpreter invocation.
1515                    (end-of-line (and (looking-at "^#!") 2))
1516                    (point))))
1517         ;; Parse the -*- line into the `result' alist.
1518         (cond ((not (search-forward "-*-" end t))
1519                ;; doesn't have one.
1520                (setq force t))
1521               ((looking-at "[ \t]*\\([^ \t\n\r:;]+?\\)\\([ \t]*-\\*-\\)")
1522                ;; Antiquated form: "-*- ModeName -*-".
1523                (setq result
1524                      (list (cons 'mode
1525                                  (intern (buffer-substring
1526                                           (match-beginning 1)
1527                                           (match-end 1)))))
1528                      ))
1529               (t
1530                ;; Usual form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1531                ;; (last ";" is optional).
1532                (save-excursion
1533                  (if (search-forward "-*-" end t)
1534                      (setq end (- (point) 3))
1535                    (error "-*- not terminated before end of line")))
1536                (while (< (point) end)
1537                  (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1538                      (error "malformed -*- line"))
1539                  (goto-char (match-end 0))
1540                  ;; There used to be a downcase here,
1541                  ;; but the manual didn't say so,
1542                  ;; and people want to set var names that aren't all lc.
1543                  (let ((key (intern (buffer-substring
1544                                      (match-beginning 1)
1545                                      (match-end 1))))
1546                        (val (save-restriction
1547                               (narrow-to-region (point) end)
1548                               (read (current-buffer)))))
1549                    ;; Case sensitivity!  Icepicks in my forehead!
1550                    (if (equal (downcase (symbol-name key)) "mode")
1551                        (setq key 'mode))
1552                    (setq result (cons (cons key val) result))
1553                    (skip-chars-forward " \t;")))
1554                (setq result (nreverse result))))))
1555
1556     (let ((set-any-p (or force
1557                          ;; It's OK to force null specifications.
1558                          (null result)
1559                          ;; It's OK to force mode-only specifications.
1560                          (let ((remaining result)
1561                                (mode-specs-only t))
1562                            (while remaining
1563                              (if (eq (car (car remaining)) 'mode)
1564                                  (setq remaining (cdr remaining))
1565                                ;; Otherwise, we have a real local.
1566                                (setq mode-specs-only nil
1567                                      remaining nil))
1568                              )
1569                            mode-specs-only)
1570                          ;; Otherwise, check.
1571                          (hack-local-variables-p t)))
1572           (mode-p nil))
1573       (while result
1574         (let ((key (car (car result)))
1575               (val (cdr (car result))))
1576           (cond ((eq key 'mode)
1577                  (setq mode-p t)
1578                  (let ((mode (intern (concat (downcase (symbol-name val))
1579                                              "-mode"))))
1580                    ;; Without this guard, `normal-mode' would potentially run
1581                    ;; the major mode function twice: once via `set-auto-mode'
1582                    ;; and once via `hack-local-variables'.
1583                    (if (not (eq mode major-mode))
1584                        (funcall mode))
1585                    ))
1586                 (set-any-p
1587                  (hack-one-local-variable key val))
1588                 (t
1589                  nil)))
1590         (setq result (cdr result)))
1591       mode-p)))
1592
1593 (defconst ignored-local-variables
1594   (list 'enable-local-eval)
1595   "Variables to be ignored in a file's local variable spec.")
1596
1597 ;; Get confirmation before setting these variables as locals in a file.
1598 (put 'debugger 'risky-local-variable t)
1599 (put 'enable-local-eval 'risky-local-variable t)
1600 (put 'ignored-local-variables 'risky-local-variable t)
1601 (put 'eval 'risky-local-variable t)
1602 (put 'file-name-handler-alist 'risky-local-variable t)
1603 (put 'minor-mode-map-alist 'risky-local-variable t)
1604 (put 'after-load-alist 'risky-local-variable t)
1605 (put 'buffer-file-name 'risky-local-variable t)
1606 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1607 (put 'buffer-file-truename 'risky-local-variable t)
1608 (put 'exec-path 'risky-local-variable t)
1609 (put 'load-path 'risky-local-variable t)
1610 (put 'exec-directory 'risky-local-variable t)
1611 (put 'process-environment 'risky-local-variable t)
1612 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1613 (put 'outline-level 'risky-local-variable t)
1614 (put 'rmail-output-file-alist 'risky-local-variable t)
1615
1616 ;; This one is safe because the user gets to check it before it is used.
1617 (put 'compile-command 'safe-local-variable t)
1618
1619 ;(defun hack-one-local-variable-quotep (exp)
1620 ;  (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1621
1622 ;; "Set" one variable in a local variables spec.
1623 ;; A few variable names are treated specially.
1624 (defun hack-one-local-variable (var val)
1625   (cond ((eq var 'mode)
1626          (funcall (intern (concat (downcase (symbol-name val))
1627                                   "-mode"))))
1628         ((memq var ignored-local-variables)
1629          nil)
1630         ;; "Setting" eval means either eval it or do nothing.
1631         ;; Likewise for setting hook variables.
1632         ((or (get var 'risky-local-variable)
1633              (and
1634               (string-match #r"-hooks?$\|-functions?$\|-forms?$\|-program$\|-command$"
1635                             (symbol-name var))
1636               (not (get var 'safe-local-variable))))
1637 ;        ;; Permit evaling a put of a harmless property
1638 ;        ;; if the args do nothing tricky.
1639 ;        (if (or (and (eq var 'eval)
1640 ;                     (consp val)
1641 ;                     (eq (car val) 'put)
1642 ;                     (hack-one-local-variable-quotep (nth 1 val))
1643 ;                     (hack-one-local-variable-quotep (nth 2 val))
1644 ;                     ;; Only allow safe values of lisp-indent-hook;
1645 ;                     ;; not functions.
1646 ;                     (or (numberp (nth 3 val))
1647 ;                         (equal (nth 3 val) ''defun))
1648 ;                     (memq (nth 1 (nth 2 val))
1649 ;                           '(lisp-indent-hook)))
1650          (if (and (not (zerop (user-uid)))
1651                   (or (eq enable-local-eval t)
1652                       (and enable-local-eval
1653                            (save-window-excursion
1654                              (switch-to-buffer (current-buffer))
1655                              (save-excursion
1656                                (beginning-of-line)
1657                                (set-window-start (selected-window) (point)))
1658                              (setq enable-local-eval
1659                                    (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1660                                                      (file-name-nondirectory buffer-file-name))))))))
1661              (if (eq var 'eval)
1662                  (save-excursion (eval val))
1663                (make-local-variable var)
1664                (set var val))
1665            (message "Ignoring `eval:' in file's local variables")))
1666         ;; Ordinary variable, really set it.
1667         (t (make-local-variable var)
1668            (set var val))))
1669 \f
1670 (defcustom change-major-mode-with-file-name t
1671   "*Non-nil means \\[write-file] should set the major mode from the file name.
1672 However, the mode will not be changed if
1673 \(1) a local variables list or the `-*-' line specifies a major mode, or
1674 \(2) the current major mode is a \"special\" mode,
1675 \    not suitable for ordinary files, or
1676 \(3) the new file name does not particularly specify any mode."
1677   :type 'boolean
1678   :group 'editing-basics)
1679
1680 (defun set-visited-file-name (filename &optional no-query along-with-file)
1681   "Change name of file visited in current buffer to FILENAME.
1682 The next time the buffer is saved it will go in the newly specified file.
1683 nil or empty string as argument means make buffer not be visiting any file.
1684 Remember to delete the initial contents of the minibuffer
1685 if you wish to pass an empty string as the argument.
1686
1687 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1688 confirmation in the case where another buffer is already visiting FILENAME.
1689
1690 The optional third argument ALONG-WITH-FILE, if non-nil, means that
1691 the old visited file has been renamed to the new name FILENAME."
1692   (interactive "FSet visited file name: ")
1693   (if (buffer-base-buffer)
1694       (error "An indirect buffer cannot visit a file"))
1695   (let (truename)
1696     (if filename
1697         (setq filename
1698               (if (string-equal filename "")
1699                   nil
1700                 (expand-file-name filename))))
1701     (if filename
1702         (progn
1703           (setq truename (file-truename filename))
1704           ;; #### Do we need to check if truename is non-nil?
1705           (if find-file-use-truenames
1706               (setq filename truename))))
1707     (let ((buffer (and filename (find-buffer-visiting filename))))
1708       (and buffer (not (eq buffer (current-buffer)))
1709            (not no-query)
1710            (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1711                                    filename)))
1712            (error "Aborted")))
1713     (or (equal filename buffer-file-name)
1714         (progn
1715           (and filename (lock-buffer filename))
1716           (unlock-buffer)))
1717     (setq buffer-file-name filename)
1718     (if filename                        ; make buffer name reflect filename.
1719         (let ((new-name (file-name-nondirectory buffer-file-name)))
1720           (if (string= new-name "")
1721               (error "Empty file name"))
1722           (setq default-directory (file-name-directory buffer-file-name))
1723           (or (string= new-name (buffer-name))
1724               (rename-buffer new-name t))))
1725     (setq buffer-backed-up nil)
1726     (or along-with-file
1727         (clear-visited-file-modtime))
1728     (compute-buffer-file-truename) ; insert-file-contents does this too.
1729 ;    ;; Abbreviate the file names of the buffer.
1730 ;    (if truename
1731 ;        (progn
1732 ;          (setq buffer-file-truename (abbreviate-file-name truename))
1733 ;          (if find-file-visit-truename
1734 ;              (setq buffer-file-name buffer-file-truename))))
1735     (setq buffer-file-number
1736           (if filename
1737               (nthcdr 10 (file-attributes buffer-file-name))
1738               nil)))
1739   ;; write-file-hooks is normally used for things like ftp-find-file
1740   ;; that visit things that are not local files as if they were files.
1741   ;; Changing to visit an ordinary local file instead should flush the hook.
1742   (kill-local-variable 'write-file-hooks)
1743   (kill-local-variable 'after-save-hook)
1744   (kill-local-variable 'local-write-file-hooks)
1745   (kill-local-variable 'write-file-data-hooks)
1746   (kill-local-variable 'revert-buffer-function)
1747   (kill-local-variable 'backup-inhibited)
1748   ;; If buffer was read-only because of version control,
1749   ;; that reason is gone now, so make it writable.
1750   (if-boundp 'vc-mode
1751       (progn
1752         (if vc-mode
1753             (setq buffer-read-only nil))
1754         (kill-local-variable 'vc-mode)))
1755   ;; Turn off backup files for certain file names.
1756   ;; Since this is a permanent local, the major mode won't eliminate it.
1757   (and buffer-file-name
1758        (not (funcall backup-enable-predicate buffer-file-name))
1759        (progn
1760          (make-local-variable 'backup-inhibited)
1761          (setq backup-inhibited t)))
1762   (let ((oauto buffer-auto-save-file-name))
1763     ;; If auto-save was not already on, turn it on if appropriate.
1764     (if (not buffer-auto-save-file-name)
1765         (and buffer-file-name auto-save-default
1766              (auto-save-mode t))
1767       ;; If auto save is on, start using a new name.
1768       ;; We deliberately don't rename or delete the old auto save
1769       ;; for the old visited file name.  This is because perhaps
1770       ;; the user wants to save the new state and then compare with the
1771       ;; previous state from the auto save file.
1772       (setq buffer-auto-save-file-name
1773             (make-auto-save-file-name)))
1774     ;; Rename the old auto save file if any.
1775     (and oauto buffer-auto-save-file-name
1776          (file-exists-p oauto)
1777          (rename-file oauto buffer-auto-save-file-name t)))
1778   (if buffer-file-name
1779       (not along-with-file)
1780       (set-buffer-modified-p t))
1781   ;; Update the major mode, if the file name determines it.
1782   (condition-case nil
1783       ;; Don't change the mode if it is special.
1784       (or (not change-major-mode-with-file-name)
1785           (get major-mode 'mode-class)
1786           ;; Don't change the mode if the local variable list specifies it.
1787           (hack-local-variables t)
1788           (set-auto-mode t))
1789     (error nil))
1790   ;; #### ??
1791   (run-hooks 'after-set-visited-file-name-hooks))
1792
1793 (defun write-file (filename &optional confirm codesys)
1794   "Write current buffer into file FILENAME.
1795 Makes buffer visit that file, and marks it not modified.
1796 If the buffer is already visiting a file, you can specify
1797 a directory name as FILENAME, to write a file of the same
1798 old name in that directory.
1799 If optional second arg CONFIRM is non-nil,
1800 ask for confirmation for overwriting an existing file.
1801 Under XEmacs/Mule, optional third argument specifies the
1802 coding system to use when encoding the file.  Interactively,
1803 with a prefix argument, you will be prompted for the coding system."
1804 ;;  (interactive "FWrite file: ")
1805   (interactive
1806    (list (if buffer-file-name
1807              (read-file-name "Write file: "
1808                                  nil nil nil nil)
1809            (read-file-name "Write file: "
1810                                (cdr (assq 'default-directory
1811                                           (buffer-local-variables)))
1812                                nil nil (buffer-name)))
1813          t
1814          (if (and current-prefix-arg (featurep 'file-coding))
1815              (read-coding-system "Coding system: "))))
1816   (and (eq (current-buffer) mouse-grabbed-buffer)
1817        (error "Can't write minibuffer window"))
1818   (or (null filename) (string-equal filename "")
1819       (progn
1820         ;; If arg is just a directory,
1821         ;; use same file name, but in that directory.
1822         (if (and (file-directory-p filename) buffer-file-name)
1823             (setq filename (concat (file-name-as-directory filename)
1824                                    (file-name-nondirectory buffer-file-name))))
1825         (and confirm
1826              (file-exists-p filename)
1827              (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1828                  (error "Canceled")))
1829         (set-visited-file-name filename)))
1830   (set-buffer-modified-p t)
1831   (setq buffer-read-only nil)
1832   (if codesys
1833       (let ((buffer-file-coding-system (get-coding-system codesys)))
1834         (save-buffer))
1835     (save-buffer)))
1836 \f
1837 (defun backup-buffer ()
1838   "Make a backup of the disk file visited by the current buffer, if appropriate.
1839 This is normally done before saving the buffer the first time.
1840 If the value is non-nil, it is the result of `file-modes' on the original file;
1841 this means that the caller, after saving the buffer, should change the modes
1842 of the new file to agree with the old modes."
1843   (if buffer-file-name
1844       (let ((handler (find-file-name-handler buffer-file-name 'backup-buffer)))
1845         (if handler
1846             (funcall handler 'backup-buffer)
1847           (if (and make-backup-files
1848                    (not backup-inhibited)
1849                    (not buffer-backed-up)
1850                    (file-exists-p buffer-file-name)
1851                    (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1852                          '(?- ?l)))
1853               (let ((real-file-name buffer-file-name)
1854                     backup-info backupname targets setmodes)
1855                 ;; If specified name is a symbolic link, chase it to the target.
1856                 ;; Thus we make the backups in the directory where the real file is.
1857                 (setq real-file-name (file-chase-links real-file-name))
1858                 (setq backup-info (find-backup-file-name real-file-name)
1859                       backupname (car backup-info)
1860                       targets (cdr backup-info))
1861 ;;;     (if (file-directory-p buffer-file-name)
1862 ;;;         (error "Cannot save buffer in directory %s" buffer-file-name))
1863                 (if backup-info
1864                     (condition-case ()
1865                         (let ((delete-old-versions
1866                                ;; If have old versions to maybe delete,
1867                                ;; ask the user to confirm now, before doing anything.
1868                                ;; But don't actually delete till later.
1869                                (and targets
1870                                     (or (eq delete-old-versions t)
1871                                         (eq delete-old-versions nil))
1872                                     (or delete-old-versions
1873                                         (y-or-n-p (format "Delete excess backup versions of %s? "
1874                                                           real-file-name))))))
1875                           ;; Actually write the back up file.
1876                           (condition-case ()
1877                               (if (or file-precious-flag
1878                                         ;                         (file-symlink-p buffer-file-name)
1879                                       backup-by-copying
1880                                       (and backup-by-copying-when-linked
1881                                            (> (file-nlinks real-file-name) 1))
1882                                       (and backup-by-copying-when-mismatch
1883                                            (let ((attr (file-attributes real-file-name)))
1884                                              (or (nth 9 attr)
1885                                                  (not (file-ownership-preserved-p real-file-name))))))
1886                                   (condition-case ()
1887                                       (copy-file real-file-name backupname t t)
1888                                     (file-error
1889                                      ;; If copying fails because file BACKUPNAME
1890                                      ;; is not writable, delete that file and try again.
1891                                      (if (and (file-exists-p backupname)
1892                                               (not (file-writable-p backupname)))
1893                                          (delete-file backupname))
1894                                      (copy-file real-file-name backupname t t)))
1895                                 ;; rename-file should delete old backup.
1896                                 (rename-file real-file-name backupname t)
1897                                 (setq setmodes (file-modes backupname)))
1898                             (file-error
1899                              ;; If trouble writing the backup, write
1900                              ;; it in `auto-save-directory'.  Fall
1901                              ;; back to $HOME if that's not possible.
1902                              (setq backupname
1903                                    (expand-file-name "%backup%~"
1904                                                      (or (when (and auto-save-directory
1905                                                                     (file-writable-p auto-save-directory))
1906                                                            auto-save-directory)
1907                                                          (getenv "HOME"))))
1908                              (message "Cannot write backup file; backing up in %s" backupname)
1909                              (sleep-for 1)
1910                              (condition-case ()
1911                                  (copy-file real-file-name backupname t t)
1912                                (file-error
1913                                 ;; If copying fails because file BACKUPNAME
1914                                 ;; is not writable, delete that file and try again.
1915                                 (if (and (file-exists-p backupname)
1916                                          (not (file-writable-p backupname)))
1917                                     (delete-file backupname))
1918                                 (copy-file real-file-name backupname t t)))))
1919                           (setq buffer-backed-up t)
1920                           ;; Now delete the old versions, if desired.
1921                           (if delete-old-versions
1922                               (while targets
1923                                 (ignore-file-errors (delete-file (car targets)))
1924                                 (setq targets (cdr targets))))
1925                           setmodes)
1926                       (file-error nil)))))))))
1927
1928 (defun file-name-sans-versions (name &optional keep-backup-version)
1929   "Return FILENAME sans backup versions or strings.
1930 This is a separate procedure so your site-init or startup file can
1931 redefine it.
1932 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1933 we do not remove backup version numbers, only true file version numbers."
1934   (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1935     (if handler
1936         (funcall handler 'file-name-sans-versions name keep-backup-version)
1937       (substring name 0
1938                  (if keep-backup-version
1939                      (length name)
1940                    (or (string-match #r"\.~[0-9.]+~\'" name)
1941                        ;; XEmacs - VC uses extensions like ".~tagname~" or ".~1.1.5.2~"
1942                        (let ((pos (string-match "\\.~\\([^.~ \t]+\\|[0-9.]+\\)~\\'" name)))
1943                          (and pos
1944                               ;; #### - is this filesystem check too paranoid?
1945                               (file-exists-p (substring name 0 pos))
1946                               pos))
1947                        (string-match "~\\'" name)
1948                        (length name)))))))
1949
1950 (defun file-ownership-preserved-p (file)
1951   "Return t if deleting FILE and rewriting it would preserve the owner."
1952   (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1953     (if handler
1954         (funcall handler 'file-ownership-preserved-p file)
1955       (let ((attributes (file-attributes file)))
1956         ;; Return t if the file doesn't exist, since it's true that no
1957         ;; information would be lost by an (attempted) delete and create.
1958         (or (null attributes)
1959             (= (nth 2 attributes) (user-uid)))))))
1960
1961 (defun file-name-sans-extension (filename)
1962   "Return FILENAME sans final \"extension\".
1963 The extension, in a file name, is the part that follows the last `.'."
1964   (save-match-data
1965     (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1966           directory)
1967       (if (string-match #r"\.[^.]*\'" file)
1968           (if (setq directory (file-name-directory filename))
1969               (expand-file-name (substring file 0 (match-beginning 0))
1970                                 directory)
1971             (substring file 0 (match-beginning 0)))
1972         filename))))
1973
1974 (defun file-name-extension (filename &optional period)
1975   "Return FILENAME's final \"extension\".
1976 The extension, in a file name, is the part that follows the last `.'.
1977 Return nil for extensionless file names such as `foo'.
1978 Return the empty string for file names such as `foo.'.
1979
1980 If PERIOD is non-nil, then the returned value includes the period
1981 that delimits the extension, and if FILENAME has no extension,
1982 the value is \"\"."
1983   (save-match-data
1984     (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
1985       (if (string-match #r"\.[^.]*\'" file)
1986           (substring file (+ (match-beginning 0) (if period 0 1)))
1987         (if period
1988             "")))))
1989
1990 (defun make-backup-file-name (file)
1991   "Create the non-numeric backup file name for FILE.
1992 This is a separate function so you can redefine it for customization."
1993   ;; FSF has code here for MS-DOS short filenames, not supported in XEmacs.
1994     (concat file "~"))
1995
1996 (defun backup-file-name-p (file)
1997   "Return non-nil if FILE is a backup file name (numeric or not).
1998 This is a separate function so you can redefine it for customization.
1999 You may need to redefine `file-name-sans-versions' as well."
2000   (string-match "~\\'" file))
2001
2002 ;; This is used in various files.
2003 ;; The usage of bv-length is not very clean,
2004 ;; but I can't see a good alternative,
2005 ;; so as of now I am leaving it alone.
2006 (defun backup-extract-version (fn)
2007   "Given the name of a numeric backup file, return the backup number.
2008 Uses the free variable `bv-length', whose value should be
2009 the index in the name where the version number begins."
2010   (declare (special bv-length))
2011   (if (and (string-match "[0-9]+~\\'" fn bv-length)
2012            (= (match-beginning 0) bv-length))
2013       (string-to-int (substring fn bv-length -1))
2014       0))
2015
2016 (defun find-backup-file-name (fn)
2017   "Find a file name for a backup file, and suggestions for deletions.
2018 Value is a list whose car is the name for the backup file
2019  and whose cdr is a list of old versions to consider deleting now.
2020 If the value is nil, don't make a backup."
2021   (declare (special bv-length))
2022   (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
2023     ;; Run a handler for this function so that ange-ftp can refuse to do it.
2024     (if handler
2025         (funcall handler 'find-backup-file-name fn)
2026       (if (eq version-control 'never)
2027           (list (make-backup-file-name fn))
2028         (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
2029                ;; used by backup-extract-version:
2030                (bv-length (length base-versions))
2031                possibilities
2032                (versions nil)
2033                (high-water-mark 0)
2034                (deserve-versions-p nil)
2035                (number-to-delete 0))
2036           (condition-case ()
2037               (setq possibilities (file-name-all-completions
2038                                    base-versions
2039                                    (file-name-directory fn))
2040                     versions (sort (mapcar
2041                                     #'backup-extract-version
2042                                     possibilities)
2043                                    '<)
2044                     high-water-mark (apply #'max 0 versions)
2045                     deserve-versions-p (or version-control
2046                                            (> high-water-mark 0))
2047                     number-to-delete (- (length versions)
2048                                         kept-old-versions kept-new-versions -1))
2049             (file-error
2050              (setq possibilities nil)))
2051           (if (not deserve-versions-p)
2052               (list (make-backup-file-name fn))
2053             (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
2054                   (if (and (> number-to-delete 0)
2055                            ;; Delete nothing if there is overflow
2056                            ;; in the number of versions to keep.
2057                            (>= (+ kept-new-versions kept-old-versions -1) 0))
2058                       (mapcar #'(lambda (n)
2059                                   (concat fn ".~" (int-to-string n) "~"))
2060                               (let ((v (nthcdr kept-old-versions versions)))
2061                                 (rplacd (nthcdr (1- number-to-delete) v) ())
2062                                 v))))))))))
2063
2064 (defun file-nlinks (filename)
2065   "Return number of names file FILENAME has."
2066   (car (cdr (file-attributes filename))))
2067
2068 (defun file-relative-name (filename &optional directory)
2069   "Convert FILENAME to be relative to DIRECTORY (default: default-directory).
2070 This function returns a relative file name which is equivalent to FILENAME
2071 when used with that default directory as the default.
2072 If this is impossible (which can happen on MS Windows when the file name
2073 and directory use different drive names) then it returns FILENAME."
2074   (save-match-data
2075     (let ((fname (expand-file-name filename)))
2076       (setq directory (file-name-as-directory
2077                        (expand-file-name (or directory default-directory))))
2078       ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2079       ;; drive names, they can't be relative, so return the absolute name.
2080       (if (and (eq system-type 'windows-nt)
2081                (not (string-equal (substring fname  0 2)
2082                                   (substring directory 0 2))))
2083           filename
2084         (let ((ancestor ".")
2085               (fname-dir (file-name-as-directory fname)))
2086           (while (and (not (string-match (concat "^" (regexp-quote directory))
2087                                          fname-dir))
2088                       (not (string-match (concat "^" (regexp-quote directory)) fname)))
2089             (setq directory (file-name-directory (substring directory 0 -1))
2090                   ancestor (if (equal ancestor ".")
2091                                ".."
2092                              (concat "../" ancestor))))
2093           ;; Now ancestor is empty, or .., or ../.., etc.
2094           (if (string-match (concat "^" (regexp-quote directory)) fname)
2095               ;; We matched within FNAME's directory part.
2096               ;; Add the rest of FNAME onto ANCESTOR.
2097               (let ((rest (substring fname (match-end 0))))
2098                 (if (and (equal ancestor ".")
2099                          (not (equal rest "")))
2100                     ;; But don't bother with ANCESTOR if it would give us `./'.
2101                     rest
2102                   (concat (file-name-as-directory ancestor) rest)))
2103             ;; We matched FNAME's directory equivalent.
2104             ancestor))))))
2105 \f
2106 (defun save-buffer (&optional args)
2107   "Save current buffer in visited file if modified.  Versions described below.
2108
2109 By default, makes the previous version into a backup file
2110  if previously requested or if this is the first save.
2111 With 1 or 3 \\[universal-argument]'s, marks this version
2112  to become a backup when the next save is done.
2113 With 2 or 3 \\[universal-argument]'s,
2114  unconditionally makes the previous version into a backup file.
2115 With argument of 0, never makes the previous version into a backup file.
2116
2117 If a file's name is FOO, the names of its numbered backup versions are
2118  FOO.~i~ for various integers i.  A non-numbered backup file is called FOO~.
2119 Numeric backups (rather than FOO~) will be made if value of
2120  `version-control' is not the atom `never' and either there are already
2121  numeric versions of the file being backed up, or `version-control' is
2122  non-nil.
2123 We don't want excessive versions piling up, so there are variables
2124  `kept-old-versions', which tells XEmacs how many oldest versions to keep,
2125  and `kept-new-versions', which tells how many newest versions to keep.
2126  Defaults are 2 old versions and 2 new.
2127 `dired-kept-versions' controls dired's clean-directory (.) command.
2128 If `delete-old-versions' is nil, system will query user
2129  before trimming versions.  Otherwise it does it silently."
2130   (interactive "_p")
2131   (let ((modp (buffer-modified-p))
2132         (large (> (buffer-size) 50000))
2133         (make-backup-files (or (and make-backup-files (not (eq args 0)))
2134                                (memq args '(16 64)))))
2135     (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2136     (if (and modp large) (display-message
2137                           'progress (format "Saving file %s..."
2138                                             (buffer-file-name))))
2139     (basic-save-buffer)
2140     (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2141
2142 (defun delete-auto-save-file-if-necessary (&optional force)
2143   "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2144 Normally delete only if the file was written by this XEmacs
2145 since the last real save, but optional arg FORCE non-nil means delete anyway."
2146   (and buffer-auto-save-file-name delete-auto-save-files
2147        (not (string= buffer-file-name buffer-auto-save-file-name))
2148        (or force (recent-auto-save-p))
2149        (progn
2150          (ignore-file-errors (delete-file buffer-auto-save-file-name))
2151          (set-buffer-auto-saved))))
2152
2153 ;; XEmacs change (from Sun)
2154 ;; used to communicate with continue-save-buffer:
2155 (defvar continue-save-buffer-hooks-tail nil)
2156
2157 ;; Not in FSFmacs
2158 (defun basic-write-file-data (realname truename)
2159   ;; call the hooks until the bytes are put
2160   ;; call write-region as a last resort
2161   (let ((region-written nil)
2162         (hooks write-file-data-hooks))
2163     (while (and hooks (not region-written))
2164       (setq region-written (funcall (car hooks) realname)
2165             hooks (cdr hooks)))
2166     (if (not region-written)
2167         (write-region (point-min) (point-max) realname nil t truename))))
2168
2169 (put 'after-save-hook 'permanent-local t)
2170 (defvar after-save-hook nil
2171   "Normal hook that is run after a buffer is saved to its file.
2172 These hooks are considered to pertain to the visited file.
2173 So this list is cleared if you change the visited file name.")
2174
2175 (defun files-fetch-hook-value (hook)
2176   (let ((localval (symbol-value hook))
2177         (globalval (default-value hook)))
2178     (if (memq t localval)
2179         (setq localval (append (delq t localval) (delq t globalval))))
2180     localval))
2181
2182 (defun basic-save-buffer ()
2183   "Save the current buffer in its visited file, if it has been modified.
2184 After saving the buffer, run `after-save-hook'."
2185   (interactive)
2186   (save-excursion
2187     ;; In an indirect buffer, save its base buffer instead.
2188     (if (buffer-base-buffer)
2189         (set-buffer (buffer-base-buffer)))
2190     (if (buffer-modified-p)
2191         (let ((recent-save (recent-auto-save-p)))
2192           ;; If buffer has no file name, ask user for one.
2193           (or buffer-file-name
2194               (let ((filename
2195                      (expand-file-name
2196                       (read-file-name "File to save in: ") nil)))
2197                 (and (file-exists-p filename)
2198                      (or (y-or-n-p (format "File `%s' exists; overwrite? "
2199                                            filename))
2200                          (error "Canceled")))
2201                 (set-visited-file-name filename)))
2202           (or (verify-visited-file-modtime (current-buffer))
2203               (not (file-exists-p buffer-file-name))
2204               (yes-or-no-p
2205                (format "%s has changed since visited or saved.  Save anyway? "
2206                        (file-name-nondirectory buffer-file-name)))
2207               (error "Save not confirmed"))
2208           (save-restriction
2209             (widen)
2210
2211             ;; Add final newline if required.  See `require-final-newline'.
2212             (when (and (not (eq (char-before (point-max)) ?\n)) ; common case
2213                        (char-before (point-max))                ; empty buffer?
2214                        (not (and (eq selective-display t)
2215                                  (eq (char-before (point-max)) ?\r)))
2216                        (or (eq require-final-newline t)
2217                            (and require-final-newline
2218                                 (y-or-n-p
2219                                  (format "Buffer %s does not end in newline.  Add one? "
2220                                          (buffer-name))))))
2221               (save-excursion
2222                 (goto-char (point-max))
2223                 (insert ?\n)))
2224
2225             ;; Run the write-file-hooks until one returns non-nil.
2226             ;; Bind after-save-hook to nil while running the
2227             ;; write-file-hooks so that if this function is called
2228             ;; recursively (from inside a write-file-hook) the
2229             ;; after-hooks will only get run once (from the
2230             ;; outermost call).
2231             ;;
2232             ;; Ugh, have to duplicate logic of run-hook-with-args-until-success
2233             (let ((hooks (append (files-fetch-hook-value 'write-contents-hooks)
2234                                  (files-fetch-hook-value
2235                                   'local-write-file-hooks)
2236                                  (files-fetch-hook-value 'write-file-hooks)))
2237                   (after-save-hook nil)
2238                   (local-write-file-hooks nil)
2239                   (write-contents-hooks nil)
2240                   (write-file-hooks nil)
2241                   done)
2242               (while (and hooks
2243                           (let ((continue-save-buffer-hooks-tail hooks))
2244                             (not (setq done (funcall (car hooks))))))
2245                 (setq hooks (cdr hooks)))
2246               ;; If a hook returned t, file is already "written".
2247               ;; Otherwise, write it the usual way now.
2248               (if (not done)
2249                   (basic-save-buffer-1)))
2250             ;; XEmacs: next two clauses (buffer-file-number setting and
2251             ;; set-file-modes) moved into basic-save-buffer-1.
2252             )
2253           ;; If the auto-save file was recent before this command,
2254           ;; delete it now.
2255           (delete-auto-save-file-if-necessary recent-save)
2256           ;; Support VC `implicit' locking.
2257           (if-fboundp 'vc-after-save
2258             (vc-after-save))
2259           (run-hooks 'after-save-hook))
2260       (display-message 'no-log "(No changes need to be saved)"))))
2261
2262 ;; This does the "real job" of writing a buffer into its visited file
2263 ;; and making a backup file.  This is what is normally done
2264 ;; but inhibited if one of write-file-hooks returns non-nil.
2265 ;; It returns a value to store in setmodes.
2266 (defun basic-save-buffer-1 ()
2267   (let (setmodes tempsetmodes)
2268     (if (not (file-writable-p buffer-file-name))
2269         (let ((dir (file-name-directory buffer-file-name)))
2270           (if (not (file-directory-p dir))
2271               (error "%s is not a directory" dir)
2272             (if (not (file-exists-p buffer-file-name))
2273                 (error "Directory %s write-protected" dir)
2274               (if (yes-or-no-p
2275                    (format "File %s is write-protected; try to save anyway? "
2276                            (file-name-nondirectory
2277                             buffer-file-name)))
2278                   (setq tempsetmodes t)
2279                 (error
2280                  "Attempt to save to a file which you aren't allowed to write"))))))
2281     (or buffer-backed-up
2282         (setq setmodes (backup-buffer)))
2283     (let ((dir (file-name-directory buffer-file-name)))
2284       (if (and file-precious-flag
2285                (file-writable-p dir))
2286           ;; If file is precious, write temp name, then rename it.
2287           ;; This requires write access to the containing dir,
2288           ;; which is why we don't try it if we don't have that access.
2289           (let ((realname buffer-file-name)
2290                 tempname nogood i succeed
2291                 (old-modtime (visited-file-modtime)))
2292             (setq i 0)
2293             (setq nogood t)
2294             ;; Find the temporary name to write under.
2295             (while nogood
2296               (setq tempname (format "%s#tmp#%d" dir i))
2297               (setq nogood (file-exists-p tempname))
2298               (setq i (1+ i)))
2299             (unwind-protect
2300                 (progn (clear-visited-file-modtime)
2301                        (write-region (point-min) (point-max)
2302                                      tempname nil realname
2303                                      buffer-file-truename)
2304                        (setq succeed t))
2305               ;; If writing the temp file fails,
2306               ;; delete the temp file.
2307               (or succeed
2308                   (progn
2309                     (delete-file tempname)
2310                     (set-visited-file-modtime old-modtime))))
2311             ;; Since we have created an entirely new file
2312             ;; and renamed it, make sure it gets the
2313             ;; right permission bits set.
2314             (setq setmodes (file-modes buffer-file-name))
2315             ;; We succeeded in writing the temp file,
2316             ;; so rename it.
2317             (rename-file tempname buffer-file-name t))
2318         ;; If file not writable, see if we can make it writable
2319         ;; temporarily while we write it.
2320         ;; But no need to do so if we have just backed it up
2321         ;; (setmodes is set) because that says we're superseding.
2322         (cond ((and tempsetmodes (not setmodes))
2323                ;; Change the mode back, after writing.
2324                (setq setmodes (file-modes buffer-file-name))
2325                (set-file-modes buffer-file-name 511)))
2326         (basic-write-file-data buffer-file-name buffer-file-truename)))
2327     (setq buffer-file-number
2328           (if buffer-file-name
2329               (nth 10 (file-attributes buffer-file-name))
2330             nil))
2331     (if setmodes
2332         (condition-case ()
2333             (set-file-modes buffer-file-name setmodes)
2334           (error nil)))))
2335
2336 ;; XEmacs change, from Sun
2337 (defun continue-save-buffer ()
2338   "Provide a clean way for a write-file-hook to wrap AROUND
2339 the execution of the remaining hooks and writing to disk.
2340 Do not call this function except from a functions
2341 on the `write-file-hooks' or `write-contents-hooks' list.
2342 A hook that calls this function must return non-nil,
2343 to signal completion to its caller.  `continue-save-buffer'
2344 always returns non-nil."
2345   (let ((hooks (cdr (or continue-save-buffer-hooks-tail
2346                         (error
2347          "continue-save-buffer called outside a write-file-hook!"))))
2348         (done nil))
2349     ;; Do something like this:
2350     ;; (let ((write-file-hooks hooks)) (basic-save-buffer))
2351     ;; First run the rest of the hooks.
2352     (while (and hooks
2353                 (let ((continue-save-buffer-hooks-tail hooks))
2354                   (not (setq done (funcall (car hooks))))))
2355       (setq hooks (cdr hooks)))
2356     ;;
2357     ;; If a hook returned t, file is already "written".
2358     (if (not done)
2359         (basic-save-buffer-1))
2360     'continue-save-buffer))
2361
2362 (defcustom save-some-buffers-query-display-buffer t
2363   "*Non-nil makes `\\[save-some-buffers]' switch to the buffer offered for saving."
2364   :type 'boolean
2365   :group 'editing-basics)
2366
2367 (defun save-some-buffers (&optional arg exiting)
2368   "Save some modified file-visiting buffers.  Asks user about each one.
2369 Optional argument (the prefix) non-nil means save all with no questions.
2370 Optional second argument EXITING means ask about certain non-file buffers
2371  as well as about file buffers."
2372   (interactive "P")
2373   (save-excursion
2374     ;; `delete-other-windows' can bomb during autoloads generation, so
2375     ;; guard it well.
2376     (if (or noninteractive
2377             (eq (selected-window) (minibuffer-window))
2378             (not save-some-buffers-query-display-buffer))
2379         ;; If playing with windows is unsafe or undesired, just do the
2380         ;; usual drill.
2381         (save-some-buffers-1 arg exiting nil)
2382       ;; Else, protect the windows.
2383       (when (save-window-excursion
2384               (save-some-buffers-1 arg exiting t))
2385         ;; Force redisplay.
2386         (sit-for 0)))))
2387
2388 ;; XEmacs - do not use queried flag
2389 (defun save-some-buffers-1 (arg exiting switch-buffer)
2390   (let* ((switched nil)
2391          (last-buffer nil)
2392          (files-done
2393           (map-y-or-n-p
2394            (lambda (buffer)
2395              (prog1
2396                  (and (buffer-modified-p buffer)
2397                       (not (buffer-base-buffer buffer))
2398                       ;; XEmacs addition:
2399                       (not (symbol-value-in-buffer 'save-buffers-skip buffer))
2400                       (or
2401                        (buffer-file-name buffer)
2402                        (and exiting
2403                             (progn
2404                               (set-buffer buffer)
2405                               (and buffer-offer-save (> (buffer-size) 0)))))
2406                       (if arg
2407                           t
2408                         ;; #### We should provide a per-buffer means to
2409                         ;; disable the switching.  For instance, you might
2410                         ;; want to turn it off for buffers the contents of
2411                         ;; which is meaningless to humans, such as
2412                         ;; `.newsrc.eld'.
2413                         (when (and switch-buffer
2414                                    ;; map-y-or-n-p is displaying help
2415                                    (not (eq last-buffer buffer)))
2416                           (unless (one-window-p)
2417                             (delete-other-windows))
2418                           (setq switched t)
2419                           ;; #### Consider using `display-buffer' here for 21.1!
2420                           ;;(display-buffer buffer nil (selected-frame)))
2421                           (switch-to-buffer buffer t))
2422                         (if (buffer-file-name buffer)
2423                             (format "Save file %s? "
2424                                     (buffer-file-name buffer))
2425                           (format "Save buffer %s? "
2426                                   (buffer-name buffer)))))
2427                (setq last-buffer buffer)))
2428            (lambda (buffer)
2429              (set-buffer buffer)
2430              (condition-case ()
2431                  (save-buffer)
2432                (error nil)))
2433            (buffer-list)
2434            '("buffer" "buffers" "save")
2435            ;;instead of this we just say "yes all", "no all", etc.
2436            ;;"save all the rest"
2437            ;;"save only this buffer" "save no more buffers")
2438            ;; this is rather bogus. --ben
2439            ;; (it makes the dialog box too big, and you get an error
2440            ;; "wrong type argument: framep, nil" when you hit q after
2441            ;; choosing the option from the dialog box)
2442
2443            ;; We should fix the dialog box rather than disabling
2444            ;; this!  --hniksic
2445            (list (list ?\C-r (lambda (buf)
2446                                ;; #### FSF has an EXIT-ACTION argument
2447                                ;; to `view-buffer'.
2448                                (declare-fboundp (view-buffer buf))
2449                                (with-boundp 'view-exit-action
2450                                  (setq view-exit-action
2451                                        (lambda (ignore)
2452                                          (exit-recursive-edit))))
2453                                (recursive-edit)
2454                                ;; Return nil to ask about BUF again.
2455                                nil)
2456                        "%_Display Buffer"))))
2457          (abbrevs-done
2458           (and save-abbrevs abbrevs-changed
2459                (progn
2460                  (if (or arg
2461                          (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
2462                      (write-abbrev-file nil))
2463                  ;; Don't keep bothering user if he says no.
2464                  (setq abbrevs-changed nil)
2465                  t))))
2466     (or (> files-done 0) abbrevs-done
2467         (display-message 'no-log "(No files need saving)"))
2468     switched))
2469
2470 \f
2471 (defun not-modified (&optional arg)
2472   "Mark current buffer as unmodified, not needing to be saved.
2473 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2474
2475 It is not a good idea to use this function in Lisp programs, because it
2476 prints a message in the minibuffer.  Instead, use `set-buffer-modified-p'."
2477   (interactive "_P")
2478   (if arg ;; rewritten for I18N3 snarfing
2479       (display-message 'command "Modification-flag set")
2480     (display-message 'command "Modification-flag cleared"))
2481   (set-buffer-modified-p arg))
2482
2483 (defun toggle-read-only (&optional arg)
2484   "Toggle the current buffer's read-only status.
2485 With arg, set read-only iff arg is positive."
2486   (interactive "_P")
2487   (setq buffer-read-only
2488         (if (null arg)
2489             (not buffer-read-only)
2490             (> (prefix-numeric-value arg) 0)))
2491   ;; Force modeline redisplay
2492   (redraw-modeline))
2493
2494 (defun insert-file (filename &optional codesys)
2495   "Insert contents of file FILENAME into buffer after point.
2496 Set mark after the inserted text.
2497
2498 Under XEmacs/Mule, optional second argument specifies the
2499 coding system to use when decoding the file.  Interactively,
2500 with a prefix argument, you will be prompted for the coding system.
2501
2502 This function is meant for the user to run interactively.
2503 Don't call it from programs!  Use `insert-file-contents' instead.
2504 \(Its calling sequence is different; see its documentation)."
2505   (interactive "*fInsert file: \nZCoding system: ")
2506   (if (file-directory-p filename)
2507       (signal 'file-error (list "Opening input file" "file is a directory"
2508                                 filename)))
2509   (let ((tem
2510          (if codesys
2511              (let ((coding-system-for-read
2512                     (get-coding-system codesys)))
2513                (insert-file-contents filename))
2514            (insert-file-contents filename))))
2515     (push-mark (+ (point) (car (cdr tem))))))
2516
2517 (defun append-to-file (start end filename &optional codesys)
2518   "Append the contents of the region to the end of file FILENAME.
2519 When called from a function, expects three arguments,
2520 START, END and FILENAME.  START and END are buffer positions
2521 saying what text to write.
2522 Under XEmacs/Mule, optional fourth argument specifies the
2523 coding system to use when encoding the file.  Interactively,
2524 with a prefix argument, you will be prompted for the coding system."
2525   (interactive "r\nFAppend to file: \nZCoding system: ")
2526   (if codesys
2527       (let ((buffer-file-coding-system (get-coding-system codesys)))
2528         (write-region start end filename t))
2529     (write-region start end filename t)))
2530
2531 (defun file-newest-backup (filename)
2532   "Return most recent backup file for FILENAME or nil if no backups exist."
2533   (let* ((filename (expand-file-name filename))
2534          (file (file-name-nondirectory filename))
2535          (dir  (file-name-directory    filename))
2536          (comp (file-name-all-completions file dir))
2537          newest)
2538     (while comp
2539       (setq file (concat dir (car comp))
2540             comp (cdr comp))
2541       (if (and (backup-file-name-p file)
2542                (or (null newest) (file-newer-than-file-p file newest)))
2543           (setq newest file)))
2544     newest))
2545
2546 (defun rename-uniquely ()
2547   "Rename current buffer to a similar name not already taken.
2548 This function is useful for creating multiple shell process buffers
2549 or multiple mail buffers, etc."
2550   (interactive)
2551   (save-match-data
2552     (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2553                                (not (and buffer-file-name
2554                                          (string= (buffer-name)
2555                                                   (file-name-nondirectory
2556                                                    buffer-file-name)))))
2557                           ;; If the existing buffer name has a <NNN>,
2558                           ;; which isn't part of the file name (if any),
2559                           ;; then get rid of that.
2560                           (substring (buffer-name) 0 (match-beginning 0))
2561                         (buffer-name)))
2562            (new-buf (generate-new-buffer base-name))
2563            (name (buffer-name new-buf)))
2564       (kill-buffer new-buf)
2565       (rename-buffer name)
2566       (redraw-modeline))))
2567
2568 (defun make-directory-path (path)
2569   "Create all the directories along path that don't exist yet."
2570   (interactive "Fdirectory path to create: ")
2571   (make-directory path t))
2572
2573 (defun make-directory (dir &optional parents)
2574   "Create the directory DIR and any nonexistent parent dirs.
2575 Interactively, the default choice of directory to create
2576 is the current default directory for file names.
2577 That is useful when you have visited a file in a nonexistent directory.
2578
2579 Noninteractively, the second (optional) argument PARENTS says whether
2580 to create parent directories if they don't exist."
2581   (interactive (list (let ((current-prefix-arg current-prefix-arg))
2582                        (read-directory-name "Create directory: "))
2583                      current-prefix-arg))
2584   (let ((handler (find-file-name-handler dir 'make-directory)))
2585     (if handler
2586         (funcall handler 'make-directory dir parents)
2587       (if (not parents)
2588           (make-directory-internal dir)
2589         (let ((dir (directory-file-name (expand-file-name dir)))
2590               create-list)
2591           (while (not (file-exists-p dir))
2592             (setq create-list (cons dir create-list)
2593                   dir (directory-file-name (file-name-directory dir))))
2594           (while create-list
2595             (make-directory-internal (car create-list))
2596             (setq create-list (cdr create-list))))))))
2597 \f
2598 (put 'revert-buffer-function 'permanent-local t)
2599 (defvar revert-buffer-function nil
2600   "Function to use to revert this buffer, or nil to do the default.
2601 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2602 which are the arguments that `revert-buffer' received.")
2603
2604 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2605 (defvar revert-buffer-insert-file-contents-function nil
2606   "Function to use to insert contents when reverting this buffer.
2607 Gets two args, first the nominal file name to use,
2608 and second, t if reading the auto-save file.
2609 If the current buffer contents are to be discarded, the function must do
2610 so itself.")
2611
2612 (defvar before-revert-hook nil
2613   "Normal hook for `revert-buffer' to run before reverting.
2614 If `revert-buffer-function' is used to override the normal revert
2615 mechanism, this hook is not used.")
2616
2617 (defvar after-revert-hook nil
2618   "Normal hook for `revert-buffer' to run after reverting.
2619 Note that the hook value that it runs is the value that was in effect
2620 before reverting; that makes a difference if you have buffer-local
2621 hook functions.
2622
2623 If `revert-buffer-function' is used to override the normal revert
2624 mechanism, this hook is not used.")
2625
2626 (defvar revert-buffer-internal-hook nil
2627   "Don't use this.")
2628
2629 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2630   "Replace the buffer text with the text of the visited file on disk.
2631 This undoes all changes since the file was visited or saved.
2632 With a prefix argument, offer to revert from latest auto-save file, if
2633 that is more recent than the visited file.
2634
2635 This command also refreshes certain special buffers that contain text
2636 which doesn't come from a file, but reflects some other data base
2637 instead: for example, Dired buffers and buffer-list buffers.  This is
2638 implemented by having the modes set `revert-buffer-function'.
2639
2640 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2641 to revert from the auto-save file when this is nil.  Note that the
2642 sense of this argument is the reverse of the prefix argument, for the
2643 sake of backward compatibility.  IGNORE-AUTO is optional, defaulting
2644 to nil.
2645
2646 Optional second argument NOCONFIRM means don't ask for confirmation at
2647 all.
2648
2649 Optional third argument PRESERVE-MODES non-nil means don't alter
2650 the buffer's modes.  Otherwise, reinitialize them using `normal-mode'.
2651
2652 If the value of `revert-buffer-function' is non-nil, it is called to
2653 do all the work for this command.  Otherwise, the hooks
2654 `before-revert-hook' and `after-revert-hook' are run at the beginning
2655 and the end, and if `revert-buffer-insert-file-contents-function' is
2656 non-nil, it is called instead of rereading visited file contents.
2657
2658 If the buffer-modified flag is nil, and we are not reverting from an
2659 auto-save file, then compare the contents of the buffer and the file.
2660 Revert only if they differ."
2661
2662   ;; I admit it's odd to reverse the sense of the prefix argument, but
2663   ;; there is a lot of code out there which assumes that the first
2664   ;; argument should be t to avoid consulting the auto-save file, and
2665   ;; there's no straightforward way to encourage authors to notice a
2666   ;; reversal of the argument sense.  So I'm just changing the user
2667   ;; interface, but leaving the programmatic interface the same.
2668   (interactive (list (not current-prefix-arg)))
2669   (if revert-buffer-function
2670       (funcall revert-buffer-function ignore-auto noconfirm)
2671     (let* ((opoint (point))
2672            (newbuf nil)
2673            (found nil)
2674            (delay-prompt nil)
2675            (auto-save-p (and (not ignore-auto)
2676                              (recent-auto-save-p)
2677                              buffer-auto-save-file-name
2678                              (file-readable-p buffer-auto-save-file-name)
2679                              (y-or-n-p
2680    "Buffer has been auto-saved recently.  Revert from auto-save file? ")))
2681            (file-name (if auto-save-p
2682                           buffer-auto-save-file-name
2683                         buffer-file-name)))
2684       (cond ((null file-name)
2685              (error "Buffer does not seem to be associated with any file"))
2686             ((or noconfirm
2687                  (and (not (buffer-modified-p))
2688                       (dolist (rx revert-without-query found)
2689                         (when (string-match rx file-name)
2690                           (setq found t))))
2691                  ;; If we will call revert-buffer-internal, delay prompting
2692                  (and (not auto-save-p)
2693                       (not (buffer-modified-p))
2694                       (setq delay-prompt t))
2695                  (yes-or-no-p (format "Revert buffer from file %s? "
2696                                       file-name)))
2697              (run-hooks 'before-revert-hook)
2698              (cond ((or auto-save-p
2699                         (buffer-modified-p)
2700                         ;; Do we need to do expensive reversion?  Compare ...
2701                         (and (setq newbuf (revert-buffer-internal
2702                                            file-name))
2703                              ;; ... and if different, prompt
2704                              (or noconfirm found
2705                                  (and delay-prompt
2706                                       (yes-or-no-p
2707                                        (format "Revert buffer from file %s? "
2708                                                file-name))))))
2709                     ;; If file was backed up but has changed since,
2710                     ;; we should make another backup.
2711                     (and (not auto-save-p)
2712                          (not (verify-visited-file-modtime (current-buffer)))
2713                          (setq buffer-backed-up nil))
2714                     ;; Get rid of all undo records for this buffer.
2715                     (or (eq buffer-undo-list t)
2716                         (setq buffer-undo-list nil))
2717                     ;; Effectively copy the after-revert-hook status,
2718                     ;; since after-find-file will clobber it.
2719                     (let ((global-hook (default-value 'after-revert-hook))
2720                           (local-hook-p (local-variable-p 'after-revert-hook
2721                                                           (current-buffer)))
2722                           (local-hook (and (local-variable-p 'after-revert-hook
2723                                                              (current-buffer))
2724                                            after-revert-hook)))
2725                       (let (buffer-read-only
2726                             ;; Don't make undo records for the reversion.
2727                             (buffer-undo-list t))
2728                         (if revert-buffer-insert-file-contents-function
2729                             (funcall revert-buffer-insert-file-contents-function
2730                                      file-name auto-save-p)
2731                           (if (not (file-exists-p file-name))
2732                               (error "File %s no longer exists!" file-name))
2733                           ;; Bind buffer-file-name to nil
2734                           ;; so that we don't try to lock the file.
2735                           (let ((buffer-file-name nil))
2736                             (or auto-save-p
2737                                 (unlock-buffer)))
2738                           (widen)
2739                           (insert-file-contents file-name (not auto-save-p)
2740                                                 nil nil t)))
2741                       (goto-char (min opoint (point-max)))
2742                       ;; Recompute the truename in case changes in symlinks
2743                       ;; have changed the truename.
2744                       ;;XEmacs: already done by insert-file-contents
2745                       ;;(setq buffer-file-truename
2746                       ;;(abbreviate-file-name (file-truename buffer-file-name)))
2747                       (after-find-file nil nil t t preserve-modes)
2748                       ;; Run after-revert-hook as it was before we reverted.
2749                       (setq-default revert-buffer-internal-hook global-hook)
2750                       (if local-hook-p
2751                           (progn
2752                             (make-local-variable 'revert-buffer-internal-hook)
2753                             (setq revert-buffer-internal-hook local-hook))
2754                         (kill-local-variable 'revert-buffer-internal-hook))
2755                       (run-hooks 'revert-buffer-internal-hook)))
2756                    ((null newbuf)
2757                     ;; The resultant buffer is identical, alter
2758                     ;; modtime, update mods and exit
2759                     (set-visited-file-modtime)
2760                     (after-find-file nil nil t t t)
2761                     ;; We preserved modes above so fixup the local
2762                     ;; variables manually
2763                     (condition-case err
2764                         (hack-local-variables)
2765                       (error (lwarn 'local-variables 'warning
2766                                "File local-variables error: %s"
2767                                (error-message-string err)))))
2768                    (t t))
2769              t)))))
2770
2771 ;; #### something like `revert-buffer-compare-with-file' is a better name
2772 ;; #### why is the argument optional?
2773 (defun revert-buffer-internal (&optional file-name)
2774   "Read contents of FILE-NAME into a buffer, and compare to current buffer.
2775 Return nil if identical, and the new buffer if different."
2776
2777   (let* ((newbuf (get-buffer-create " *revert*"))
2778          bmin bmax)
2779     (save-excursion
2780       (set-buffer newbuf)
2781       (with-obsolete-variable '(before-change-function after-change-function)
2782         (let (buffer-read-only
2783               (buffer-undo-list t)
2784               after-change-function
2785               after-change-functions
2786               before-change-function
2787               before-change-functions)
2788           (if revert-buffer-insert-file-contents-function
2789               (funcall revert-buffer-insert-file-contents-function
2790                        file-name nil)
2791             (if (not (file-exists-p file-name))
2792                 (error "File %s no longer exists!" file-name))
2793             (widen)
2794             (insert-file-contents file-name nil nil nil t)
2795             (setq bmin (point-min)
2796                   bmax (point-max))))))
2797     (if (not (and (eq bmin (point-min))
2798                   (eq bmax (point-max))
2799                   (eq (compare-buffer-substrings
2800                        newbuf bmin bmax (current-buffer) bmin bmax) 0)))
2801         newbuf
2802       (and (kill-buffer newbuf) nil))))
2803
2804 (defun recover-file (file)
2805   "Visit file FILE, but get contents from its last auto-save file."
2806   ;; Actually putting the file name in the minibuffer should be used
2807   ;; only rarely.
2808   ;; Not just because users often use the default.
2809   (interactive "FRecover file: ")
2810   (setq file (expand-file-name file))
2811   (let ((handler (or (find-file-name-handler file 'recover-file)
2812                     (find-file-name-handler
2813                      (let ((buffer-file-name file))
2814                        (make-auto-save-file-name))
2815                      'recover-file))))
2816     (if handler
2817         (funcall handler 'recover-file file)
2818       (if (auto-save-file-name-p (file-name-nondirectory file))
2819           (error "%s is an auto-save file" file))
2820       (let ((file-name (let ((buffer-file-name file))
2821                          (make-auto-save-file-name))))
2822         (cond ((if (file-exists-p file)
2823                    (not (file-newer-than-file-p file-name file))
2824                  (not (file-exists-p file-name)))
2825                (error "Auto-save file %s not current" file-name))
2826               ((save-window-excursion
2827                  ;; XEmacs change: use insert-directory instead of
2828                  ;; calling ls directly.
2829                  (with-output-to-temp-buffer "*Directory*"
2830                    (buffer-disable-undo standard-output)
2831                    (save-excursion
2832                      (set-buffer "*Directory*")
2833                      (setq default-directory (file-name-directory file))
2834                      (insert-directory file
2835                                        (if (file-symlink-p file) "-lL" "-l"))
2836                      (setq default-directory (file-name-directory file-name))
2837                      (insert-directory file-name "-l")))
2838                  (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2839                (switch-to-buffer (find-file-noselect file t))
2840                (let ((buffer-read-only nil))
2841                  (erase-buffer)
2842                  (insert-file-contents file-name nil))
2843                (after-find-file nil nil t))
2844               (t (error "Recover-file cancelled.")))))))
2845
2846 (defun recover-session ()
2847   "Recover auto save files from a previous Emacs session.
2848 This command first displays a Dired buffer showing you the
2849 previous sessions that you could recover from.
2850 To choose one, move point to the proper line and then type C-c C-c.
2851 Then you'll be asked about a number of files to recover."
2852   (interactive)
2853   (unless (fboundp 'dired)
2854     (error "recover-session requires dired"))
2855   (if (null auto-save-list-file-prefix)
2856       (error
2857        "You set `auto-save-list-file-prefix' to disable making session files"))
2858   (dired (concat auto-save-list-file-prefix "*"))
2859   (goto-char (point-min))
2860   (or (looking-at "Move to the session you want to recover,")
2861       (let ((inhibit-read-only t))
2862         (insert "Move to the session you want to recover,\n"
2863                 "then type C-c C-c to select it.\n\n"
2864                 "You can also delete some of these files;\n"
2865                 "type d on a line to mark that file for deletion.\n\n")))
2866   (use-local-map (let ((map (make-sparse-keymap)))
2867                    (set-keymap-parents map (list (current-local-map)))
2868                    map))
2869   (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
2870
2871 (defun recover-session-finish ()
2872   "Choose one saved session to recover auto-save files from.
2873 This command is used in the special Dired buffer created by
2874 \\[recover-session]."
2875   (interactive)
2876   ;; Get the name of the session file to recover from.
2877   (let ((file (declare-fboundp (dired-get-filename)))
2878         files
2879         (buffer (get-buffer-create " *recover*")))
2880     ;; #### dired-do-flagged-delete in FSF.
2881     ;; This version is for ange-ftp
2882     ;;(dired-do-deletions t)
2883     ;; This version is for efs
2884     (declare-fboundp (dired-expunge-deletions))
2885     (unwind-protect
2886         (save-excursion
2887           ;; Read in the auto-save-list file.
2888           (set-buffer buffer)
2889           (erase-buffer)
2890           (insert-file-contents file)
2891           ;; Loop thru the text of that file
2892           ;; and get out the names of the files to recover.
2893           (while (not (eobp))
2894             (let (thisfile autofile)
2895               (if (eolp)
2896                   ;; This is a pair of lines for a non-file-visiting buffer.
2897                   ;; Get the auto-save file name and manufacture
2898                   ;; a "visited file name" from that.
2899                   (progn
2900                     (forward-line 1)
2901                     (setq autofile
2902                           (buffer-substring-no-properties
2903                            (point)
2904                            (save-excursion
2905                              (end-of-line)
2906                              (point))))
2907                     (setq thisfile
2908                           (expand-file-name
2909                            (substring
2910                             (file-name-nondirectory autofile)
2911                             1 -1)
2912                            (file-name-directory autofile)))
2913                     (forward-line 1))
2914                 ;; This pair of lines is a file-visiting
2915                 ;; buffer.  Use the visited file name.
2916                 (progn
2917                   (setq thisfile
2918                         (buffer-substring-no-properties
2919                          (point) (progn (end-of-line) (point))))
2920                   (forward-line 1)
2921                   (setq autofile
2922                         (buffer-substring-no-properties
2923                          (point) (progn (end-of-line) (point))))
2924                   (forward-line 1)))
2925               ;; Ignore a file if its auto-save file does not exist now.
2926               (if (file-exists-p autofile)
2927                   (setq files (cons thisfile files)))))
2928           (setq files (nreverse files))
2929           ;; The file contains a pair of line for each auto-saved buffer.
2930           ;; The first line of the pair contains the visited file name
2931           ;; or is empty if the buffer was not visiting a file.
2932           ;; The second line is the auto-save file name.
2933           (if files
2934               (map-y-or-n-p  "Recover %s? "
2935                              (lambda (file)
2936                                (condition-case nil
2937                                    (save-excursion (recover-file file))
2938                                  (error
2939                                   "Failed to recover `%s'" file)))
2940                              files
2941                              '("file" "files" "recover"))
2942             (message "No files can be recovered from this session now")))
2943       (kill-buffer buffer))))
2944
2945 (defun kill-some-buffers (&optional list)
2946   "For each buffer in LIST, ask whether to kill it.
2947 LIST defaults to all existing live buffers."
2948   (interactive)
2949   (if (null list)
2950       (setq list (buffer-list)))
2951   (while list
2952     (let* ((buffer (car list))
2953            (name (buffer-name buffer)))
2954       (and (not (string-equal name ""))
2955            (/= (aref name 0) ?\ )
2956            (yes-or-no-p
2957             (format
2958              (if (buffer-modified-p buffer)
2959                  (gettext "Buffer %s HAS BEEN EDITED.  Kill? ")
2960                (gettext "Buffer %s is unmodified.  Kill? "))
2961              name))
2962            (kill-buffer buffer)))
2963     (setq list (cdr list))))
2964 \f
2965 (defun auto-save-mode (arg)
2966   "Toggle auto-saving of contents of current buffer.
2967 With prefix argument ARG, turn auto-saving on if positive, else off."
2968   (interactive "P")
2969   (setq buffer-auto-save-file-name
2970         (and (if (null arg)
2971                  (or (not buffer-auto-save-file-name)
2972                      ;; If autosave is off because buffer has shrunk,
2973                      ;; then toggling should turn it on.
2974                      (< buffer-saved-size 0))
2975                (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2976              (if (and buffer-file-name auto-save-visited-file-name
2977                       (not buffer-read-only))
2978                  buffer-file-name
2979                (make-auto-save-file-name))))
2980   ;; If -1 was stored here, to temporarily turn off saving,
2981   ;; turn it back on.
2982   (and (< buffer-saved-size 0)
2983        (setq buffer-saved-size 0))
2984   (if (interactive-p)
2985       (if buffer-auto-save-file-name ;; rewritten for I18N3 snarfing
2986           (display-message 'command "Auto-save on (in this buffer)")
2987         (display-message 'command "Auto-save off (in this buffer)")))
2988   buffer-auto-save-file-name)
2989
2990 (defun rename-auto-save-file ()
2991   "Adjust current buffer's auto save file name for current conditions.
2992 Also rename any existing auto save file, if it was made in this session."
2993   (let ((osave buffer-auto-save-file-name))
2994     (setq buffer-auto-save-file-name
2995           (make-auto-save-file-name))
2996     (if (and osave buffer-auto-save-file-name
2997              (not (string= buffer-auto-save-file-name buffer-file-name))
2998              (not (string= buffer-auto-save-file-name osave))
2999              (file-exists-p osave)
3000              (recent-auto-save-p))
3001         (rename-file osave buffer-auto-save-file-name t))))
3002
3003 ;; make-auto-save-file-name and auto-save-file-name-p are now only in
3004 ;; auto-save.el.
3005
3006 \f
3007 (defun wildcard-to-regexp (wildcard)
3008   "Given a shell file name pattern WILDCARD, return an equivalent regexp.
3009 The generated regexp will match a filename iff the filename
3010 matches that wildcard according to shell rules.  Only wildcards known
3011 by `sh' are supported."
3012   (let* ((i (string-match "[[.*+\\^$?]" wildcard))
3013          ;; Copy the initial run of non-special characters.
3014          (result (substring wildcard 0 i))
3015          (len (length wildcard)))
3016     ;; If no special characters, we're almost done.
3017     (if i
3018         (while (< i len)
3019           (let ((ch (aref wildcard i))
3020                 j)
3021             (setq
3022              result
3023              (concat result
3024                      (cond
3025                       ((eq ch ?\[)      ; [...] maps to regexp char class
3026                        (progn
3027                          (setq i (1+ i))
3028                          (concat
3029                           (cond
3030                            ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
3031                             (progn
3032                               (setq i (1+ i))
3033                               (if (eq (aref wildcard i) ?\])
3034                                   (progn
3035                                     (setq i (1+ i))
3036                                     "[^]")
3037                                 "[^")))
3038                            ((eq (aref wildcard i) ?^)
3039                             ;; Found "[^".  Insert a `\0' character
3040                             ;; (which cannot happen in a filename)
3041                             ;; into the character class, so that `^'
3042                             ;; is not the first character after `[',
3043                             ;; and thus non-special in a regexp.
3044                             (progn
3045                               (setq i (1+ i))
3046                               "[\000^"))
3047                            ((eq (aref wildcard i) ?\])
3048                             ;; I don't think `]' can appear in a
3049                             ;; character class in a wildcard, but
3050                             ;; let's be general here.
3051                             (progn
3052                               (setq i (1+ i))
3053                               "[]"))
3054                            (t "["))
3055                           (prog1        ; copy everything upto next `]'.
3056                               (substring wildcard
3057                                          i
3058                                          (setq j (string-match
3059                                                   "]" wildcard i)))
3060                             (setq i (if j (1- j) (1- len)))))))
3061                       ((eq ch ?.)  "\\.")
3062                       ((eq ch ?*)  "[^\000]*")
3063                       ((eq ch ?+)  "\\+")
3064                       ((eq ch ?^)  "\\^")
3065                       ((eq ch ?$)  "\\$")
3066                       ((eq ch ?\\) #r"\\") ; probably cannot happen...
3067                       ((eq ch ??)  "[^\000]")
3068                       (t (char-to-string ch)))))
3069             (setq i (1+ i)))))
3070     ;; Shell wildcards should match the entire filename,
3071     ;; not its part.  Make the regexp say so.
3072     (concat "\\`" result "\\'")))
3073 \f
3074 (defcustom list-directory-brief-switches "-CF"
3075   "*Switches for list-directory to pass to `ls' for brief listing."
3076   :type 'string
3077   :group 'dired)
3078
3079 (defcustom list-directory-verbose-switches "-l"
3080   "*Switches for list-directory to pass to `ls' for verbose listing,"
3081   :type 'string
3082   :group 'dired)
3083
3084 (defun list-directory (dirname &optional verbose)
3085   "Display a list of files in or matching DIRNAME, a la `ls'.
3086 DIRNAME is globbed by the shell if necessary.
3087 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
3088 Actions controlled by variables `list-directory-brief-switches'
3089 and `list-directory-verbose-switches'."
3090   (interactive (let ((pfx current-prefix-arg))
3091                  (list (read-file-name (if pfx (gettext "List directory (verbose): ")
3092                                          (gettext "List directory (brief): "))
3093                                        nil default-directory nil)
3094                        pfx)))
3095   (let ((switches (if verbose list-directory-verbose-switches
3096                     list-directory-brief-switches)))
3097     (or dirname (setq dirname default-directory))
3098     (setq dirname (expand-file-name dirname))
3099     (with-output-to-temp-buffer "*Directory*"
3100       (buffer-disable-undo standard-output)
3101       (princ "Directory ")
3102       (princ dirname)
3103       (terpri)
3104       (save-excursion
3105         (set-buffer "*Directory*")
3106         (setq default-directory (file-name-directory dirname))
3107         (let ((wildcard (not (file-directory-p dirname))))
3108           (insert-directory dirname switches wildcard (not wildcard)))))))
3109
3110 (defvar insert-directory-program "ls"
3111   "Absolute or relative name of the `ls' program used by `insert-directory'.")
3112
3113 ;; insert-directory
3114 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
3115 ;;   FULL-DIRECTORY-P is nil.
3116 ;;   The single line of output must display FILE's name as it was
3117 ;;   given, namely, an absolute path name.
3118 ;; - must insert exactly one line for each file if WILDCARD or
3119 ;;   FULL-DIRECTORY-P is t, plus one optional "total" line
3120 ;;   before the file lines, plus optional text after the file lines.
3121 ;;   Lines are delimited by "\n", so filenames containing "\n" are not
3122 ;;   allowed.
3123 ;;   File lines should display the basename.
3124 ;; - must be consistent with
3125 ;;   - functions dired-move-to-filename, (these two define what a file line is)
3126 ;;               dired-move-to-end-of-filename,
3127 ;;               dired-between-files, (shortcut for (not (dired-move-to-filename)))
3128 ;;               dired-insert-headerline
3129 ;;               dired-after-subdir-garbage (defines what a "total" line is)
3130 ;;   - variable dired-subdir-regexp
3131 (defun insert-directory (file switches &optional wildcard full-directory-p)
3132   "Insert directory listing for FILE, formatted according to SWITCHES.
3133 Leaves point after the inserted text.
3134 SWITCHES may be a string of options, or a list of strings.
3135 Optional third arg WILDCARD means treat FILE as shell wildcard.
3136 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
3137 switches do not contain `d', so that a full listing is expected.
3138
3139 This works by running a directory listing program
3140 whose name is in the variable `insert-directory-program'.
3141 If WILDCARD, it also runs the shell specified by `shell-file-name'."
3142   ;; We need the directory in order to find the right handler.
3143   (let ((handler (find-file-name-handler (expand-file-name file)
3144                                          'insert-directory)))
3145     (cond
3146      (handler
3147       (funcall handler 'insert-directory file switches
3148                wildcard full-directory-p))
3149      (t
3150       (let* ((beg (point))
3151              (result
3152               (if wildcard
3153                   ;; Run ls in the directory of the file pattern we asked for.
3154                   (let ((default-directory
3155                           (if (file-name-absolute-p file)
3156                               (file-name-directory file)
3157                             (file-name-directory (expand-file-name file))))
3158                         (pattern (file-name-nondirectory file))
3159                         (start 0))
3160                     ;; Quote some characters that have special meanings in shells;
3161                     ;; but don't quote the wildcards--we want them to be special.
3162                     ;; We also currently don't quote the quoting characters
3163                     ;; in case people want to use them explicitly to quote
3164                     ;; wildcard characters.
3165                     ;;#### Unix-specific
3166                     (while (string-match "[ \t\n;<>&|()#$]" pattern start)
3167                       (setq pattern
3168                             (concat (substring pattern 0 (match-beginning 0))
3169                                     "\\"
3170                                     (substring pattern (match-beginning 0)))
3171                             start (1+ (match-end 0))))
3172                     (call-process shell-file-name nil t nil
3173                                   "-c" (concat "\\" ;; Disregard shell aliases!
3174                                                insert-directory-program
3175                                                " -d "
3176                                                (if (stringp switches)
3177                                                    switches
3178                                                  (mapconcat 'identity switches " "))
3179                                                " "
3180                                                pattern)))
3181                 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
3182                 ;; directory if FILE is a symbolic link.
3183                 (apply 'call-process
3184                        insert-directory-program nil t nil
3185                        (let (list)
3186                          (if (listp switches)
3187                              (setq list switches)
3188                            (if (not (equal switches ""))
3189                                (let ((switches switches))
3190                                  ;; Split the switches at any spaces
3191                                  ;; so we can pass separate options as separate args.
3192                                  (while (string-match " " switches)
3193                                    (setq list (cons (substring switches 0 (match-beginning 0))
3194                                                     list)
3195                                          switches (substring switches (match-end 0))))
3196                                  (setq list (cons switches list)))))
3197                          (append list
3198                                  (list
3199                                   (if full-directory-p
3200                                       (concat (file-name-as-directory file)
3201                                               ;;#### Unix-specific
3202                                               ".")
3203                                     file))))))))
3204         ;; If `insert-directory-program' failed, signal an error.
3205         (if (/= result 0)
3206             ;; On non-Posix systems, we cannot open a directory, so
3207             ;; don't even try, because that will always result in
3208             ;; the ubiquitous "Access denied".  Instead, show the
3209             ;; command line so the user can try to guess what went wrong.
3210             (error "Listing directory failed."))
3211
3212         (when (or (and (listp switches)
3213                        (member "--dired" switches))
3214                   (string-match "--dired\\>" switches))
3215           (forward-line -2)
3216           (when (looking-at "//SUBDIRED//")
3217             (delete-region (point) (progn (forward-line 1) (point)))
3218             (forward-line -1))
3219           (let ((end (line-end-position)))
3220             (forward-word 1)
3221             (forward-char 3)
3222             (while (< (point) end)
3223               (let ((start (+ beg (read (current-buffer))))
3224                     (end (+ beg (read (current-buffer)))))
3225                 (if (= (char-after end) ?\n)
3226                     (let ((filename-extent (make-extent start end)))
3227                       (set-extent-property filename-extent 'dired-file-name t)
3228                       (set-extent-property filename-extent 'start-open t)
3229                       (set-extent-property filename-extent 'end-open t))
3230                   ;; It seems that we can't trust ls's output as to
3231                   ;; byte positions of filenames.
3232                   (map-extents
3233                    #'(lambda (extent maparg)
3234                        (delete-extent extent)
3235                        nil)
3236                    nil beg (point) nil nil 'dired-file-name)
3237                   (end-of-line))))
3238             (goto-char end)
3239             (beginning-of-line)
3240             (delete-region (point) (progn (forward-line 2) (point))))))))))
3241
3242 (defvar kill-emacs-query-functions nil
3243   "Functions to call with no arguments to query about killing XEmacs.
3244 If any of these functions returns nil, killing Emacs is cancelled.
3245 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
3246 but `kill-emacs', the low level primitive, does not.
3247 See also `kill-emacs-hook'.")
3248
3249 (defun save-buffers-kill-emacs (&optional arg)
3250   "Offer to save each buffer, then kill this XEmacs process.
3251 With prefix arg, silently save all file-visiting buffers, then kill."
3252   (interactive "P")
3253   (save-some-buffers arg t)
3254   (and (or (not (memq t (mapcar #'(lambda (buf) (and (buffer-file-name buf)
3255                                                      (buffer-modified-p buf)))
3256                                 (buffer-list))))
3257            (yes-or-no-p "Modified buffers exist; exit anyway? "))
3258        (or (not (fboundp 'process-list))
3259            ;; process-list is not defined on VMS.
3260            (let ((processes (process-list))
3261                  active)
3262              (while processes
3263                (and (memq (process-status (car processes)) '(run stop open))
3264                     (let ((val (process-kill-without-query (car processes))))
3265                       (process-kill-without-query (car processes) val)
3266                       val)
3267                     (setq active t))
3268                (setq processes (cdr processes)))
3269              (or
3270               (not active)
3271               (save-excursion
3272                 (save-window-excursion
3273                   (delete-other-windows)
3274                   (list-processes)
3275                   (yes-or-no-p
3276                    "Active processes exist; kill them and exit anyway? "))))))
3277        ;; Query the user for other things, perhaps.
3278        (run-hook-with-args-until-failure 'kill-emacs-query-functions)
3279        (kill-emacs)))
3280
3281 (defun symlink-expand-file-name (filename)
3282   "If FILENAME is a symlink, return its non-symlink equivalent.
3283 Unlike `file-truename', this doesn't chase symlinks in directory
3284 components of the file or expand a relative pathname into an
3285 absolute one."
3286   (let ((count 20))
3287     (while (and (> count 0) (file-symlink-p filename))
3288       (setq filename (file-symlink-p filename)
3289             count (1- count)))
3290     (if (> count 0)
3291         filename
3292       (error "Apparently circular symlink path"))))
3293
3294 ;; Suggested by Michael Kifer <kifer@CS.SunySB.EDU>
3295 (defun file-remote-p (file-name)
3296   "Test whether FILE-NAME is looked for on a remote system."
3297   (cond ((not (declare-boundp allow-remote-paths)) nil)
3298         ((fboundp 'ange-ftp-ftp-path)
3299          (declare-fboundp (ange-ftp-ftp-path file-name)))
3300         ((fboundp 'efs-ftp-path)
3301          (declare-fboundp (efs-ftp-path file-name)))
3302         (t nil)))
3303
3304 ;; #### FSF has file-name-non-special here.
3305
3306 ;;; files.el ends here