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