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