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