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