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