FFI updates from Evgeny
[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                   (and (file-exists-p fn)
936                        (funcall predicate fn)))))
937
938 (defun find-file-noselect (filename &optional nowarn rawfile)
939   "Read file FILENAME into a buffer and return the buffer.
940 If a buffer exists visiting FILENAME, return that one, but
941 verify that the file has not changed since visited or saved.
942 The buffer is not selected, just returned to the caller.
943 If NOWARN is non-nil, warning messages will be suppressed.
944 If RAWFILE is non-nil, the file is read literally."
945   (setq filename (abbreviate-file-name (expand-file-name filename)))
946   ;; Try magic files first
947   (let ((mfa-item (find-file-find-magic filename)))
948     (if mfa-item
949         (funcall (cdr mfa-item) filename)
950
951       (let* ((buf (get-file-buffer filename))
952              (truename (abbreviate-file-name (file-truename filename)))
953              (number (nthcdr 10 (file-attributes truename)))
954 ;          ;; Find any buffer for a file which has same truename.
955 ;          (other (and (not buf) (find-buffer-visiting filename)))
956              (error nil))
957
958 ;     ;; Let user know if there is a buffer with the same truename.
959 ;      (if (and (not buf) same-truename (not nowarn))
960 ;         (message "%s and %s are the same file (%s)"
961 ;                  filename (buffer-file-name same-truename)
962 ;                  truename)
963 ;       (if (and (not buf) same-number (not nowarn))
964 ;         (message "%s and %s are the same file"
965 ;                  filename (buffer-file-name same-number))))
966 ;      ;; Optionally also find that buffer.
967 ;      (if (or find-file-existing-other-name find-file-visit-truename)
968 ;         (setq buf (or same-truename same-number)))
969
970         (when (and buf
971                    (or find-file-compare-truenames find-file-use-truenames)
972                    (not nowarn))
973           (save-excursion
974             (set-buffer buf)
975             (if (not (string-equal buffer-file-name filename))
976                 (message "%s and %s are the same file (%s)"
977                          filename buffer-file-name
978                          buffer-file-truename))))
979
980         (if buf
981             (or nowarn
982                 (verify-visited-file-modtime buf)
983                 (cond ((not (file-exists-p filename))
984                        (error "File %s no longer exists!" filename))
985                       ;; Certain files should be reverted automatically
986                       ;; if they have changed on disk and not in the buffer.
987                       ((and (not (buffer-modified-p buf))
988                             (dolist (rx revert-without-query nil)
989                               (when (string-match rx filename)
990                                 (return t))))
991                        (with-current-buffer buf
992                          (message "Reverting file %s..." filename)
993                          (revert-buffer t t)
994                          (message "Reverting file %s... done" filename)))
995                       ((yes-or-no-p
996                         (if (string= (file-name-nondirectory filename)
997                                      (buffer-name buf))
998                             (format
999                              (if (buffer-modified-p buf)
1000                                  (gettext "File %s changed on disk.  Discard your edits? ")
1001                                (gettext "File %s changed on disk.  Reread from disk? "))
1002                              (file-name-nondirectory filename))
1003                           (format
1004                            (if (buffer-modified-p buf)
1005                                (gettext "File %s changed on disk.  Discard your edits in %s? ")
1006                              (gettext "File %s changed on disk.  Reread from disk into %s? "))
1007                            (file-name-nondirectory filename)
1008                            (buffer-name buf))))
1009                        (with-current-buffer buf
1010                          (revert-buffer t t)))))
1011           ;; Else: we must create a new buffer for filename
1012           (save-excursion
1013 ;;; The truename stuff makes this obsolete.
1014 ;;;       (let* ((link-name (car (file-attributes filename)))
1015 ;;;              (linked-buf (and (stringp link-name)
1016 ;;;                               (get-file-buffer link-name))))
1017 ;;;         (if (bufferp linked-buf)
1018 ;;;             (message "Symbolic link to file in buffer %s"
1019 ;;;                      (buffer-name linked-buf))))
1020             (setq buf (create-file-buffer filename))
1021             ;; Catch various signals, such as QUIT, and kill the buffer
1022             ;; in that case.
1023             (condition-case data
1024                 (progn
1025                   (set-buffer-major-mode buf)
1026                   (set-buffer buf)
1027                   (erase-buffer)
1028                   (condition-case ()
1029                       (if rawfile
1030                           (insert-file-contents-literally filename t)
1031                         (insert-file-contents filename t))
1032                     (file-error
1033                      (when (and (file-exists-p filename)
1034                                 (not (file-readable-p filename)))
1035                        (signal 'file-error (list "File is not readable" filename)))
1036                      (if rawfile
1037                          ;; Unconditionally set error
1038                          (setq error t)
1039                        (or
1040                         ;; Run find-file-not-found-hooks until one returns non-nil.
1041                         (run-hook-with-args-until-success 'find-file-not-found-hooks)
1042                         ;; If they fail too, set error.
1043                         (setq error t)))))
1044                   ;; Find the file's truename, and maybe use that as visited name.
1045                   ;; automatically computed in XEmacs, unless jka-compr was used!
1046                   (unless buffer-file-truename
1047                     (setq buffer-file-truename truename))
1048                   (setq buffer-file-number number)
1049                   (and find-file-use-truenames
1050                        ;; This should be in C.  Put pathname
1051                        ;; abbreviations that have been explicitly
1052                        ;; requested back into the pathname.  Most
1053                        ;; importantly, strip out automounter /tmp_mnt
1054                        ;; directories so that auto-save will work
1055                        (setq buffer-file-name (abbreviate-file-name buffer-file-name)))
1056                   ;; Set buffer's default directory to that of the file.
1057                   (setq default-directory (file-name-directory buffer-file-name))
1058                   ;; Turn off backup files for certain file names.  Since
1059                   ;; this is a permanent local, the major mode won't eliminate it.
1060                   (and (not (funcall backup-enable-predicate buffer-file-name))
1061                        (progn
1062                          (make-local-variable 'backup-inhibited)
1063                          (setq backup-inhibited t)))
1064                   (if rawfile
1065                       ;; #### FSF 20.3 sets buffer-file-coding-system to
1066                       ;; `no-conversion' here.  Should we copy?  It also
1067                       ;; makes `find-file-literally' a local variable
1068                       ;; and sets it to t.
1069                       nil
1070                     (after-find-file error (not nowarn))
1071                     (setq buf (current-buffer))))
1072               (t
1073                (kill-buffer buf)
1074                (signal (car data) (cdr data))))
1075             ))
1076         buf))))
1077 \f
1078 ;; FSF has `insert-file-literally' and `find-file-literally' here.
1079
1080 (defvar after-find-file-from-revert-buffer nil)
1081
1082 (defun after-find-file (&optional error warn noauto
1083                                   after-find-file-from-revert-buffer
1084                                   nomodes)
1085   "Called after finding a file and by the default revert function.
1086 Sets buffer mode, parses local variables.
1087 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
1088 error in reading the file.  WARN non-nil means warn if there
1089 exists an auto-save file more recent than the visited file.
1090 NOAUTO means don't mess with auto-save mode.
1091 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1092  means this call was from `revert-buffer'.
1093 Fifth arg NOMODES non-nil means don't alter the file's modes.
1094 Finishes by calling the functions in `find-file-hooks'."
1095   (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1096   (if noninteractive
1097       nil
1098     (let* (not-serious
1099            (msg
1100             (cond ((and error (file-attributes buffer-file-name))
1101                    (setq buffer-read-only t)
1102                    (gettext "File exists, but cannot be read."))
1103                   ((not buffer-read-only)
1104                    (if (and warn
1105                             (file-newer-than-file-p (make-auto-save-file-name)
1106                                                     buffer-file-name))
1107                        (format "%s has auto save data; consider M-x recover-file"
1108                                (file-name-nondirectory buffer-file-name))
1109                      (setq not-serious t)
1110                      (if error (gettext "(New file)") nil)))
1111                   ((not error)
1112                    (setq not-serious t)
1113                    (gettext "Note: file is write protected"))
1114                   ((file-attributes (directory-file-name default-directory))
1115                    (gettext "File not found and directory write-protected"))
1116                   ((file-exists-p (file-name-directory buffer-file-name))
1117                    (setq buffer-read-only nil))
1118                   (t
1119                    ;; If the directory the buffer is in doesn't exist,
1120                    ;; offer to create it.  It's better to do this now
1121                    ;; than when we save the buffer, because we want
1122                    ;; autosaving to work.
1123                    (setq buffer-read-only nil)
1124                    ;; XEmacs
1125                    (or (file-exists-p (file-name-directory buffer-file-name))
1126                        (condition-case nil
1127                            (if (yes-or-no-p
1128                                 (format
1129                                  "The directory containing %s does not exist.  Create? "
1130                                  (abbreviate-file-name buffer-file-name)))
1131                                (make-directory (file-name-directory
1132                                                 buffer-file-name)
1133                                                t))
1134                          (quit
1135                           (kill-buffer (current-buffer))
1136                           (signal 'quit nil))))
1137                    nil))))
1138       (when msg
1139         (message "%s" msg)
1140         (unless not-serious
1141           (save-excursion (sit-for 1 t)))))
1142     (if (and auto-save-default (not noauto))
1143         (auto-save-mode t)))
1144   (unless nomodes
1145     (normal-mode t)
1146     (run-hooks 'find-file-hooks)))
1147
1148 (defun normal-mode (&optional find-file)
1149   "Choose the major mode for this buffer automatically.
1150 Also sets up any specified local variables of the file.
1151 Uses the visited file name, the -*- line, and the local variables spec.
1152
1153 This function is called automatically from `find-file'.  In that case,
1154 we may set up specified local variables depending on the value of
1155 `enable-local-variables': if it is t, we do; if it is nil, we don't;
1156 otherwise, we query.  `enable-local-variables' is ignored if you
1157 run `normal-mode' explicitly."
1158   (interactive)
1159   (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1160   (and (condition-case err
1161            (progn (set-auto-mode)
1162                   t)
1163          (error (message "File mode specification error: %s"
1164                          (prin1-to-string err))
1165                 nil))
1166        (condition-case err
1167            (hack-local-variables (not find-file))
1168          (error (lwarn 'local-variables 'warning
1169                   "File local-variables error: %s"
1170                   (error-message-string err))))))
1171
1172 ;; `auto-mode-alist' used to contain entries for modes in core and in packages.
1173 ;; The applicable entries are now located in the corresponding modes in
1174 ;; packages, the ones here are for core modes.  Ditto for
1175 ;; `interpreter-mode-alist' below.
1176 ;; Per Abrahamsen suggested splitting auto-mode-alist to
1177 ;; several distinct variables such as, in order of precedence,
1178 ;; `user-auto-mode-alist' for users, `package-auto-mode-alist' for
1179 ;; packages and `auto-mode-alist' (which might also be called
1180 ;; `default-auto-mode-alist') for default stuff, such as some of the
1181 ;; entries below.
1182
1183 (defvar auto-mode-alist
1184   '((#r"\.te?xt\'" . text-mode)
1185     (#r"\.el\'" . emacs-lisp-mode)
1186     (#r"\.c?l\(?:i?sp\)?\'" . lisp-mode)
1187     (#r"\.article\'" . text-mode)
1188     (#r"\.letter\'" . text-mode)
1189     ;; Mailer puts message to be edited in /tmp/Re.... or Message
1190     ;; #### Unix-specific!
1191     ("\\`/tmp/Re" . text-mode)
1192     ("/Message[0-9]*\\'" . text-mode)
1193     ;; some news reader is reported to use this
1194     ("^/tmp/fol/" . text-mode)
1195     ;; .emacs following a directory delimiter in either Unix or
1196     ;; Windows syntax.
1197     (#r"[/\][._].*emacs\'" . emacs-lisp-mode)
1198     (#r"\.ml\'" . lisp-mode)
1199     )
1200 "Alist of filename patterns vs. corresponding major mode functions.
1201 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1202 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1203 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1204 mode function to use.  FUNCTION will be called, unless it is nil.
1205
1206 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1207 calling FUNCTION (if it's not nil), we delete the suffix that matched
1208 REGEXP and search the list again for another match.")
1209
1210 (defvar interpreter-mode-alist
1211   '(("emacs" . emacs-lisp-mode))
1212   "Alist mapping interpreter names to major modes.
1213 This alist is used to guess the major mode of a file based on the
1214 contents of the first line.  This line often contains something like:
1215 #!/bin/sh
1216 but may contain something more imaginative like
1217 #! /bin/env python
1218 or
1219 eval 'exec perl -w -S $0 ${1+\"$@\"}'.
1220
1221 Each alist element looks like (INTERPRETER . MODE).
1222 The car of each element is a regular expression which is compared
1223 with the name of the interpreter specified in the first line.
1224 If it matches, mode MODE is selected.")
1225
1226 (defvar binary-file-regexps
1227   '(#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]\)\'")
1228   "List of regexps of filenames containing binary (non-text) data.")
1229
1230 ;(eval-when-compile
1231 ;  (require 'regexp-opt)
1232 ;  (list
1233 ;   (format "\\.\\(?:%s\\)\\'"
1234 ;          (regexp-opt
1235 ;           '(
1236 ;             ;; Compressed files
1237 ;             "7Z" "7z" "ARC" "EAR" "JAR" "LZH" "RAR" "WAR"
1238 ;             "XPI" "Z" "ZIP" "ZOO" "arc" "bz2" "ear" "gz"
1239 ;             "jar" "tar" "tgz" "tiff" "war" "xpi" "zip" "zoo"
1240 ;             "zoo" "lha" "lzh" "lzma" "xz"
1241 ;             ;; Code
1242 ;             "EXE" "exe" "elc" "o" "so" "a"
1243 ;             ;; Images
1244 ;             "gif" "jpeg" "jpg" "pbm" "pgm" "png" "pnm" "ppm"
1245 ;             "GIF" "JPEG" "JPG"
1246 ;             ;; Documents
1247 ;             "PDF" "odt" "pdf" "sxc" "sxd" "sxi" "sxm" "sxw" "doc")))))
1248
1249 (defvar inhibit-first-line-modes-regexps
1250   binary-file-regexps
1251   "List of regexps; if one matches a file name, don't look for `-*-'.")
1252
1253 (defvar inhibit-first-line-modes-suffixes nil
1254   "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1255 When checking `inhibit-first-line-modes-regexps', we first discard
1256 from the end of the file name anything that matches one of these regexps.")
1257
1258 (defvar user-init-file
1259   nil ; set by command-line
1260   "File name including directory of user's initialization file.
1261
1262 This normally defaults to \"~/.sxemacs/init.el\", if you are a XEmacs
1263 user you can get up and running quickly by symlinking \"~/.sxemacs\"
1264 to your old \"~/.xemacs\" directory.")
1265
1266 (defun set-auto-mode (&optional just-from-file-name)
1267   "Select major mode appropriate for current buffer.
1268 This checks for a -*- mode tag in the buffer's text,
1269 compares the filename against the entries in `auto-mode-alist',
1270 or checks the interpreter that runs this file against
1271 `interpreter-mode-alist'.
1272
1273 It does not check for the `mode:' local variable in the
1274 Local Variables section of the file; for that, use `hack-local-variables'.
1275
1276 If `enable-local-variables' is nil, this function does not check for a
1277 -*- mode tag.
1278
1279 If the optional argument JUST-FROM-FILE-NAME is non-nil,
1280 then we do not set anything but the major mode,
1281 and we don't even do that unless it would come from the file name."
1282   (save-excursion
1283     ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1284     ;; Do this by calling the hack-local-variables helper to avoid redundancy.
1285     ;; We bind enable-local-variables to nil this time because we're going to
1286     ;; call hack-local-variables-prop-line again later, "for real."  Note that
1287     ;; this temporary binding does not prevent hack-local-variables-prop-line
1288     ;; from setting the major mode.
1289     (or (and enable-local-variables
1290              (let ((enable-local-variables nil))
1291                (hack-local-variables-prop-line nil))
1292              )
1293         ;; It's not in the -*- line, so check the auto-mode-alist, unless
1294         ;; this buffer isn't associated with a file.
1295         (null buffer-file-name)
1296         (let ((name (file-name-sans-versions buffer-file-name))
1297               (keep-going t))
1298           (while keep-going
1299             (setq keep-going nil)
1300             (let ((alist auto-mode-alist)
1301                   (mode nil))
1302
1303               ;; Find first matching alist entry.
1304
1305               ;; #### This is incorrect. In NT, case sensitivity is a volume
1306               ;; property. For instance, NFS mounts *are* case sensitive.
1307               ;; Need internal function (file-name-case-sensitive f), F
1308               ;; being file or directory name. - kkm
1309               (let ((case-fold-search
1310                      (eq system-type 'windows-nt)))
1311                 (while (and (not mode) alist)
1312                   (if (string-match (car (car alist)) name)
1313                       (if (and (consp (cdr (car alist)))
1314                                (nth 2 (car alist)))
1315                           (progn
1316                             (setq mode (car (cdr (car alist)))
1317                                   name (substring name 0 (match-beginning 0))
1318                                   keep-going t))
1319                         (setq mode (cdr (car alist))
1320                               keep-going nil)))
1321                   (setq alist (cdr alist))))
1322               (unless just-from-file-name
1323                 ;; If we can't deduce a mode from the file name,
1324                 ;; look for an interpreter specified in the first line.
1325                 (if (and (null mode)
1326                          (save-excursion ; XEmacs
1327                            (goto-char (point-min))
1328                            (looking-at "#!")))
1329                     (let ((firstline
1330                            (buffer-substring
1331                             (point-min)
1332                             (save-excursion
1333                               (goto-char (point-min)) (end-of-line) (point)))))
1334                       (setq alist interpreter-mode-alist)
1335                       (while alist
1336                         (if (string-match (car (car alist)) firstline)
1337                             (progn
1338                               (setq mode (cdr (car alist)))
1339                               (setq alist nil))
1340                           (setq alist (cdr alist)))))))
1341               (if mode
1342                   (if (not (fboundp mode))
1343                       (let ((name (declare-fboundp (package-get-package-provider mode))))
1344                         (if name
1345                             (message "Mode %s is not installed.  Download package %s" mode name)
1346                           (message "Mode %s either doesn't exist or is not a known package" mode))
1347                         (sit-for 2)
1348                         (error "%s" mode))
1349                     (unless (and just-from-file-name
1350                                  (or
1351                                   ;; Don't reinvoke major mode.
1352                                   (eq mode major-mode)
1353                                   ;; Don't lose on minor modes.
1354                                   (assq mode minor-mode-alist)))
1355                       (funcall mode))))))))))
1356
1357 (defvar hack-local-variables-hook nil
1358   "Normal hook run after processing a file's local variables specs.
1359 Major modes can use this to examine user-specified local variables
1360 in order to initialize other data structure based on them.
1361
1362 This hook runs even if there were no local variables or if their
1363 evaluation was suppressed.  See also `enable-local-variables' and
1364 `enable-local-eval'.")
1365
1366 (defun hack-local-variables (&optional force)
1367   "Parse, and bind or evaluate as appropriate, any local variables
1368 for current buffer."
1369   ;; Don't look for -*- if this file name matches any
1370   ;; of the regexps in inhibit-first-line-modes-regexps.
1371   (if (or (null buffer-file-name) ; don't lose if buffer has no file!
1372           (not (let ((temp inhibit-first-line-modes-regexps)
1373                      (name (if buffer-file-name
1374                                (file-name-sans-versions buffer-file-name)
1375                              (buffer-name))))
1376                  (while (let ((sufs inhibit-first-line-modes-suffixes))
1377                           (while (and sufs (not
1378                                             (string-match (car sufs) name)))
1379                             (setq sufs (cdr sufs)))
1380                           sufs)
1381                    (setq name (substring name 0 (match-beginning 0))))
1382                  (while (and temp
1383                              (not (string-match (car temp) name)))
1384                    (setq temp (cdr temp))
1385                    temp))))
1386       (progn
1387         ;; Look for variables in the -*- line.
1388         (hack-local-variables-prop-line force)
1389         ;; Look for "Local variables:" block in last page.
1390         (hack-local-variables-last-page force)))
1391   (run-hooks 'hack-local-variables-hook))
1392
1393 ;;; Local variables may be specified in the last page of the file (within 3k
1394 ;;; from the end of the file and after the last ^L) in the form
1395 ;;;
1396 ;;;   Local variables:
1397 ;;;   variable-name: variable-value
1398 ;;;   end:
1399 ;;;
1400 ;;; The lines may begin with a common prefix, like ";;;   " in the above
1401 ;;; example.  They may also have a common suffix (" */" for example).  In
1402 ;;; this form, the local variable "mode" can be used to change the major
1403 ;;; mode, and the local variable "eval" can be used to evaluate an arbitrary
1404 ;;; form.
1405 ;;;
1406 ;;; Local variables may also be specified in the first line of the file.
1407 ;;; Embedded in this line are a pair of "-*-" sequences.  What lies between
1408 ;;; them are variable-name/variable-value pairs, like:
1409 ;;;
1410 ;;;      -*- mode: emacs-lisp -*-
1411 ;;; or   -*- mode: postscript; version-control: never -*-
1412 ;;; or   -*- tags-file-name: "/foo/bar/TAGS" -*-
1413 ;;;
1414 ;;; The local variable "eval" is not used with this form. For hysterical
1415 ;;; reasons, the syntax "-*- modename -*-" is allowed as well.
1416 ;;;
1417
1418 (defun hack-local-variables-p (modeline)
1419   (or (eq enable-local-variables t)
1420       (and enable-local-variables
1421            (save-window-excursion
1422              (condition-case nil
1423                  (switch-to-buffer (current-buffer))
1424                (error
1425                 ;; If we fail to switch in the selected window,
1426                 ;; it is probably a minibuffer.
1427                 ;; So try another window.
1428                 (condition-case nil
1429                     (switch-to-buffer-other-window (current-buffer))
1430                   (error
1431                    (switch-to-buffer-other-frame (current-buffer))))))
1432              (or modeline (save-excursion
1433                              (beginning-of-line)
1434                              (set-window-start (selected-window) (point))))
1435              (y-or-n-p (format
1436                         "Set local variables as specified %s of %s? "
1437                         (if modeline "in -*- line" "at end")
1438                         (if buffer-file-name
1439                             (file-name-nondirectory buffer-file-name)
1440                             (concat "buffer " (buffer-name)))))))))
1441
1442 (defun hack-local-variables-last-page (&optional force)
1443   ;; Set local variables set in the "Local Variables:" block of the last page.
1444   (save-excursion
1445     (goto-char (point-max))
1446     (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1447     (if (let ((case-fold-search t))
1448           (and (search-forward "Local Variables:" nil t)
1449                (or force
1450                    (hack-local-variables-p nil))))
1451         (let ((continue t)
1452               prefix prefixlen suffix start
1453               (enable-local-eval enable-local-eval))
1454           ;; The prefix is what comes before "local variables:" in its line.
1455           ;; The suffix is what comes after "local variables:" in its line.
1456           (skip-chars-forward " \t")
1457           (or (eolp)
1458               (setq suffix (buffer-substring (point)
1459                                              (progn (end-of-line) (point)))))
1460           (goto-char (match-beginning 0))
1461           (or (bolp)
1462               (setq prefix
1463                     (buffer-substring (point)
1464                                       (progn (beginning-of-line) (point)))))
1465           (if prefix (setq prefixlen (length prefix)
1466                            prefix (regexp-quote prefix)))
1467           (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1468           (while continue
1469             ;; Look at next local variable spec.
1470             (if selective-display (re-search-forward "[\n\C-m]")
1471               (forward-line 1))
1472             ;; Skip the prefix, if any.
1473             (if prefix
1474                 (if (looking-at prefix)
1475                     (forward-char prefixlen)
1476                   (error "Local variables entry is missing the prefix")))
1477             ;; Find the variable name; strip whitespace.
1478             (skip-chars-forward " \t")
1479             (setq start (point))
1480             (skip-chars-forward "^:\n")
1481             (if (eolp) (error "Missing colon in local variables entry"))
1482             (skip-chars-backward " \t")
1483             (let* ((str (buffer-substring start (point)))
1484                    (var (read str))
1485                   val)
1486               ;; Setting variable named "end" means end of list.
1487               (if (string-equal (downcase str) "end")
1488                   (setq continue nil)
1489                 ;; Otherwise read the variable value.
1490                 (skip-chars-forward "^:")
1491                 (forward-char 1)
1492                 (setq val (read (current-buffer)))
1493                 (skip-chars-backward "\n")
1494                 (skip-chars-forward " \t")
1495                 (or (if suffix (looking-at suffix) (eolp))
1496                     (error "Local variables entry is terminated incorrectly"))
1497                 ;; Set the variable.  "Variables" mode and eval are funny.
1498                 (hack-one-local-variable var val))))))))
1499
1500 ;; jwz - New Version 20.1/19.15
1501 (defun hack-local-variables-prop-line (&optional force)
1502   ;; Set local variables specified in the -*- line.
1503   ;; Returns t if mode was set.
1504   (let ((result nil))
1505     (save-excursion
1506       (goto-char (point-min))
1507       (skip-chars-forward " \t\n\r")
1508       (let ((end (save-excursion
1509                    ;; If the file begins with "#!"
1510                    ;; (un*x exec interpreter magic), look
1511                    ;; for mode frobs in the first two
1512                    ;; lines.  You cannot necessarily
1513                    ;; put them in the first line of
1514                    ;; such a file without screwing up
1515                    ;; the interpreter invocation.
1516                    (end-of-line (and (looking-at "^#!") 2))
1517                    (point))))
1518         ;; Parse the -*- line into the `result' alist.
1519         (cond ((not (search-forward "-*-" end t))
1520                ;; doesn't have one.
1521                (setq force t))
1522               ((looking-at "[ \t]*\\([^ \t\n\r:;]+?\\)\\([ \t]*-\\*-\\)")
1523                ;; Antiquated form: "-*- ModeName -*-".
1524                (setq result
1525                      (list (cons 'mode
1526                                  (intern (buffer-substring
1527                                           (match-beginning 1)
1528                                           (match-end 1)))))
1529                      ))
1530               (t
1531                ;; Usual form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1532                ;; (last ";" is optional).
1533                (save-excursion
1534                  (if (search-forward "-*-" end t)
1535                      (setq end (- (point) 3))
1536                    (error "-*- not terminated before end of line")))
1537                (while (< (point) end)
1538                  (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1539                      (error "malformed -*- line"))
1540                  (goto-char (match-end 0))
1541                  ;; There used to be a downcase here,
1542                  ;; but the manual didn't say so,
1543                  ;; and people want to set var names that aren't all lc.
1544                  (let ((key (intern (buffer-substring
1545                                      (match-beginning 1)
1546                                      (match-end 1))))
1547                        (val (save-restriction
1548                               (narrow-to-region (point) end)
1549                               (read (current-buffer)))))
1550                    ;; Case sensitivity!  Icepicks in my forehead!
1551                    (if (equal (downcase (symbol-name key)) "mode")
1552                        (setq key 'mode))
1553                    (setq result (cons (cons key val) result))
1554                    (skip-chars-forward " \t;")))
1555                (setq result (nreverse result))))))
1556
1557     (let ((set-any-p (or force
1558                          ;; It's OK to force null specifications.
1559                          (null result)
1560                          ;; It's OK to force mode-only specifications.
1561                          (let ((remaining result)
1562                                (mode-specs-only t))
1563                            (while remaining
1564                              (if (eq (car (car remaining)) 'mode)
1565                                  (setq remaining (cdr remaining))
1566                                ;; Otherwise, we have a real local.
1567                                (setq mode-specs-only nil
1568                                      remaining nil))
1569                              )
1570                            mode-specs-only)
1571                          ;; Otherwise, check.
1572                          (hack-local-variables-p t)))
1573           (mode-p nil))
1574       (while result
1575         (let ((key (car (car result)))
1576               (val (cdr (car result))))
1577           (cond ((eq key 'mode)
1578                  (setq mode-p t)
1579                  (let ((mode (intern (concat (downcase (symbol-name val))
1580                                              "-mode"))))
1581                    ;; Without this guard, `normal-mode' would potentially run
1582                    ;; the major mode function twice: once via `set-auto-mode'
1583                    ;; and once via `hack-local-variables'.
1584                    (if (not (eq mode major-mode))
1585                        (funcall mode))
1586                    ))
1587                 (set-any-p
1588                  (hack-one-local-variable key val))
1589                 (t
1590                  nil)))
1591         (setq result (cdr result)))
1592       mode-p)))
1593
1594 (defconst ignored-local-variables
1595   (list 'enable-local-eval)
1596   "Variables to be ignored in a file's local variable spec.")
1597
1598 ;; Get confirmation before setting these variables as locals in a file.
1599 (put 'debugger 'risky-local-variable t)
1600 (put 'enable-local-eval 'risky-local-variable t)
1601 (put 'ignored-local-variables 'risky-local-variable t)
1602 (put 'eval 'risky-local-variable t)
1603 (put 'file-name-handler-alist 'risky-local-variable t)
1604 (put 'minor-mode-map-alist 'risky-local-variable t)
1605 (put 'after-load-alist 'risky-local-variable t)
1606 (put 'buffer-file-name 'risky-local-variable t)
1607 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1608 (put 'buffer-file-truename 'risky-local-variable t)
1609 (put 'exec-path 'risky-local-variable t)
1610 (put 'load-path 'risky-local-variable t)
1611 (put 'exec-directory 'risky-local-variable t)
1612 (put 'process-environment 'risky-local-variable t)
1613 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1614 (put 'outline-level 'risky-local-variable t)
1615 (put 'rmail-output-file-alist 'risky-local-variable t)
1616
1617 ;; This one is safe because the user gets to check it before it is used.
1618 (put 'compile-command 'safe-local-variable t)
1619
1620 ;(defun hack-one-local-variable-quotep (exp)
1621 ;  (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1622
1623 ;; "Set" one variable in a local variables spec.
1624 ;; A few variable names are treated specially.
1625 (defun hack-one-local-variable (var val)
1626   (cond ((eq var 'mode)
1627          (funcall (intern (concat (downcase (symbol-name val))
1628                                   "-mode"))))
1629         ((memq var ignored-local-variables)
1630          nil)
1631         ;; "Setting" eval means either eval it or do nothing.
1632         ;; Likewise for setting hook variables.
1633         ((or (get var 'risky-local-variable)
1634              (and
1635               (string-match #r"-hooks?$\|-functions?$\|-forms?$\|-program$\|-command$"
1636                             (symbol-name var))
1637               (not (get var 'safe-local-variable))))
1638 ;        ;; Permit evaling a put of a harmless property
1639 ;        ;; if the args do nothing tricky.
1640 ;        (if (or (and (eq var 'eval)
1641 ;                     (consp val)
1642 ;                     (eq (car val) 'put)
1643 ;                     (hack-one-local-variable-quotep (nth 1 val))
1644 ;                     (hack-one-local-variable-quotep (nth 2 val))
1645 ;                     ;; Only allow safe values of lisp-indent-hook;
1646 ;                     ;; not functions.
1647 ;                     (or (numberp (nth 3 val))
1648 ;                         (equal (nth 3 val) ''defun))
1649 ;                     (memq (nth 1 (nth 2 val))
1650 ;                           '(lisp-indent-hook)))
1651          (if (and (not (zerop (user-uid)))
1652                   (or (eq enable-local-eval t)
1653                       (and enable-local-eval
1654                            (save-window-excursion
1655                              (switch-to-buffer (current-buffer))
1656                              (save-excursion
1657                                (beginning-of-line)
1658                                (set-window-start (selected-window) (point)))
1659                              (setq enable-local-eval
1660                                    (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1661                                                      (file-name-nondirectory buffer-file-name))))))))
1662              (if (eq var 'eval)
1663                  (save-excursion (eval val))
1664                (make-local-variable var)
1665                (set var val))
1666            (message "Ignoring `eval:' in file's local variables")))
1667         ;; Ordinary variable, really set it.
1668         (t (make-local-variable var)
1669            (set var val))))
1670 \f
1671 (defcustom change-major-mode-with-file-name t
1672   "*Non-nil means \\[write-file] should set the major mode from the file name.
1673 However, the mode will not be changed if
1674 \(1) a local variables list or the `-*-' line specifies a major mode, or
1675 \(2) the current major mode is a \"special\" mode,
1676 \    not suitable for ordinary files, or
1677 \(3) the new file name does not particularly specify any mode."
1678   :type 'boolean
1679   :group 'editing-basics)
1680
1681 (defun set-visited-file-name (filename &optional no-query along-with-file)
1682   "Change name of file visited in current buffer to FILENAME.
1683 The next time the buffer is saved it will go in the newly specified file.
1684 nil or empty string as argument means make buffer not be visiting any file.
1685 Remember to delete the initial contents of the minibuffer
1686 if you wish to pass an empty string as the argument.
1687
1688 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1689 confirmation in the case where another buffer is already visiting FILENAME.
1690
1691 The optional third argument ALONG-WITH-FILE, if non-nil, means that
1692 the old visited file has been renamed to the new name FILENAME."
1693   (interactive "FSet visited file name: ")
1694   (if (buffer-base-buffer)
1695       (error "An indirect buffer cannot visit a file"))
1696   (let (truename)
1697     (if filename
1698         (setq filename
1699               (if (string-equal filename "")
1700                   nil
1701                 (expand-file-name filename))))
1702     (if filename
1703         (progn
1704           (setq truename (file-truename filename))
1705           ;; #### Do we need to check if truename is non-nil?
1706           (if find-file-use-truenames
1707               (setq filename truename))))
1708     (let ((buffer (and filename (find-buffer-visiting filename))))
1709       (and buffer (not (eq buffer (current-buffer)))
1710            (not no-query)
1711            (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1712                                    filename)))
1713            (error "Aborted")))
1714     (or (equal filename buffer-file-name)
1715         (progn
1716           (and filename (lock-buffer filename))
1717           (unlock-buffer)))
1718     (setq buffer-file-name filename)
1719     (if filename                        ; make buffer name reflect filename.
1720         (let ((new-name (file-name-nondirectory buffer-file-name)))
1721           (if (string= new-name "")
1722               (error "Empty file name"))
1723           (setq default-directory (file-name-directory buffer-file-name))
1724           (or (string= new-name (buffer-name))
1725               (rename-buffer new-name t))))
1726     (setq buffer-backed-up nil)
1727     (or along-with-file
1728         (clear-visited-file-modtime))
1729     (compute-buffer-file-truename) ; insert-file-contents does this too.
1730 ;    ;; Abbreviate the file names of the buffer.
1731 ;    (if truename
1732 ;        (progn
1733 ;          (setq buffer-file-truename (abbreviate-file-name truename))
1734 ;          (if find-file-visit-truename
1735 ;              (setq buffer-file-name buffer-file-truename))))
1736     (setq buffer-file-number
1737           (if filename
1738               (nthcdr 10 (file-attributes buffer-file-name))
1739               nil)))
1740   ;; write-file-hooks is normally used for things like ftp-find-file
1741   ;; that visit things that are not local files as if they were files.
1742   ;; Changing to visit an ordinary local file instead should flush the hook.
1743   (kill-local-variable 'write-file-hooks)
1744   (kill-local-variable 'after-save-hook)
1745   (kill-local-variable 'local-write-file-hooks)
1746   (kill-local-variable 'write-file-data-hooks)
1747   (kill-local-variable 'revert-buffer-function)
1748   (kill-local-variable 'backup-inhibited)
1749   ;; If buffer was read-only because of version control,
1750   ;; that reason is gone now, so make it writable.
1751   (if-boundp 'vc-mode
1752       (progn
1753         (if vc-mode
1754             (setq buffer-read-only nil))
1755         (kill-local-variable 'vc-mode)))
1756   ;; Turn off backup files for certain file names.
1757   ;; Since this is a permanent local, the major mode won't eliminate it.
1758   (and buffer-file-name
1759        (not (funcall backup-enable-predicate buffer-file-name))
1760        (progn
1761          (make-local-variable 'backup-inhibited)
1762          (setq backup-inhibited t)))
1763   (let ((oauto buffer-auto-save-file-name))
1764     ;; If auto-save was not already on, turn it on if appropriate.
1765     (if (not buffer-auto-save-file-name)
1766         (and buffer-file-name auto-save-default
1767              (auto-save-mode t))
1768       ;; If auto save is on, start using a new name.
1769       ;; We deliberately don't rename or delete the old auto save
1770       ;; for the old visited file name.  This is because perhaps
1771       ;; the user wants to save the new state and then compare with the
1772       ;; previous state from the auto save file.
1773       (setq buffer-auto-save-file-name
1774             (make-auto-save-file-name)))
1775     ;; Rename the old auto save file if any.
1776     (and oauto buffer-auto-save-file-name
1777          (file-exists-p oauto)
1778          (rename-file oauto buffer-auto-save-file-name t)))
1779   (if buffer-file-name
1780       (not along-with-file)
1781       (set-buffer-modified-p t))
1782   ;; Update the major mode, if the file name determines it.
1783   (condition-case nil
1784       ;; Don't change the mode if it is special.
1785       (or (not change-major-mode-with-file-name)
1786           (get major-mode 'mode-class)
1787           ;; Don't change the mode if the local variable list specifies it.
1788           (hack-local-variables t)
1789           (set-auto-mode t))
1790     (error nil))
1791   ;; #### ??
1792   (run-hooks 'after-set-visited-file-name-hooks))
1793
1794 (defun write-file (filename &optional confirm codesys)
1795   "Write current buffer into file FILENAME.
1796 Makes buffer visit that file, and marks it not modified.
1797 If the buffer is already visiting a file, you can specify
1798 a directory name as FILENAME, to write a file of the same
1799 old name in that directory.
1800 If optional second arg CONFIRM is non-nil,
1801 ask for confirmation for overwriting an existing file.
1802 Under XEmacs/Mule, optional third argument specifies the
1803 coding system to use when encoding the file.  Interactively,
1804 with a prefix argument, you will be prompted for the coding system."
1805 ;;  (interactive "FWrite file: ")
1806   (interactive
1807    (list (if buffer-file-name
1808              (read-file-name "Write file: "
1809                                  nil nil nil nil)
1810            (read-file-name "Write file: "
1811                                (cdr (assq 'default-directory
1812                                           (buffer-local-variables)))
1813                                nil nil (buffer-name)))
1814          t
1815          (if (and current-prefix-arg (featurep 'file-coding))
1816              (read-coding-system "Coding system: "))))
1817   (and (eq (current-buffer) mouse-grabbed-buffer)
1818        (error "Can't write minibuffer window"))
1819   (or (null filename) (string-equal filename "")
1820       (progn
1821         ;; If arg is just a directory,
1822         ;; use same file name, but in that directory.
1823         (if (and (file-directory-p filename) buffer-file-name)
1824             (setq filename (concat (file-name-as-directory filename)
1825                                    (file-name-nondirectory buffer-file-name))))
1826         (and confirm
1827              (file-exists-p filename)
1828              (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1829                  (error "Canceled")))
1830         (set-visited-file-name filename)))
1831   (set-buffer-modified-p t)
1832   (setq buffer-read-only nil)
1833   (if codesys
1834       (let ((buffer-file-coding-system (get-coding-system codesys)))
1835         (save-buffer))
1836     (save-buffer)))
1837 \f
1838 (defun backup-buffer ()
1839   "Make a backup of the disk file visited by the current buffer, if appropriate.
1840 This is normally done before saving the buffer the first time.
1841 If the value is non-nil, it is the result of `file-modes' on the original file;
1842 this means that the caller, after saving the buffer, should change the modes
1843 of the new file to agree with the old modes."
1844   (if buffer-file-name
1845       (let ((handler (find-file-name-handler buffer-file-name 'backup-buffer)))
1846         (if handler
1847             (funcall handler 'backup-buffer)
1848           (if (and make-backup-files
1849                    (not backup-inhibited)
1850                    (not buffer-backed-up)
1851                    (file-exists-p buffer-file-name)
1852                    (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1853                          '(?- ?l)))
1854               (let ((real-file-name buffer-file-name)
1855                     backup-info backupname targets setmodes)
1856                 ;; If specified name is a symbolic link, chase it to the target.
1857                 ;; Thus we make the backups in the directory where the real file is.
1858                 (setq real-file-name (file-chase-links real-file-name))
1859                 (setq backup-info (find-backup-file-name real-file-name)
1860                       backupname (car backup-info)
1861                       targets (cdr backup-info))
1862 ;;;     (if (file-directory-p buffer-file-name)
1863 ;;;         (error "Cannot save buffer in directory %s" buffer-file-name))
1864                 (if backup-info
1865                     (condition-case ()
1866                         (let ((delete-old-versions
1867                                ;; If have old versions to maybe delete,
1868                                ;; ask the user to confirm now, before doing anything.
1869                                ;; But don't actually delete till later.
1870                                (and targets
1871                                     (or (eq delete-old-versions t)
1872                                         (eq delete-old-versions nil))
1873                                     (or delete-old-versions
1874                                         (y-or-n-p (format "Delete excess backup versions of %s? "
1875                                                           real-file-name))))))
1876                           ;; Actually write the back up file.
1877                           (condition-case ()
1878                               (if (or file-precious-flag
1879                                         ;                         (file-symlink-p buffer-file-name)
1880                                       backup-by-copying
1881                                       (and backup-by-copying-when-linked
1882                                            (> (file-nlinks real-file-name) 1))
1883                                       (and backup-by-copying-when-mismatch
1884                                            (let ((attr (file-attributes real-file-name)))
1885                                              (or (nth 9 attr)
1886                                                  (not (file-ownership-preserved-p real-file-name))))))
1887                                   (condition-case ()
1888                                       (copy-file real-file-name backupname t t)
1889                                     (file-error
1890                                      ;; If copying fails because file BACKUPNAME
1891                                      ;; is not writable, delete that file and try again.
1892                                      (if (and (file-exists-p backupname)
1893                                               (not (file-writable-p backupname)))
1894                                          (delete-file backupname))
1895                                      (copy-file real-file-name backupname t t)))
1896                                 ;; rename-file should delete old backup.
1897                                 (rename-file real-file-name backupname t)
1898                                 (setq setmodes (file-modes backupname)))
1899                             (file-error
1900                              ;; If trouble writing the backup, write
1901                              ;; it in `auto-save-directory'.  Fall
1902                              ;; back to $HOME if that's not possible.
1903                              (setq backupname
1904                                    (expand-file-name "%backup%~"
1905                                                      (or (when (and auto-save-directory
1906                                                                     (file-writable-p auto-save-directory))
1907                                                            auto-save-directory)
1908                                                          (getenv "HOME"))))
1909                              (message "Cannot write backup file; backing up in %s" backupname)
1910                              (sleep-for 1)
1911                              (condition-case ()
1912                                  (copy-file real-file-name backupname t t)
1913                                (file-error
1914                                 ;; If copying fails because file BACKUPNAME
1915                                 ;; is not writable, delete that file and try again.
1916                                 (if (and (file-exists-p backupname)
1917                                          (not (file-writable-p backupname)))
1918                                     (delete-file backupname))
1919                                 (copy-file real-file-name backupname t t)))))
1920                           (setq buffer-backed-up t)
1921                           ;; Now delete the old versions, if desired.
1922                           (if delete-old-versions
1923                               (while targets
1924                                 (ignore-file-errors (delete-file (car targets)))
1925                                 (setq targets (cdr targets))))
1926                           setmodes)
1927                       (file-error nil)))))))))
1928
1929 (defun file-name-sans-versions (name &optional keep-backup-version)
1930   "Return FILENAME sans backup versions or strings.
1931 This is a separate procedure so your site-init or startup file can
1932 redefine it.
1933 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1934 we do not remove backup version numbers, only true file version numbers."
1935   (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1936     (if handler
1937         (funcall handler 'file-name-sans-versions name keep-backup-version)
1938       (substring name 0
1939                  (if keep-backup-version
1940                      (length name)
1941                    (or (string-match #r"\.~[0-9.]+~\'" name)
1942                        ;; XEmacs - VC uses extensions like ".~tagname~" or ".~1.1.5.2~"
1943                        (let ((pos (string-match "\\.~\\([^.~ \t]+\\|[0-9.]+\\)~\\'" name)))
1944                          (and pos
1945                               ;; #### - is this filesystem check too paranoid?
1946                               (file-exists-p (substring name 0 pos))
1947                               pos))
1948                        (string-match "~\\'" name)
1949                        (length name)))))))
1950
1951 (defun file-ownership-preserved-p (file)
1952   "Return t if deleting FILE and rewriting it would preserve the owner."
1953   (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1954     (if handler
1955         (funcall handler 'file-ownership-preserved-p file)
1956       (let ((attributes (file-attributes file)))
1957         ;; Return t if the file doesn't exist, since it's true that no
1958         ;; information would be lost by an (attempted) delete and create.
1959         (or (null attributes)
1960             (= (nth 2 attributes) (user-uid)))))))
1961
1962 (defun file-name-sans-extension (filename)
1963   "Return FILENAME sans final \"extension\".
1964 The extension, in a file name, is the part that follows the last `.'."
1965   (save-match-data
1966     (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1967           directory)
1968       (if (string-match #r"\.[^.]*\'" file)
1969           (if (setq directory (file-name-directory filename))
1970               (expand-file-name (substring file 0 (match-beginning 0))
1971                                 directory)
1972             (substring file 0 (match-beginning 0)))
1973         filename))))
1974
1975 (defun file-name-extension (filename &optional period)
1976   "Return FILENAME's final \"extension\".
1977 The extension, in a file name, is the part that follows the last `.'.
1978 Return nil for extensionless file names such as `foo'.
1979 Return the empty string for file names such as `foo.'.
1980
1981 If PERIOD is non-nil, then the returned value includes the period
1982 that delimits the extension, and if FILENAME has no extension,
1983 the value is \"\"."
1984   (save-match-data
1985     (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
1986       (if (string-match #r"\.[^.]*\'" file)
1987           (substring file (+ (match-beginning 0) (if period 0 1)))
1988         (if period
1989             "")))))
1990
1991 (defun make-backup-file-name (file)
1992   "Create the non-numeric backup file name for FILE.
1993 This is a separate function so you can redefine it for customization."
1994   ;; FSF has code here for MS-DOS short filenames, not supported in XEmacs.
1995     (concat file "~"))
1996
1997 (defun backup-file-name-p (file)
1998   "Return non-nil if FILE is a backup file name (numeric or not).
1999 This is a separate function so you can redefine it for customization.
2000 You may need to redefine `file-name-sans-versions' as well."
2001   (string-match "~\\'" file))
2002
2003 ;; This is used in various files.
2004 ;; The usage of bv-length is not very clean,
2005 ;; but I can't see a good alternative,
2006 ;; so as of now I am leaving it alone.
2007 (defun backup-extract-version (fn)
2008   "Given the name of a numeric backup file, return the backup number.
2009 Uses the free variable `bv-length', whose value should be
2010 the index in the name where the version number begins."
2011   (declare (special bv-length))
2012   (if (and (string-match "[0-9]+~\\'" fn bv-length)
2013            (= (match-beginning 0) bv-length))
2014       (string-to-int (substring fn bv-length -1))
2015       0))
2016
2017 (defun find-backup-file-name (fn)
2018   "Find a file name for a backup file, and suggestions for deletions.
2019 Value is a list whose car is the name for the backup file
2020  and whose cdr is a list of old versions to consider deleting now.
2021 If the value is nil, don't make a backup."
2022   (declare (special bv-length))
2023   (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
2024     ;; Run a handler for this function so that ange-ftp can refuse to do it.
2025     (if handler
2026         (funcall handler 'find-backup-file-name fn)
2027       (if (eq version-control 'never)
2028           (list (make-backup-file-name fn))
2029         (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
2030                ;; used by backup-extract-version:
2031                (bv-length (length base-versions))
2032                possibilities
2033                (versions nil)
2034                (high-water-mark 0)
2035                (deserve-versions-p nil)
2036                (number-to-delete 0))
2037           (condition-case ()
2038               (setq possibilities (file-name-all-completions
2039                                    base-versions
2040                                    (file-name-directory fn))
2041                     versions (sort (mapcar
2042                                     #'backup-extract-version
2043                                     possibilities)
2044                                    '<)
2045                     high-water-mark (apply #'max 0 versions)
2046                     deserve-versions-p (or version-control
2047                                            (> high-water-mark 0))
2048                     number-to-delete (- (length versions)
2049                                         kept-old-versions kept-new-versions -1))
2050             (file-error
2051              (setq possibilities nil)))
2052           (if (not deserve-versions-p)
2053               (list (make-backup-file-name fn))
2054             (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
2055                   (if (and (> number-to-delete 0)
2056                            ;; Delete nothing if there is overflow
2057                            ;; in the number of versions to keep.
2058                            (>= (+ kept-new-versions kept-old-versions -1) 0))
2059                       (mapcar #'(lambda (n)
2060                                   (concat fn ".~" (int-to-string n) "~"))
2061                               (let ((v (nthcdr kept-old-versions versions)))
2062                                 (rplacd (nthcdr (1- number-to-delete) v) ())
2063                                 v))))))))))
2064
2065 (defun file-nlinks (filename)
2066   "Return number of names file FILENAME has."
2067   (car (cdr (file-attributes filename))))
2068
2069 (defun file-relative-name (filename &optional directory)
2070   "Convert FILENAME to be relative to DIRECTORY (default: default-directory).
2071 This function returns a relative file name which is equivalent to FILENAME
2072 when used with that default directory as the default.
2073 If this is impossible (which can happen on MS Windows when the file name
2074 and directory use different drive names) then it returns FILENAME."
2075   (save-match-data
2076     (let ((fname (expand-file-name filename)))
2077       (setq directory (file-name-as-directory
2078                        (expand-file-name (or directory default-directory))))
2079       ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2080       ;; drive names, they can't be relative, so return the absolute name.
2081       (if (and (eq system-type 'windows-nt)
2082                (not (string-equal (substring fname  0 2)
2083                                   (substring directory 0 2))))
2084           filename
2085         (let ((ancestor ".")
2086               (fname-dir (file-name-as-directory fname)))
2087           (while (and (not (string-match (concat "^" (regexp-quote directory))
2088                                          fname-dir))
2089                       (not (string-match (concat "^" (regexp-quote directory)) fname)))
2090             (setq directory (file-name-directory (substring directory 0 -1))
2091                   ancestor (if (equal ancestor ".")
2092                                ".."
2093                              (concat "../" ancestor))))
2094           ;; Now ancestor is empty, or .., or ../.., etc.
2095           (if (string-match (concat "^" (regexp-quote directory)) fname)
2096               ;; We matched within FNAME's directory part.
2097               ;; Add the rest of FNAME onto ANCESTOR.
2098               (let ((rest (substring fname (match-end 0))))
2099                 (if (and (equal ancestor ".")
2100                          (not (equal rest "")))
2101                     ;; But don't bother with ANCESTOR if it would give us `./'.
2102                     rest
2103                   (concat (file-name-as-directory ancestor) rest)))
2104             ;; We matched FNAME's directory equivalent.
2105             ancestor))))))
2106 \f
2107 (defun save-buffer (&optional args)
2108   "Save current buffer in visited file if modified.  Versions described below.
2109
2110 By default, makes the previous version into a backup file
2111  if previously requested or if this is the first save.
2112 With 1 or 3 \\[universal-argument]'s, marks this version
2113  to become a backup when the next save is done.
2114 With 2 or 3 \\[universal-argument]'s,
2115  unconditionally makes the previous version into a backup file.
2116 With argument of 0, never makes the previous version into a backup file.
2117
2118 If a file's name is FOO, the names of its numbered backup versions are
2119  FOO.~i~ for various integers i.  A non-numbered backup file is called FOO~.
2120 Numeric backups (rather than FOO~) will be made if value of
2121  `version-control' is not the atom `never' and either there are already
2122  numeric versions of the file being backed up, or `version-control' is
2123  non-nil.
2124 We don't want excessive versions piling up, so there are variables
2125  `kept-old-versions', which tells XEmacs how many oldest versions to keep,
2126  and `kept-new-versions', which tells how many newest versions to keep.
2127  Defaults are 2 old versions and 2 new.
2128 `dired-kept-versions' controls dired's clean-directory (.) command.
2129 If `delete-old-versions' is nil, system will query user
2130  before trimming versions.  Otherwise it does it silently."
2131   (interactive "_p")
2132   (let ((modp (buffer-modified-p))
2133         (large (> (buffer-size) 50000))
2134         (make-backup-files (or (and make-backup-files (not (eq args 0)))
2135                                (memq args '(16 64)))))
2136     (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2137     (if (and modp large) (display-message
2138                           'progress (format "Saving file %s..."
2139                                             (buffer-file-name))))
2140     (basic-save-buffer)
2141     (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2142
2143 (defun delete-auto-save-file-if-necessary (&optional force)
2144   "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2145 Normally delete only if the file was written by this XEmacs
2146 since the last real save, but optional arg FORCE non-nil means delete anyway."
2147   (and buffer-auto-save-file-name delete-auto-save-files
2148        (not (string= buffer-file-name buffer-auto-save-file-name))
2149        (or force (recent-auto-save-p))
2150        (progn
2151          (ignore-file-errors (delete-file buffer-auto-save-file-name))
2152          (set-buffer-auto-saved))))
2153
2154 ;; XEmacs change (from Sun)
2155 ;; used to communicate with continue-save-buffer:
2156 (defvar continue-save-buffer-hooks-tail nil)
2157
2158 ;; Not in FSFmacs
2159 (defun basic-write-file-data (realname truename)
2160   ;; call the hooks until the bytes are put
2161   ;; call write-region as a last resort
2162   (let ((region-written nil)
2163         (hooks write-file-data-hooks))
2164     (while (and hooks (not region-written))
2165       (setq region-written (funcall (car hooks) realname)
2166             hooks (cdr hooks)))
2167     (if (not region-written)
2168         (write-region (point-min) (point-max) realname nil t truename))))
2169
2170 (put 'after-save-hook 'permanent-local t)
2171 (defvar after-save-hook nil
2172   "Normal hook that is run after a buffer is saved to its file.
2173 These hooks are considered to pertain to the visited file.
2174 So this list is cleared if you change the visited file name.")
2175
2176 (defun files-fetch-hook-value (hook)
2177   (let ((localval (symbol-value hook))
2178         (globalval (default-value hook)))
2179     (if (memq t localval)
2180         (setq localval (append (delq t localval) (delq t globalval))))
2181     localval))
2182
2183 (defun basic-save-buffer ()
2184   "Save the current buffer in its visited file, if it has been modified.
2185 After saving the buffer, run `after-save-hook'."
2186   (interactive)
2187   (save-excursion
2188     ;; In an indirect buffer, save its base buffer instead.
2189     (if (buffer-base-buffer)
2190         (set-buffer (buffer-base-buffer)))
2191     (if (buffer-modified-p)
2192         (let ((recent-save (recent-auto-save-p)))
2193           ;; If buffer has no file name, ask user for one.
2194           (or buffer-file-name
2195               (let ((filename
2196                      (expand-file-name
2197                       (read-file-name "File to save in: ") nil)))
2198                 (and (file-exists-p filename)
2199                      (or (y-or-n-p (format "File `%s' exists; overwrite? "
2200                                            filename))
2201                          (error "Canceled")))
2202                 (set-visited-file-name filename)))
2203           (or (verify-visited-file-modtime (current-buffer))
2204               (not (file-exists-p buffer-file-name))
2205               (yes-or-no-p
2206                (format "%s has changed since visited or saved.  Save anyway? "
2207                        (file-name-nondirectory buffer-file-name)))
2208               (error "Save not confirmed"))
2209           (save-restriction
2210             (widen)
2211
2212             ;; Add final newline if required.  See `require-final-newline'.
2213             (when (and (not (eq (char-before (point-max)) ?\n)) ; common case
2214                        (char-before (point-max))                ; empty buffer?
2215                        (not (and (eq selective-display t)
2216                                  (eq (char-before (point-max)) ?\r)))
2217                        (or (eq require-final-newline t)
2218                            (and require-final-newline
2219                                 (y-or-n-p
2220                                  (format "Buffer %s does not end in newline.  Add one? "
2221                                          (buffer-name))))))
2222               (save-excursion
2223                 (goto-char (point-max))
2224                 (insert ?\n)))
2225
2226             ;; Run the write-file-hooks until one returns non-nil.
2227             ;; Bind after-save-hook to nil while running the
2228             ;; write-file-hooks so that if this function is called
2229             ;; recursively (from inside a write-file-hook) the
2230             ;; after-hooks will only get run once (from the
2231             ;; outermost call).
2232             ;;
2233             ;; Ugh, have to duplicate logic of run-hook-with-args-until-success
2234             (let ((hooks (append (files-fetch-hook-value 'write-contents-hooks)
2235                                  (files-fetch-hook-value
2236                                   'local-write-file-hooks)
2237                                  (files-fetch-hook-value 'write-file-hooks)))
2238                   (after-save-hook nil)
2239                   (local-write-file-hooks nil)
2240                   (write-contents-hooks nil)
2241                   (write-file-hooks nil)
2242                   done)
2243               (while (and hooks
2244                           (let ((continue-save-buffer-hooks-tail hooks))
2245                             (not (setq done (funcall (car hooks))))))
2246                 (setq hooks (cdr hooks)))
2247               ;; If a hook returned t, file is already "written".
2248               ;; Otherwise, write it the usual way now.
2249               (if (not done)
2250                   (basic-save-buffer-1)))
2251             ;; XEmacs: next two clauses (buffer-file-number setting and
2252             ;; set-file-modes) moved into basic-save-buffer-1.
2253             )
2254           ;; If the auto-save file was recent before this command,
2255           ;; delete it now.
2256           (delete-auto-save-file-if-necessary recent-save)
2257           ;; Support VC `implicit' locking.
2258           (if-fboundp 'vc-after-save
2259             (vc-after-save))
2260           (run-hooks 'after-save-hook))
2261       (display-message 'no-log "(No changes need to be saved)"))))
2262
2263 ;; This does the "real job" of writing a buffer into its visited file
2264 ;; and making a backup file.  This is what is normally done
2265 ;; but inhibited if one of write-file-hooks returns non-nil.
2266 ;; It returns a value to store in setmodes.
2267 (defun basic-save-buffer-1 ()
2268   (let (setmodes tempsetmodes)
2269     (if (not (file-writable-p buffer-file-name))
2270         (let ((dir (file-name-directory buffer-file-name)))
2271           (if (not (file-directory-p dir))
2272               (error "%s is not a directory" dir)
2273             (if (not (file-exists-p buffer-file-name))
2274                 (error "Directory %s write-protected" dir)
2275               (if (yes-or-no-p
2276                    (format "File %s is write-protected; try to save anyway? "
2277                            (file-name-nondirectory
2278                             buffer-file-name)))
2279                   (setq tempsetmodes t)
2280                 (error
2281                  "Attempt to save to a file which you aren't allowed to write"))))))
2282     (or buffer-backed-up
2283         (setq setmodes (backup-buffer)))
2284     (let ((dir (file-name-directory buffer-file-name)))
2285       (if (and file-precious-flag
2286                (file-writable-p dir))
2287           ;; If file is precious, write temp name, then rename it.
2288           ;; This requires write access to the containing dir,
2289           ;; which is why we don't try it if we don't have that access.
2290           (let ((realname buffer-file-name)
2291                 tempname nogood i succeed
2292                 (old-modtime (visited-file-modtime)))
2293             (setq i 0)
2294             (setq nogood t)
2295             ;; Find the temporary name to write under.
2296             (while nogood
2297               (setq tempname (format "%s#tmp#%d" dir i))
2298               (setq nogood (file-exists-p tempname))
2299               (setq i (1+ i)))
2300             (unwind-protect
2301                 (progn (clear-visited-file-modtime)
2302                        (write-region (point-min) (point-max)
2303                                      tempname nil realname
2304                                      buffer-file-truename)
2305                        (setq succeed t))
2306               ;; If writing the temp file fails,
2307               ;; delete the temp file.
2308               (or succeed
2309                   (progn
2310                     (delete-file tempname)
2311                     (set-visited-file-modtime old-modtime))))
2312             ;; Since we have created an entirely new file
2313             ;; and renamed it, make sure it gets the
2314             ;; right permission bits set.
2315             (setq setmodes (file-modes buffer-file-name))
2316             ;; We succeeded in writing the temp file,
2317             ;; so rename it.
2318             (rename-file tempname buffer-file-name t))
2319         ;; If file not writable, see if we can make it writable
2320         ;; temporarily while we write it.
2321         ;; But no need to do so if we have just backed it up
2322         ;; (setmodes is set) because that says we're superseding.
2323         (cond ((and tempsetmodes (not setmodes))
2324                ;; Change the mode back, after writing.
2325                (setq setmodes (file-modes buffer-file-name))
2326                (set-file-modes buffer-file-name 511)))
2327         (basic-write-file-data buffer-file-name buffer-file-truename)))
2328     (setq buffer-file-number
2329           (if buffer-file-name
2330               (nth 10 (file-attributes buffer-file-name))
2331             nil))
2332     (if setmodes
2333         (condition-case ()
2334             (set-file-modes buffer-file-name setmodes)
2335           (error nil)))))
2336
2337 ;; XEmacs change, from Sun
2338 (defun continue-save-buffer ()
2339   "Provide a clean way for a write-file-hook to wrap AROUND
2340 the execution of the remaining hooks and writing to disk.
2341 Do not call this function except from a functions
2342 on the `write-file-hooks' or `write-contents-hooks' list.
2343 A hook that calls this function must return non-nil,
2344 to signal completion to its caller.  `continue-save-buffer'
2345 always returns non-nil."
2346   (let ((hooks (cdr (or continue-save-buffer-hooks-tail
2347                         (error
2348          "continue-save-buffer called outside a write-file-hook!"))))
2349         (done nil))
2350     ;; Do something like this:
2351     ;; (let ((write-file-hooks hooks)) (basic-save-buffer))
2352     ;; First run the rest of the hooks.
2353     (while (and hooks
2354                 (let ((continue-save-buffer-hooks-tail hooks))
2355                   (not (setq done (funcall (car hooks))))))
2356       (setq hooks (cdr hooks)))
2357     ;;
2358     ;; If a hook returned t, file is already "written".
2359     (if (not done)
2360         (basic-save-buffer-1))
2361     'continue-save-buffer))
2362
2363 (defcustom save-some-buffers-query-display-buffer t
2364   "*Non-nil makes `\\[save-some-buffers]' switch to the buffer offered for saving."
2365   :type 'boolean
2366   :group 'editing-basics)
2367
2368 (defun save-some-buffers (&optional arg exiting)
2369   "Save some modified file-visiting buffers.  Asks user about each one.
2370 Optional argument (the prefix) non-nil means save all with no questions.
2371 Optional second argument EXITING means ask about certain non-file buffers
2372  as well as about file buffers."
2373   (interactive "P")
2374   (save-excursion
2375     ;; `delete-other-windows' can bomb during autoloads generation, so
2376     ;; guard it well.
2377     (if (or noninteractive
2378             (eq (selected-window) (minibuffer-window))
2379             (not save-some-buffers-query-display-buffer))
2380         ;; If playing with windows is unsafe or undesired, just do the
2381         ;; usual drill.
2382         (save-some-buffers-1 arg exiting nil)
2383       ;; Else, protect the windows.
2384       (when (save-window-excursion
2385               (save-some-buffers-1 arg exiting t))
2386         ;; Force redisplay.
2387         (sit-for 0)))))
2388
2389 ;; XEmacs - do not use queried flag
2390 (defun save-some-buffers-1 (arg exiting switch-buffer)
2391   (let* ((switched nil)
2392          (last-buffer nil)
2393          (files-done
2394           (map-y-or-n-p
2395            (lambda (buffer)
2396              (prog1
2397                  (and (buffer-modified-p buffer)
2398                       (not (buffer-base-buffer buffer))
2399                       ;; XEmacs addition:
2400                       (not (symbol-value-in-buffer 'save-buffers-skip buffer))
2401                       (or
2402                        (buffer-file-name buffer)
2403                        (and exiting
2404                             (progn
2405                               (set-buffer buffer)
2406                               (and buffer-offer-save (> (buffer-size) 0)))))
2407                       (if arg
2408                           t
2409                         ;; #### We should provide a per-buffer means to
2410                         ;; disable the switching.  For instance, you might
2411                         ;; want to turn it off for buffers the contents of
2412                         ;; which is meaningless to humans, such as
2413                         ;; `.newsrc.eld'.
2414                         (when (and switch-buffer
2415                                    ;; map-y-or-n-p is displaying help
2416                                    (not (eq last-buffer buffer)))
2417                           (unless (one-window-p)
2418                             (delete-other-windows))
2419                           (setq switched t)
2420                           ;; #### Consider using `display-buffer' here for 21.1!
2421                           ;;(display-buffer buffer nil (selected-frame)))
2422                           (switch-to-buffer buffer t))
2423                         (if (buffer-file-name buffer)
2424                             (format "Save file %s? "
2425                                     (buffer-file-name buffer))
2426                           (format "Save buffer %s? "
2427                                   (buffer-name buffer)))))
2428                (setq last-buffer buffer)))
2429            (lambda (buffer)
2430              (set-buffer buffer)
2431              (condition-case ()
2432                  (save-buffer)
2433                (error nil)))
2434            (buffer-list)
2435            '("buffer" "buffers" "save")
2436            ;;instead of this we just say "yes all", "no all", etc.
2437            ;;"save all the rest"
2438            ;;"save only this buffer" "save no more buffers")
2439            ;; this is rather bogus. --ben
2440            ;; (it makes the dialog box too big, and you get an error
2441            ;; "wrong type argument: framep, nil" when you hit q after
2442            ;; choosing the option from the dialog box)
2443
2444            ;; We should fix the dialog box rather than disabling
2445            ;; this!  --hniksic
2446            (list (list ?\C-r (lambda (buf)
2447                                ;; #### FSF has an EXIT-ACTION argument
2448                                ;; to `view-buffer'.
2449                                (declare-fboundp (view-buffer buf))
2450                                (with-boundp 'view-exit-action
2451                                  (setq view-exit-action
2452                                        (lambda (ignore)
2453                                          (exit-recursive-edit))))
2454                                (recursive-edit)
2455                                ;; Return nil to ask about BUF again.
2456                                nil)
2457                        "%_Display Buffer"))))
2458          (abbrevs-done
2459           (and save-abbrevs abbrevs-changed
2460                (progn
2461                  (if (or arg
2462                          (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
2463                      (write-abbrev-file nil))
2464                  ;; Don't keep bothering user if he says no.
2465                  (setq abbrevs-changed nil)
2466                  t))))
2467     (or (> files-done 0) abbrevs-done
2468         (display-message 'no-log "(No files need saving)"))
2469     switched))
2470
2471 \f
2472 (defun not-modified (&optional arg)
2473   "Mark current buffer as unmodified, not needing to be saved.
2474 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2475
2476 It is not a good idea to use this function in Lisp programs, because it
2477 prints a message in the minibuffer.  Instead, use `set-buffer-modified-p'."
2478   (interactive "_P")
2479   (if arg ;; rewritten for I18N3 snarfing
2480       (display-message 'command "Modification-flag set")
2481     (display-message 'command "Modification-flag cleared"))
2482   (set-buffer-modified-p arg))
2483
2484 (defun toggle-read-only (&optional arg)
2485   "Toggle the current buffer's read-only status.
2486 With arg, set read-only iff arg is positive."
2487   (interactive "_P")
2488   (setq buffer-read-only
2489         (if (null arg)
2490             (not buffer-read-only)
2491             (> (prefix-numeric-value arg) 0)))
2492   ;; Force modeline redisplay
2493   (redraw-modeline))
2494
2495 (defun insert-file (filename &optional codesys)
2496   "Insert contents of file FILENAME into buffer after point.
2497 Set mark after the inserted text.
2498
2499 Under XEmacs/Mule, optional second argument specifies the
2500 coding system to use when decoding the file.  Interactively,
2501 with a prefix argument, you will be prompted for the coding system.
2502
2503 This function is meant for the user to run interactively.
2504 Don't call it from programs!  Use `insert-file-contents' instead.
2505 \(Its calling sequence is different; see its documentation)."
2506   (interactive "*fInsert file: \nZCoding system: ")
2507   (if (file-directory-p filename)
2508       (signal 'file-error (list "Opening input file" "file is a directory"
2509                                 filename)))
2510   (let ((tem
2511          (if codesys
2512              (let ((coding-system-for-read
2513                     (get-coding-system codesys)))
2514                (insert-file-contents filename))
2515            (insert-file-contents filename))))
2516     (push-mark (+ (point) (car (cdr tem))))))
2517
2518 (defun append-to-file (start end filename &optional codesys)
2519   "Append the contents of the region to the end of file FILENAME.
2520 When called from a function, expects three arguments,
2521 START, END and FILENAME.  START and END are buffer positions
2522 saying what text to write.
2523 Under XEmacs/Mule, optional fourth argument specifies the
2524 coding system to use when encoding the file.  Interactively,
2525 with a prefix argument, you will be prompted for the coding system."
2526   (interactive "r\nFAppend to file: \nZCoding system: ")
2527   (if codesys
2528       (let ((buffer-file-coding-system (get-coding-system codesys)))
2529         (write-region start end filename t))
2530     (write-region start end filename t)))
2531
2532 (defun file-newest-backup (filename)
2533   "Return most recent backup file for FILENAME or nil if no backups exist."
2534   (let* ((filename (expand-file-name filename))
2535          (file (file-name-nondirectory filename))
2536          (dir  (file-name-directory    filename))
2537          (comp (file-name-all-completions file dir))
2538          newest)
2539     (while comp
2540       (setq file (concat dir (car comp))
2541             comp (cdr comp))
2542       (if (and (backup-file-name-p file)
2543                (or (null newest) (file-newer-than-file-p file newest)))
2544           (setq newest file)))
2545     newest))
2546
2547 (defun rename-uniquely ()
2548   "Rename current buffer to a similar name not already taken.
2549 This function is useful for creating multiple shell process buffers
2550 or multiple mail buffers, etc."
2551   (interactive)
2552   (save-match-data
2553     (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2554                                (not (and buffer-file-name
2555                                          (string= (buffer-name)
2556                                                   (file-name-nondirectory
2557                                                    buffer-file-name)))))
2558                           ;; If the existing buffer name has a <NNN>,
2559                           ;; which isn't part of the file name (if any),
2560                           ;; then get rid of that.
2561                           (substring (buffer-name) 0 (match-beginning 0))
2562                         (buffer-name)))
2563            (new-buf (generate-new-buffer base-name))
2564            (name (buffer-name new-buf)))
2565       (kill-buffer new-buf)
2566       (rename-buffer name)
2567       (redraw-modeline))))
2568
2569 (defun make-directory-path (path)
2570   "Create all the directories along path that don't exist yet."
2571   (interactive "Fdirectory path to create: ")
2572   (make-directory path t))
2573
2574 (defun make-directory (dir &optional parents)
2575   "Create the directory DIR and any nonexistent parent dirs.
2576 Interactively, the default choice of directory to create
2577 is the current default directory for file names.
2578 That is useful when you have visited a file in a nonexistent directory.
2579
2580 Noninteractively, the second (optional) argument PARENTS says whether
2581 to create parent directories if they don't exist."
2582   (interactive (list (let ((current-prefix-arg current-prefix-arg))
2583                        (read-directory-name "Create directory: "))
2584                      current-prefix-arg))
2585   (let ((handler (find-file-name-handler dir 'make-directory)))
2586     (if handler
2587         (funcall handler 'make-directory dir parents)
2588       (if (not parents)
2589           (make-directory-internal dir)
2590         (let ((dir (directory-file-name (expand-file-name dir)))
2591               create-list)
2592           (while (not (file-exists-p dir))
2593             (setq create-list (cons dir create-list)
2594                   dir (directory-file-name (file-name-directory dir))))
2595           (while create-list
2596             (make-directory-internal (car create-list))
2597             (setq create-list (cdr create-list))))))))
2598 \f
2599 (put 'revert-buffer-function 'permanent-local t)
2600 (defvar revert-buffer-function nil
2601   "Function to use to revert this buffer, or nil to do the default.
2602 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2603 which are the arguments that `revert-buffer' received.")
2604
2605 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2606 (defvar revert-buffer-insert-file-contents-function nil
2607   "Function to use to insert contents when reverting this buffer.
2608 Gets two args, first the nominal file name to use,
2609 and second, t if reading the auto-save file.
2610 If the current buffer contents are to be discarded, the function must do
2611 so itself.")
2612
2613 (defvar before-revert-hook nil
2614   "Normal hook for `revert-buffer' to run before reverting.
2615 If `revert-buffer-function' is used to override the normal revert
2616 mechanism, this hook is not used.")
2617
2618 (defvar after-revert-hook nil
2619   "Normal hook for `revert-buffer' to run after reverting.
2620 Note that the hook value that it runs is the value that was in effect
2621 before reverting; that makes a difference if you have buffer-local
2622 hook functions.
2623
2624 If `revert-buffer-function' is used to override the normal revert
2625 mechanism, this hook is not used.")
2626
2627 (defvar revert-buffer-internal-hook nil
2628   "Don't use this.")
2629
2630 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2631   "Replace the buffer text with the text of the visited file on disk.
2632 This undoes all changes since the file was visited or saved.
2633 With a prefix argument, offer to revert from latest auto-save file, if
2634 that is more recent than the visited file.
2635
2636 This command also refreshes certain special buffers that contain text
2637 which doesn't come from a file, but reflects some other data base
2638 instead: for example, Dired buffers and buffer-list buffers.  This is
2639 implemented by having the modes set `revert-buffer-function'.
2640
2641 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2642 to revert from the auto-save file when this is nil.  Note that the
2643 sense of this argument is the reverse of the prefix argument, for the
2644 sake of backward compatibility.  IGNORE-AUTO is optional, defaulting
2645 to nil.
2646
2647 Optional second argument NOCONFIRM means don't ask for confirmation at
2648 all.
2649
2650 Optional third argument PRESERVE-MODES non-nil means don't alter
2651 the buffer's modes.  Otherwise, reinitialize them using `normal-mode'.
2652
2653 If the value of `revert-buffer-function' is non-nil, it is called to
2654 do all the work for this command.  Otherwise, the hooks
2655 `before-revert-hook' and `after-revert-hook' are run at the beginning
2656 and the end, and if `revert-buffer-insert-file-contents-function' is
2657 non-nil, it is called instead of rereading visited file contents.
2658
2659 If the buffer-modified flag is nil, and we are not reverting from an
2660 auto-save file, then compare the contents of the buffer and the file.
2661 Revert only if they differ."
2662
2663   ;; I admit it's odd to reverse the sense of the prefix argument, but
2664   ;; there is a lot of code out there which assumes that the first
2665   ;; argument should be t to avoid consulting the auto-save file, and
2666   ;; there's no straightforward way to encourage authors to notice a
2667   ;; reversal of the argument sense.  So I'm just changing the user
2668   ;; interface, but leaving the programmatic interface the same.
2669   (interactive (list (not current-prefix-arg)))
2670   (if revert-buffer-function
2671       (funcall revert-buffer-function ignore-auto noconfirm)
2672     (let* ((opoint (point))
2673            (newbuf nil)
2674            (found nil)
2675            (delay-prompt nil)
2676            (auto-save-p (and (not ignore-auto)
2677                              (recent-auto-save-p)
2678                              buffer-auto-save-file-name
2679                              (file-readable-p buffer-auto-save-file-name)
2680                              (y-or-n-p
2681    "Buffer has been auto-saved recently.  Revert from auto-save file? ")))
2682            (file-name (if auto-save-p
2683                           buffer-auto-save-file-name
2684                         buffer-file-name)))
2685       (cond ((null file-name)
2686              (error "Buffer does not seem to be associated with any file"))
2687             ((or noconfirm
2688                  (and (not (buffer-modified-p))
2689                       (dolist (rx revert-without-query found)
2690                         (when (string-match rx file-name)
2691                           (setq found t))))
2692                  ;; If we will call revert-buffer-internal, delay prompting
2693                  (and (not auto-save-p)
2694                       (not (buffer-modified-p))
2695                       (setq delay-prompt t))
2696                  (yes-or-no-p (format "Revert buffer from file %s? "
2697                                       file-name)))
2698              (run-hooks 'before-revert-hook)
2699              (cond ((or auto-save-p
2700                         (buffer-modified-p)
2701                         ;; Do we need to do expensive reversion?  Compare ...
2702                         (and (setq newbuf (revert-buffer-internal
2703                                            file-name))
2704                              ;; ... and if different, prompt
2705                              (or noconfirm found
2706                                  (and delay-prompt
2707                                       (yes-or-no-p
2708                                        (format "Revert buffer from file %s? "
2709                                                file-name))))))
2710                     ;; If file was backed up but has changed since,
2711                     ;; we should make another backup.
2712                     (and (not auto-save-p)
2713                          (not (verify-visited-file-modtime (current-buffer)))
2714                          (setq buffer-backed-up nil))
2715                     ;; Get rid of all undo records for this buffer.
2716                     (or (eq buffer-undo-list t)
2717                         (setq buffer-undo-list nil))
2718                     ;; Effectively copy the after-revert-hook status,
2719                     ;; since after-find-file will clobber it.
2720                     (let ((global-hook (default-value 'after-revert-hook))
2721                           (local-hook-p (local-variable-p 'after-revert-hook
2722                                                           (current-buffer)))
2723                           (local-hook (and (local-variable-p 'after-revert-hook
2724                                                              (current-buffer))
2725                                            after-revert-hook)))
2726                       (let (buffer-read-only
2727                             ;; Don't make undo records for the reversion.
2728                             (buffer-undo-list t))
2729                         (if revert-buffer-insert-file-contents-function
2730                             (funcall revert-buffer-insert-file-contents-function
2731                                      file-name auto-save-p)
2732                           (if (not (file-exists-p file-name))
2733                               (error "File %s no longer exists!" file-name))
2734                           ;; Bind buffer-file-name to nil
2735                           ;; so that we don't try to lock the file.
2736                           (let ((buffer-file-name nil))
2737                             (or auto-save-p
2738                                 (unlock-buffer)))
2739                           (widen)
2740                           (insert-file-contents file-name (not auto-save-p)
2741                                                 nil nil t)))
2742                       (goto-char (min opoint (point-max)))
2743                       ;; Recompute the truename in case changes in symlinks
2744                       ;; have changed the truename.
2745                       ;;XEmacs: already done by insert-file-contents
2746                       ;;(setq buffer-file-truename
2747                       ;;(abbreviate-file-name (file-truename buffer-file-name)))
2748                       (after-find-file nil nil t t preserve-modes)
2749                       ;; Run after-revert-hook as it was before we reverted.
2750                       (setq-default revert-buffer-internal-hook global-hook)
2751                       (if local-hook-p
2752                           (progn
2753                             (make-local-variable 'revert-buffer-internal-hook)
2754                             (setq revert-buffer-internal-hook local-hook))
2755                         (kill-local-variable 'revert-buffer-internal-hook))
2756                       (run-hooks 'revert-buffer-internal-hook)))
2757                    ((null newbuf)
2758                     ;; The resultant buffer is identical, alter
2759                     ;; modtime, update mods and exit
2760                     (set-visited-file-modtime)
2761                     (after-find-file nil nil t t t)
2762                     ;; We preserved modes above so fixup the local
2763                     ;; variables manually
2764                     (condition-case err
2765                         (hack-local-variables)
2766                       (error (lwarn 'local-variables 'warning
2767                                "File local-variables error: %s"
2768                                (error-message-string err)))))
2769                    (t t))
2770              t)))))
2771
2772 ;; #### something like `revert-buffer-compare-with-file' is a better name
2773 ;; #### why is the argument optional?
2774 (defun revert-buffer-internal (&optional file-name)
2775   "Read contents of FILE-NAME into a buffer, and compare to current buffer.
2776 Return nil if identical, and the new buffer if different."
2777
2778   (let* ((newbuf (get-buffer-create " *revert*"))
2779          bmin bmax)
2780     (save-excursion
2781       (set-buffer newbuf)
2782       (with-obsolete-variable '(before-change-function after-change-function)
2783         (let (buffer-read-only
2784               (buffer-undo-list t)
2785               after-change-function
2786               after-change-functions
2787               before-change-function
2788               before-change-functions)
2789           (if revert-buffer-insert-file-contents-function
2790               (funcall revert-buffer-insert-file-contents-function
2791                        file-name nil)
2792             (if (not (file-exists-p file-name))
2793                 (error "File %s no longer exists!" file-name))
2794             (widen)
2795             (insert-file-contents file-name nil nil nil t)
2796             (setq bmin (point-min)
2797                   bmax (point-max))))))
2798     (if (not (and (eq bmin (point-min))
2799                   (eq bmax (point-max))
2800                   (eq (compare-buffer-substrings
2801                        newbuf bmin bmax (current-buffer) bmin bmax) 0)))
2802         newbuf
2803       (and (kill-buffer newbuf) nil))))
2804
2805 (defun recover-file (file)
2806   "Visit file FILE, but get contents from its last auto-save file."
2807   ;; Actually putting the file name in the minibuffer should be used
2808   ;; only rarely.
2809   ;; Not just because users often use the default.
2810   (interactive "FRecover file: ")
2811   (setq file (expand-file-name file))
2812   (let ((handler (or (find-file-name-handler file 'recover-file)
2813                     (find-file-name-handler
2814                      (let ((buffer-file-name file))
2815                        (make-auto-save-file-name))
2816                      'recover-file))))
2817     (if handler
2818         (funcall handler 'recover-file file)
2819       (if (auto-save-file-name-p (file-name-nondirectory file))
2820           (error "%s is an auto-save file" file))
2821       (let ((file-name (let ((buffer-file-name file))
2822                          (make-auto-save-file-name))))
2823         (cond ((if (file-exists-p file)
2824                    (not (file-newer-than-file-p file-name file))
2825                  (not (file-exists-p file-name)))
2826                (error "Auto-save file %s not current" file-name))
2827               ((save-window-excursion
2828                  ;; XEmacs change: use insert-directory instead of
2829                  ;; calling ls directly.
2830                  (with-output-to-temp-buffer "*Directory*"
2831                    (buffer-disable-undo standard-output)
2832                    (save-excursion
2833                      (set-buffer "*Directory*")
2834                      (setq default-directory (file-name-directory file))
2835                      (insert-directory file
2836                                        (if (file-symlink-p file) "-lL" "-l"))
2837                      (setq default-directory (file-name-directory file-name))
2838                      (insert-directory file-name "-l")))
2839                  (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2840                (switch-to-buffer (find-file-noselect file t))
2841                (let ((buffer-read-only nil))
2842                  (erase-buffer)
2843                  (insert-file-contents file-name nil))
2844                (after-find-file nil nil t))
2845               (t (error "Recover-file cancelled.")))))))
2846
2847 (defun recover-session ()
2848   "Recover auto save files from a previous Emacs session.
2849 This command first displays a Dired buffer showing you the
2850 previous sessions that you could recover from.
2851 To choose one, move point to the proper line and then type C-c C-c.
2852 Then you'll be asked about a number of files to recover."
2853   (interactive)
2854   (unless (fboundp 'dired)
2855     (error "recover-session requires dired"))
2856   (if (null auto-save-list-file-prefix)
2857       (error
2858        "You set `auto-save-list-file-prefix' to disable making session files"))
2859   (dired (concat auto-save-list-file-prefix "*"))
2860   (goto-char (point-min))
2861   (or (looking-at "Move to the session you want to recover,")
2862       (let ((inhibit-read-only t))
2863         (insert "Move to the session you want to recover,\n"
2864                 "then type C-c C-c to select it.\n\n"
2865                 "You can also delete some of these files;\n"
2866                 "type d on a line to mark that file for deletion.\n\n")))
2867   (use-local-map (let ((map (make-sparse-keymap)))
2868                    (set-keymap-parents map (list (current-local-map)))
2869                    map))
2870   (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
2871
2872 (defun recover-session-finish ()
2873   "Choose one saved session to recover auto-save files from.
2874 This command is used in the special Dired buffer created by
2875 \\[recover-session]."
2876   (interactive)
2877   ;; Get the name of the session file to recover from.
2878   (let ((file (declare-fboundp (dired-get-filename)))
2879         files
2880         (buffer (get-buffer-create " *recover*")))
2881     ;; #### dired-do-flagged-delete in FSF.
2882     ;; This version is for ange-ftp
2883     ;;(dired-do-deletions t)
2884     ;; This version is for efs
2885     (declare-fboundp (dired-expunge-deletions))
2886     (unwind-protect
2887         (save-excursion
2888           ;; Read in the auto-save-list file.
2889           (set-buffer buffer)
2890           (erase-buffer)
2891           (insert-file-contents file)
2892           ;; Loop thru the text of that file
2893           ;; and get out the names of the files to recover.
2894           (while (not (eobp))
2895             (let (thisfile autofile)
2896               (if (eolp)
2897                   ;; This is a pair of lines for a non-file-visiting buffer.
2898                   ;; Get the auto-save file name and manufacture
2899                   ;; a "visited file name" from that.
2900                   (progn
2901                     (forward-line 1)
2902                     (setq autofile
2903                           (buffer-substring-no-properties
2904                            (point)
2905                            (save-excursion
2906                              (end-of-line)
2907                              (point))))
2908                     (setq thisfile
2909                           (expand-file-name
2910                            (substring
2911                             (file-name-nondirectory autofile)
2912                             1 -1)
2913                            (file-name-directory autofile)))
2914                     (forward-line 1))
2915                 ;; This pair of lines is a file-visiting
2916                 ;; buffer.  Use the visited file name.
2917                 (progn
2918                   (setq thisfile
2919                         (buffer-substring-no-properties
2920                          (point) (progn (end-of-line) (point))))
2921                   (forward-line 1)
2922                   (setq autofile
2923                         (buffer-substring-no-properties
2924                          (point) (progn (end-of-line) (point))))
2925                   (forward-line 1)))
2926               ;; Ignore a file if its auto-save file does not exist now.
2927               (if (file-exists-p autofile)
2928                   (setq files (cons thisfile files)))))
2929           (setq files (nreverse files))
2930           ;; The file contains a pair of line for each auto-saved buffer.
2931           ;; The first line of the pair contains the visited file name
2932           ;; or is empty if the buffer was not visiting a file.
2933           ;; The second line is the auto-save file name.
2934           (if files
2935               (map-y-or-n-p  "Recover %s? "
2936                              (lambda (file)
2937                                (condition-case nil
2938                                    (save-excursion (recover-file file))
2939                                  (error
2940                                   "Failed to recover `%s'" file)))
2941                              files
2942                              '("file" "files" "recover"))
2943             (message "No files can be recovered from this session now")))
2944       (kill-buffer buffer))))
2945
2946 (defun kill-some-buffers (&optional list)
2947   "For each buffer in LIST, ask whether to kill it.
2948 LIST defaults to all existing live buffers."
2949   (interactive)
2950   (if (null list)
2951       (setq list (buffer-list)))
2952   (while list
2953     (let* ((buffer (car list))
2954            (name (buffer-name buffer)))
2955       (and (not (string-equal name ""))
2956            (/= (aref name 0) ?\ )
2957            (yes-or-no-p
2958             (format
2959              (if (buffer-modified-p buffer)
2960                  (gettext "Buffer %s HAS BEEN EDITED.  Kill? ")
2961                (gettext "Buffer %s is unmodified.  Kill? "))
2962              name))
2963            (kill-buffer buffer)))
2964     (setq list (cdr list))))
2965 \f
2966 (defun auto-save-mode (arg)
2967   "Toggle auto-saving of contents of current buffer.
2968 With prefix argument ARG, turn auto-saving on if positive, else off."
2969   (interactive "P")
2970   (setq buffer-auto-save-file-name
2971         (and (if (null arg)
2972                  (or (not buffer-auto-save-file-name)
2973                      ;; If autosave is off because buffer has shrunk,
2974                      ;; then toggling should turn it on.
2975                      (< buffer-saved-size 0))
2976                (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2977              (if (and buffer-file-name auto-save-visited-file-name
2978                       (not buffer-read-only))
2979                  buffer-file-name
2980                (make-auto-save-file-name))))
2981   ;; If -1 was stored here, to temporarily turn off saving,
2982   ;; turn it back on.
2983   (and (< buffer-saved-size 0)
2984        (setq buffer-saved-size 0))
2985   (if (interactive-p)
2986       (if buffer-auto-save-file-name ;; rewritten for I18N3 snarfing
2987           (display-message 'command "Auto-save on (in this buffer)")
2988         (display-message 'command "Auto-save off (in this buffer)")))
2989   buffer-auto-save-file-name)
2990
2991 (defun rename-auto-save-file ()
2992   "Adjust current buffer's auto save file name for current conditions.
2993 Also rename any existing auto save file, if it was made in this session."
2994   (let ((osave buffer-auto-save-file-name))
2995     (setq buffer-auto-save-file-name
2996           (make-auto-save-file-name))
2997     (if (and osave buffer-auto-save-file-name
2998              (not (string= buffer-auto-save-file-name buffer-file-name))
2999              (not (string= buffer-auto-save-file-name osave))
3000              (file-exists-p osave)
3001              (recent-auto-save-p))
3002         (rename-file osave buffer-auto-save-file-name t))))
3003
3004 ;; make-auto-save-file-name and auto-save-file-name-p are now only in
3005 ;; auto-save.el.
3006
3007 \f
3008 (defun wildcard-to-regexp (wildcard)
3009   "Given a shell file name pattern WILDCARD, return an equivalent regexp.
3010 The generated regexp will match a filename iff the filename
3011 matches that wildcard according to shell rules.  Only wildcards known
3012 by `sh' are supported."
3013   (let* ((i (string-match "[[.*+\\^$?]" wildcard))
3014          ;; Copy the initial run of non-special characters.
3015          (result (substring wildcard 0 i))
3016          (len (length wildcard)))
3017     ;; If no special characters, we're almost done.
3018     (if i
3019         (while (< i len)
3020           (let ((ch (aref wildcard i))
3021                 j)
3022             (setq
3023              result
3024              (concat result
3025                      (cond
3026                       ((eq ch ?\[)      ; [...] maps to regexp char class
3027                        (progn
3028                          (setq i (1+ i))
3029                          (concat
3030                           (cond
3031                            ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
3032                             (progn
3033                               (setq i (1+ i))
3034                               (if (eq (aref wildcard i) ?\])
3035                                   (progn
3036                                     (setq i (1+ i))
3037                                     "[^]")
3038                                 "[^")))
3039                            ((eq (aref wildcard i) ?^)
3040                             ;; Found "[^".  Insert a `\0' character
3041                             ;; (which cannot happen in a filename)
3042                             ;; into the character class, so that `^'
3043                             ;; is not the first character after `[',
3044                             ;; and thus non-special in a regexp.
3045                             (progn
3046                               (setq i (1+ i))
3047                               "[\000^"))
3048                            ((eq (aref wildcard i) ?\])
3049                             ;; I don't think `]' can appear in a
3050                             ;; character class in a wildcard, but
3051                             ;; let's be general here.
3052                             (progn
3053                               (setq i (1+ i))
3054                               "[]"))
3055                            (t "["))
3056                           (prog1        ; copy everything upto next `]'.
3057                               (substring wildcard
3058                                          i
3059                                          (setq j (string-match
3060                                                   "]" wildcard i)))
3061                             (setq i (if j (1- j) (1- len)))))))
3062                       ((eq ch ?.)  "\\.")
3063                       ((eq ch ?*)  "[^\000]*")
3064                       ((eq ch ?+)  "\\+")
3065                       ((eq ch ?^)  "\\^")
3066                       ((eq ch ?$)  "\\$")
3067                       ((eq ch ?\\) #r"\\") ; probably cannot happen...
3068                       ((eq ch ??)  "[^\000]")
3069                       (t (char-to-string ch)))))
3070             (setq i (1+ i)))))
3071     ;; Shell wildcards should match the entire filename,
3072     ;; not its part.  Make the regexp say so.
3073     (concat "\\`" result "\\'")))
3074 \f
3075 (defcustom list-directory-brief-switches "-CF"
3076   "*Switches for list-directory to pass to `ls' for brief listing."
3077   :type 'string
3078   :group 'dired)
3079
3080 (defcustom list-directory-verbose-switches "-l"
3081   "*Switches for list-directory to pass to `ls' for verbose listing,"
3082   :type 'string
3083   :group 'dired)
3084
3085 (defun list-directory (dirname &optional verbose)
3086   "Display a list of files in or matching DIRNAME, a la `ls'.
3087 DIRNAME is globbed by the shell if necessary.
3088 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
3089 Actions controlled by variables `list-directory-brief-switches'
3090 and `list-directory-verbose-switches'."
3091   (interactive (let ((pfx current-prefix-arg))
3092                  (list (read-file-name (if pfx (gettext "List directory (verbose): ")
3093                                          (gettext "List directory (brief): "))
3094                                        nil default-directory nil)
3095                        pfx)))
3096   (let ((switches (if verbose list-directory-verbose-switches
3097                     list-directory-brief-switches)))
3098     (or dirname (setq dirname default-directory))
3099     (setq dirname (expand-file-name dirname))
3100     (with-output-to-temp-buffer "*Directory*"
3101       (buffer-disable-undo standard-output)
3102       (princ "Directory ")
3103       (princ dirname)
3104       (terpri)
3105       (save-excursion
3106         (set-buffer "*Directory*")
3107         (setq default-directory (file-name-directory dirname))
3108         (let ((wildcard (not (file-directory-p dirname))))
3109           (insert-directory dirname switches wildcard (not wildcard)))))))
3110
3111 (defvar insert-directory-program "ls"
3112   "Absolute or relative name of the `ls' program used by `insert-directory'.")
3113
3114 ;; insert-directory
3115 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
3116 ;;   FULL-DIRECTORY-P is nil.
3117 ;;   The single line of output must display FILE's name as it was
3118 ;;   given, namely, an absolute path name.
3119 ;; - must insert exactly one line for each file if WILDCARD or
3120 ;;   FULL-DIRECTORY-P is t, plus one optional "total" line
3121 ;;   before the file lines, plus optional text after the file lines.
3122 ;;   Lines are delimited by "\n", so filenames containing "\n" are not
3123 ;;   allowed.
3124 ;;   File lines should display the basename.
3125 ;; - must be consistent with
3126 ;;   - functions dired-move-to-filename, (these two define what a file line is)
3127 ;;               dired-move-to-end-of-filename,
3128 ;;               dired-between-files, (shortcut for (not (dired-move-to-filename)))
3129 ;;               dired-insert-headerline
3130 ;;               dired-after-subdir-garbage (defines what a "total" line is)
3131 ;;   - variable dired-subdir-regexp
3132 (defun insert-directory (file switches &optional wildcard full-directory-p)
3133   "Insert directory listing for FILE, formatted according to SWITCHES.
3134 Leaves point after the inserted text.
3135 SWITCHES may be a string of options, or a list of strings.
3136 Optional third arg WILDCARD means treat FILE as shell wildcard.
3137 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
3138 switches do not contain `d', so that a full listing is expected.
3139
3140 This works by running a directory listing program
3141 whose name is in the variable `insert-directory-program'.
3142 If WILDCARD, it also runs the shell specified by `shell-file-name'."
3143   ;; We need the directory in order to find the right handler.
3144   (let ((handler (find-file-name-handler (expand-file-name file)
3145                                          'insert-directory)))
3146     (cond
3147      (handler
3148       (funcall handler 'insert-directory file switches
3149                wildcard full-directory-p))
3150      (t
3151       (let* ((beg (point))
3152              (result
3153               (if wildcard
3154                   ;; Run ls in the directory of the file pattern we asked for.
3155                   (let ((default-directory
3156                           (if (file-name-absolute-p file)
3157                               (file-name-directory file)
3158                             (file-name-directory (expand-file-name file))))
3159                         (pattern (file-name-nondirectory file))
3160                         (start 0))
3161                     ;; Quote some characters that have special meanings in shells;
3162                     ;; but don't quote the wildcards--we want them to be special.
3163                     ;; We also currently don't quote the quoting characters
3164                     ;; in case people want to use them explicitly to quote
3165                     ;; wildcard characters.
3166                     ;;#### Unix-specific
3167                     (while (string-match "[ \t\n;<>&|()#$]" pattern start)
3168                       (setq pattern
3169                             (concat (substring pattern 0 (match-beginning 0))
3170                                     "\\"
3171                                     (substring pattern (match-beginning 0)))
3172                             start (1+ (match-end 0))))
3173                     (call-process shell-file-name nil t nil
3174                                   "-c" (concat "\\" ;; Disregard shell aliases!
3175                                                insert-directory-program
3176                                                " -d "
3177                                                (if (stringp switches)
3178                                                    switches
3179                                                  (mapconcat 'identity switches " "))
3180                                                " "
3181                                                pattern)))
3182                 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
3183                 ;; directory if FILE is a symbolic link.
3184                 (apply 'call-process
3185                        insert-directory-program nil t nil
3186                        (let (list)
3187                          (if (listp switches)
3188                              (setq list switches)
3189                            (if (not (equal switches ""))
3190                                (let ((switches switches))
3191                                  ;; Split the switches at any spaces
3192                                  ;; so we can pass separate options as separate args.
3193                                  (while (string-match " " switches)
3194                                    (setq list (cons (substring switches 0 (match-beginning 0))
3195                                                     list)
3196                                          switches (substring switches (match-end 0))))
3197                                  (setq list (cons switches list)))))
3198                          (append list
3199                                  (list
3200                                   (if full-directory-p
3201                                       (concat (file-name-as-directory file)
3202                                               ;;#### Unix-specific
3203                                               ".")
3204                                     file))))))))
3205         ;; If `insert-directory-program' failed, signal an error.
3206         (if (/= result 0)
3207             ;; On non-Posix systems, we cannot open a directory, so
3208             ;; don't even try, because that will always result in
3209             ;; the ubiquitous "Access denied".  Instead, show the
3210             ;; command line so the user can try to guess what went wrong.
3211             (error "Listing directory failed."))
3212
3213         (when (or (and (listp switches)
3214                        (member "--dired" switches))
3215                   (string-match "--dired\\>" switches))
3216           (forward-line -2)
3217           (when (looking-at "//SUBDIRED//")
3218             (delete-region (point) (progn (forward-line 1) (point)))
3219             (forward-line -1))
3220           (let ((end (line-end-position)))
3221             (forward-word 1)
3222             (forward-char 3)
3223             (while (< (point) end)
3224               (let ((start (+ beg (read (current-buffer))))
3225                     (end (+ beg (read (current-buffer)))))
3226                 (if (= (char-after end) ?\n)
3227                     (let ((filename-extent (make-extent start end)))
3228                       (set-extent-property filename-extent 'dired-file-name t)
3229                       (set-extent-property filename-extent 'start-open t)
3230                       (set-extent-property filename-extent 'end-open t))
3231                   ;; It seems that we can't trust ls's output as to
3232                   ;; byte positions of filenames.
3233                   (map-extents
3234                    #'(lambda (extent maparg)
3235                        (delete-extent extent)
3236                        nil)
3237                    nil beg (point) nil nil 'dired-file-name)
3238                   (end-of-line))))
3239             (goto-char end)
3240             (beginning-of-line)
3241             (delete-region (point) (progn (forward-line 2) (point))))))))))
3242
3243 (defvar kill-emacs-query-functions nil
3244   "Functions to call with no arguments to query about killing XEmacs.
3245 If any of these functions returns nil, killing Emacs is cancelled.
3246 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
3247 but `kill-emacs', the low level primitive, does not.
3248 See also `kill-emacs-hook'.")
3249
3250 (defun save-buffers-kill-emacs (&optional arg)
3251   "Offer to save each buffer, then kill this XEmacs process.
3252 With prefix arg, silently save all file-visiting buffers, then kill."
3253   (interactive "P")
3254   (save-some-buffers arg t)
3255   (and (or (not (memq t (mapcar #'(lambda (buf) (and (buffer-file-name buf)
3256                                                      (buffer-modified-p buf)))
3257                                 (buffer-list))))
3258            (yes-or-no-p "Modified buffers exist; exit anyway? "))
3259        (or (not (fboundp 'process-list))
3260            ;; process-list is not defined on VMS.
3261            (let ((processes (process-list))
3262                  active)
3263              (while processes
3264                (and (memq (process-status (car processes)) '(run stop open))
3265                     (let ((val (process-kill-without-query (car processes))))
3266                       (process-kill-without-query (car processes) val)
3267                       val)
3268                     (setq active t))
3269                (setq processes (cdr processes)))
3270              (or
3271               (not active)
3272               (save-excursion
3273                 (save-window-excursion
3274                   (delete-other-windows)
3275                   (list-processes)
3276                   (yes-or-no-p
3277                    "Active processes exist; kill them and exit anyway? "))))))
3278        ;; Query the user for other things, perhaps.
3279        (run-hook-with-args-until-failure 'kill-emacs-query-functions)
3280        (kill-emacs)))
3281
3282 (defun symlink-expand-file-name (filename)
3283   "If FILENAME is a symlink, return its non-symlink equivalent.
3284 Unlike `file-truename', this doesn't chase symlinks in directory
3285 components of the file or expand a relative pathname into an
3286 absolute one."
3287   (let ((count 20))
3288     (while (and (> count 0) (file-symlink-p filename))
3289       (setq filename (file-symlink-p filename)
3290             count (1- count)))
3291     (if (> count 0)
3292         filename
3293       (error "Apparently circular symlink path"))))
3294
3295 ;; Suggested by Michael Kifer <kifer@CS.SunySB.EDU>
3296 (defun file-remote-p (file-name)
3297   "Test whether FILE-NAME is looked for on a remote system."
3298   (cond ((not (declare-boundp allow-remote-paths)) nil)
3299         ((fboundp 'ange-ftp-ftp-path)
3300          (declare-fboundp (ange-ftp-ftp-path file-name)))
3301         ((fboundp 'efs-ftp-path)
3302          (declare-fboundp (efs-ftp-path file-name)))
3303         (t nil)))
3304
3305 ;; #### FSF has file-name-non-special here.
3306
3307 ;;; files.el ends here