1 ;;; files.el --- file input and output commands for SXEmacs.
3 ;; Copyright (C) 1985-1987, 1992-1995, 1997 Free Software Foundation, Inc.
4 ;; Copyright (C) 1995 Sun Microsystems.
6 ;; Maintainer: SXEmacs Development Team
7 ;; Keywords: extensions, dumped
9 ;; This file is part of SXEmacs.
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.
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.
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/>.
24 ;;; Synched up with: FSF 20.3 (but diverging)
25 ;;; Warning: Merging this file is tough. Beware.
29 ;; This file is dumped with SXEmacs.
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.
37 ;; XEmacs: Avoid compilation warnings.
38 (defvar coding-system-for-read)
39 (defvar buffer-file-coding-system)
41 (globally-declare-fboundp '(dired-noselect dired)))
45 "Support editing files."
49 "Backups of edited data files."
52 (defgroup find-file nil
53 "Finding and editing files."
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.")
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 ^.
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"
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.
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.
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.
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'."
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)
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'."
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."
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."
131 (defvar backup-enable-predicate
134 (string-match "^/tmp/" name)
135 (let ((tmpdir (temp-directory)))
137 (string-match (concat "\\`" (regexp-quote 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.")
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."
148 (make-variable-buffer-local 'buffer-offer-save)
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)
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 ""))
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)
171 (defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
172 "Non-nil means that buffer-file-number uniquely identifies files.")
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.
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.
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."
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."
198 ;; This is now defined in efs.
199 ;(defvar dired-kept-versions 2
200 ; "*When cleaning directory, number of versions to keep.")
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))
210 (defcustom kept-old-versions 2
211 "*Number of oldest versions to keep when a new numbered backup is made."
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"
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)
227 (sexp :tag "Ask" :format "%t\n" ask))
228 :group 'editing-basics)
230 (defcustom auto-save-default t
231 "*Non-nil says by default do auto-saving of every file-visiting buffer."
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."
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."
247 (defcustom find-file-run-dired t
248 "*Non-nil says run dired if `find-file' is given the name of a directory."
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))
259 ;;; End Sync: XEmacs 21.5 (cb65bfaf7110 tip) 2015-07-03 --SY
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.")
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.")
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)
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
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)
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'.")
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'.")
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'.")
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.
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))
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.
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))
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."
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))
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))
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))
396 ;; leave ':' if part of drive specifier
397 (if (and (> (length name) 1)
398 (eq (aref name 1) ?:))
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.
411 "Show the current default directory."
413 (message "Directory %s" default-directory))
416 "Value of the CDPATH environment variable, as a list.
417 Not actually set up until the first time you use it.")
419 (defvar cdpath-previous nil
420 "Prior value of the CDPATH environment variable.")
422 (defun parse-colon-path (cd-path)
423 "Explode a colon-separated search path into a list of directory names.
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."
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))
434 (list (if (= cd-start cd-colon)
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)))
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))
457 (setq default-directory dir))))
460 "Make DIR become the current buffer's default directory.
461 If your environment includes a `CDPATH' variable, try each one of that
462 colon-separated list of directories when resolving a relative directory name."
464 ;; XEmacs change? (read-file-name => read-directory-name)
465 (list (read-directory-name "Change default directory: "
466 default-directory default-directory
467 (and (member cd-path '(nil ("./")))
468 (null (getenv "CDPATH"))))))
469 (if (file-name-absolute-p dir)
470 (cd-absolute (expand-file-name dir))
472 (unless (and cd-path (equal (getenv "CDPATH") cdpath-previous))
474 (let ((trypath (parse-colon-path
475 (setq cdpath-previous (getenv "CDPATH")))))
476 (setq cd-path (or trypath (list "./")))))
478 (mapcar #'(lambda (x)
479 (let ((f (expand-file-name (concat x dir))))
480 (if (file-directory-p f)
486 ;; jwz: give a better error message to those of us with the
487 ;; good taste not to use a kludge like $CDPATH.
488 (if (equal cd-path '("./"))
489 (error "No such directory: %s" (expand-file-name dir))
490 (error "Directory not found in $CDPATH: %s" dir)))))
492 (defun load-file (file)
493 "Load the Lisp file named FILE."
494 (interactive "fLoad file: ")
495 (load (expand-file-name file) nil nil t))
497 ; We now dump utils/lib-complete.el which has improved versions of this.
498 ;(defun load-library (library)
499 ; "Load the library named LIBRARY.
500 ;This is an interface to the function `load'."
501 ; (interactive "sLoad library: ")
504 ;(defun find-library (library)
505 ; "Find the library of Lisp code named LIBRARY.
506 ;This searches `load-path' for a file named either \"LIBRARY\" or \"LIBRARY.el\"."
507 ; (interactive "sFind library file: ")
508 ; (let ((f (locate-file library load-path ":.el:")))
511 ; (error "Couldn't locate library %s" library))))
513 (defun file-local-copy (file &optional buffer)
514 "Copy the file FILE into a temporary file on this machine.
515 Returns the name of the local copy, or nil, if FILE is directly
517 (let ((handler (find-file-name-handler file 'file-local-copy)))
519 (funcall handler 'file-local-copy file)
522 ;; XEmacs change block
523 ; We have this in C and use the realpath() system call.
525 ;(defun file-truename (filename &optional counter prev-dirs)
526 ; [... lots of code snipped ...]
529 ;; XEmacs addition. Called from `insert-file-contents-internal'
530 ;; at the appropriate time.
531 (defun compute-buffer-file-truename (&optional buffer)
532 "Recompute BUFFER's value of `buffer-file-truename'
533 based on the current value of `buffer-file-name'.
534 BUFFER defaults to the current buffer if unspecified."
536 (set-buffer (or buffer (current-buffer)))
537 (cond ((null buffer-file-name)
538 (setq buffer-file-truename nil))
539 ((setq buffer-file-truename (file-truename buffer-file-name))
540 ;; it exists, we're done.
543 ;; the file doesn't exist, but maybe the directory does.
544 (let* ((dir (file-name-directory buffer-file-name))
545 (truedir (file-truename dir)))
546 (if truedir (setq dir truedir))
547 (setq buffer-file-truename
548 (expand-file-name (file-name-nondirectory buffer-file-name)
550 (if (and find-file-use-truenames buffer-file-truename)
551 (setq buffer-file-name (abbreviate-file-name buffer-file-truename)
552 default-directory (file-name-directory buffer-file-name)))
553 buffer-file-truename))
554 ;; End XEmacs change block
556 (defun file-chase-links (filename)
557 "Chase links in FILENAME until a name that is not a link.
558 Does not examine containing directories for links,
559 unlike `file-truename'."
560 (let (tem (count 100) (newname filename))
561 (while (setq tem (file-symlink-p newname))
564 (error "Apparent cycle of symbolic links for %s" filename))
565 ;; In the context of a link, `//' doesn't mean what XEmacs thinks.
566 (while (string-match "//+" tem)
567 (setq tem (concat (substring tem 0 (1+ (match-beginning 0)))
568 (substring tem (match-end 0)))))
569 ;; Handle `..' by hand, since it needs to work in the
570 ;; target of any directory symlink.
571 ;; This code is not quite complete; it does not handle
572 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
573 (while (string-match #r"\`\.\./" tem) ;#### Unix specific
574 (setq tem (substring tem 3))
575 (setq newname (file-name-as-directory
576 ;; Do the .. by hand.
579 ;; Chase links in the default dir of the symlink.
582 (file-name-directory newname))))))))
583 (setq newname (expand-file-name tem (file-name-directory newname)))
584 (setq count (1- count))))
587 (defun switch-to-other-buffer (arg)
588 "Switch to the previous buffer. With a numeric arg, n, switch to the nth
589 most recent buffer. With an arg of 0, buries the current buffer at the
590 bottom of the buffer stack."
593 (bury-buffer (current-buffer)))
595 (if (<= arg 1) (other-buffer (current-buffer))
596 (nth (1+ arg) (buffer-list)))))
598 (defun switch-to-buffer-other-window (buffer)
599 "Select buffer BUFFER in another window."
600 (interactive "BSwitch to buffer in other window: ")
601 (let ((pop-up-windows t))
602 ;; XEmacs: this used to have (selected-frame) as the third argument,
603 ;; but this is obnoxious. If the user wants the buffer in a
604 ;; different frame, then it should be this way.
606 ;; Change documented above undone --mrb
607 (pop-to-buffer buffer t (selected-frame))))
609 (defun switch-to-buffer-other-frame (buffer)
610 "Switch to buffer BUFFER in a newly-created frame."
611 (interactive "BSwitch to buffer in other frame: ")
612 (let* ((name (get-frame-name-for-buffer buffer))
613 (frame (make-frame (if name
614 (list (cons 'name (symbol-name name)))))))
615 (pop-to-buffer buffer t frame)
616 (make-frame-visible frame)
619 ;;; Sync: XEmacs 21.5 (cb65bfaf7110 tip) 2015-07-03 --SY
620 (defun switch-to-next-buffer (&optional n)
621 "Switch to the next-most-recent buffer.
622 This essentially rotates the buffer list forward.
623 N (interactively, the prefix arg) specifies how many times to rotate
624 forward, and defaults to 1. Buffers whose name begins with a space
625 \(i.e. \"invisible\" buffers) are ignored."
626 ;; Here is a different interactive spec. Look up the function
627 ;; `interactive' (i.e. `C-h f interactive') to understand how this
630 (dotimes (n (or n 1))
632 do (bury-buffer (car (buffer-list)))
633 while (funcall buffers-tab-omit-function (car (buffer-list))))
634 (switch-to-buffer (car (buffer-list)))))
636 (defun switch-to-previous-buffer (&optional n)
637 "Switch to the previously most-recent buffer.
638 This essentially rotates the buffer list backward.
639 N (interactively, the prefix arg) specifies how many times to rotate
640 backward, and defaults to 1. Buffers whose name begins with a space
641 \(i.e. \"invisible\" buffers) are ignored."
643 (dotimes (n (or n 1))
645 do (switch-to-buffer (car (last (buffer-list))))
646 while (funcall buffers-tab-omit-function (car (buffer-list))))))
648 ;;; FIXME: Could this looping be done with #'mapfam in a nicer way.
649 (defun switch-to-next-buffer-in-group (&optional n)
650 "Switch to the next-most-recent buffer in the current group.
651 This essentially rotates the buffer list forward.
652 N (interactively, the prefix arg) specifies how many times to rotate
653 forward, and defaults to 1. Buffers whose name begins with a space
654 \(i.e. \"invisible\" buffers) are ignored."
656 (dotimes (n (or n 1))
657 (let ((curbuf (car (buffer-list))))
659 do (bury-buffer (car (buffer-list)))
660 while (or (funcall buffers-tab-omit-function (car (buffer-list)))
663 (funcall f curbuf (car (buffer-list))))
664 buffers-tab-filter-functions)))))
665 (switch-to-buffer (car (buffer-list)))))
667 ;;; FIXME: Could this looping be done with #'mapfam in a nicer way.
668 (defun switch-to-previous-buffer-in-group (&optional n)
669 "Switch to the previously most-recent buffer in the current group.
670 This essentially rotates the buffer list backward.
671 N (interactively, the prefix arg) specifies how many times to rotate
672 backward, and defaults to 1. Buffers whose name begins with a space
673 \(i.e. \"invisible\" buffers) are ignored."
675 (dotimes (n (or n 1))
676 (let ((curbuf (car (buffer-list))))
678 do (switch-to-buffer (car (last (buffer-list))))
679 while (or (funcall buffers-tab-omit-function (car (buffer-list)))
682 (funcall f curbuf (car (buffer-list))))
683 buffers-tab-filter-functions)))))))
685 (defmacro find-file-create-switch-thunk (switch-function)
686 "Mark buffer modified if needed, then call SWITCH-FUNCTION.
688 The buffer will be marked modified if the file associated with the buffer
689 does not exist. This means that \\[find-file] on a non-existent file will
690 create a modified buffer, making \\[save-buffer] sufficient to create the
693 SWITCH-FUNCTION should be `switch-to-buffer' or a related function. This
694 function (that is, `find-file-create-switch-thunk') is implemented as a macro
695 because we don't have built-in lexical scope, a closure created with
696 `lexical-let' will always run as interpreted code. Though functions created
697 by this macro are unlikely to be called in performance-critical contexts.
699 This function may be called from functions related to `find-file', as well
700 as `find-file' itself."
703 (unless (and (buffer-file-name buffer)
704 (file-exists-p (buffer-file-name buffer)))
705 ;; XEmacs: nonexistent file--qualifies as a modification to the
707 (set-buffer-modified-p t buffer))
708 (,switch-function buffer))))
710 (defun find-file (filename &optional codesys wildcards)
712 Switch to a buffer visiting file FILENAME, creating one if none already
713 exists. Optional second argument specifies the coding system to use when
714 decoding the file. Interactively, with a prefix argument, you will be
715 prompted for the coding system.
717 If you do not explicitly specify a coding system, the coding system
718 is determined as follows:
720 1. `coding-system-for-read', if non-nil. (This is used by Lisp programs to
721 temporarily set an overriding coding system and should almost never
722 apply here in `find-file'.)
723 2. The result of `insert-file-contents-pre-hook', if non-nil. (This is a
724 complex interface for handling special cases.)
725 3. The matching value for this filename from `file-coding-system-alist',
726 if any. (This lets you specify the coding system to be used for
727 files with particular extensions, names, etc.)
728 4. `buffer-file-coding-system-for-read', if non-nil. (This is the global
729 default -- normally `undecided', so the built-in auto-detection
730 mechanism can do its thing.)
731 5. The coding system 'raw-text.
733 See `insert-file-contents' for more details about how the process of
734 determining the coding system works.
736 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
737 expand wildcards (if any) and visit multiple files. Wildcard expansion
738 can be suppressed by setting `find-file-wildcards' to `nil'."
739 (interactive (list (read-file-name "Find file: ")
740 (and current-prefix-arg
741 (read-coding-system "Coding system: "))
743 (and codesys (setq codesys (check-coding-system codesys)))
744 (let* ((coding-system-for-read (or codesys coding-system-for-read))
745 (value (find-file-noselect filename nil nil wildcards))
746 (thunk (find-file-create-switch-thunk switch-to-buffer)))
748 (mapcar thunk (nreverse value))
749 (funcall thunk value))))
751 (defun find-file-other-window (filename &optional codesys wildcards)
752 "Edit file FILENAME, in another window.
753 May create a new window, or reuse an existing one. See the function
754 `display-buffer'. Optional second argument specifies the coding system to
755 use when decoding the file. Interactively, with a prefix argument, you
756 will be prompted for the coding system."
757 (interactive (list (read-file-name "Find file in other window: ")
758 (and current-prefix-arg
759 (read-coding-system "Coding system: "))
761 (and codesys (setq codesys (check-coding-system codesys)))
762 (let* ((coding-system-for-read (or codesys coding-system-for-read))
763 (value (find-file-noselect filename nil nil wildcards))
764 (list (and (listp value) (nreverse value)))
765 (other-window-thunk (find-file-create-switch-thunk
766 switch-to-buffer-other-window)))
769 (funcall other-window-thunk (car list))
770 (mapcar (find-file-create-switch-thunk switch-to-buffer) (cdr list)))
771 (funcall other-window-thunk value))))
773 (defun find-file-other-frame (filename &optional codesys wildcards)
774 "Edit file FILENAME, in a newly-created frame.
775 Optional second argument specifies the coding system to use when decoding
776 the file. Interactively, with a prefix argument, you will be prompted for
778 (interactive (list (read-file-name "Find file in other frame: ")
779 (and current-prefix-arg
780 (read-coding-system "Coding system: "))
782 (and codesys (setq codesys (check-coding-system codesys)))
783 (let* ((coding-system-for-read (or codesys coding-system-for-read))
784 (value (find-file-noselect filename nil nil wildcards))
785 (list (and (listp value) (nreverse value)))
786 (other-frame-thunk (find-file-create-switch-thunk
787 switch-to-buffer-other-frame)))
790 (funcall other-frame-thunk (car list))
791 (mapcar (find-file-create-switch-thunk switch-to-buffer) (cdr list)))
792 (funcall other-frame-thunk value))))
794 ;; No need to keep this macro around in the dumped executable.
795 (unintern 'find-file-create-switch-thunk)
797 (defun find-file-read-only (filename &optional codesys wildcards)
798 "Edit file FILENAME but don't allow changes.
799 Like \\[find-file] but marks buffer as read-only.
800 Use \\[toggle-read-only] to permit editing.
801 Optional second argument specifies the coding system to use when decoding
802 the file. Interactively, with a prefix argument, you will be prompted for
804 (interactive (list (read-file-name "Find file read-only: ")
805 (and current-prefix-arg
806 (read-coding-system "Coding system: "))
808 (let ((value (find-file filename codesys wildcards)))
809 (mapc #'(lambda (buffer)
810 (set-symbol-value-in-buffer 'buffer-read-only t buffer))
811 (if (listp value) value (list value)))
814 (defun find-file-read-only-other-window (filename &optional codesys wildcards)
815 "Edit file FILENAME in another window but don't allow changes.
816 Like \\[find-file-other-window] but marks buffer as read-only.
817 Use \\[toggle-read-only] to permit editing.
818 Optional second argument specifies the coding system to use when decoding
819 the file. Interactively, with a prefix argument, you will be prompted for
821 (interactive (list (read-file-name "Find file read-only other window: ")
822 (and current-prefix-arg
823 (read-coding-system "Coding system: "))
825 (find-file-other-window filename codesys wildcards)
826 (setq buffer-read-only t)
829 (defun find-file-read-only-other-frame (filename &optional codesys wildcards)
830 "Edit file FILENAME in another frame but don't allow changes.
831 Like \\[find-file-other-frame] but marks buffer as read-only.
832 Use \\[toggle-read-only] to permit editing.
833 Optional second argument specifies the coding system to use when decoding
834 the file. Interactively, with a prefix argument, you will be prompted for
836 (interactive (list (read-file-name "Find file read-only other frame: ")
837 (and current-prefix-arg
838 (read-coding-system "Coding system: "))
840 (find-file-other-frame filename codesys wildcards)
841 (setq buffer-read-only t)
843 ;;; End Sync: XEmacs 21.5 (cb65bfaf7110 tip) 2015-07-03 --SY
845 (defun find-alternate-file-other-window (filename &optional codesys)
846 "Find file FILENAME as a replacement for the file in the next window.
847 This command does not select that window.
848 Under XEmacs/Mule, optional second argument specifies the
849 coding system to use when decoding the file. Interactively,
850 with a prefix argument, you will be prompted for the coding system."
852 (save-selected-window
854 (let ((file buffer-file-name)
858 (setq file-name (file-name-nondirectory file)
859 file-dir (file-name-directory file)))
860 (list (read-file-name
861 "Find alternate file: " file-dir nil nil file-name)
862 (if (and current-prefix-arg (featurep 'mule))
863 (read-coding-system "Coding-system: "))))))
865 (find-file-other-window filename)
866 (save-selected-window
868 (find-alternate-file filename codesys))))
870 (defun find-alternate-file (filename &optional codesys)
871 "Find file FILENAME, select its buffer, kill previous buffer.
872 If the current buffer now contains an empty file that you just visited
873 \(presumably by mistake), use this command to visit the file you really want.
874 Under XEmacs/Mule, optional second argument specifies the
875 coding system to use when decoding the file. Interactively,
876 with a prefix argument, you will be prompted for the coding system."
878 (let ((file buffer-file-name)
882 (setq file-name (file-name-nondirectory file)
883 file-dir (file-name-directory file)))
884 (list (read-file-name
885 "Find alternate file: " file-dir nil nil file-name)
886 (if (and current-prefix-arg (featurep 'mule))
887 (read-coding-system "Coding-system: ")))))
888 (and (buffer-modified-p) (buffer-file-name)
889 ;; (not buffer-read-only)
890 (not (yes-or-no-p (format
891 "Buffer %s is modified; kill anyway? "
894 (let ((obuf (current-buffer))
895 (ofile buffer-file-name)
896 (onum buffer-file-number)
897 (otrue buffer-file-truename)
898 (oname (buffer-name)))
899 (if (get-buffer " **lose**")
900 (kill-buffer " **lose**"))
901 (rename-buffer " **lose**")
902 (setq buffer-file-name nil)
903 (setq buffer-file-number nil)
904 (setq buffer-file-truename nil)
909 (let ((coding-system-for-read
910 (get-coding-system codesys)))
911 (find-file filename))
912 (find-file filename)))
913 (cond ((eq obuf (current-buffer))
914 (setq buffer-file-name ofile)
915 (setq buffer-file-number onum)
916 (setq buffer-file-truename otrue)
918 (rename-buffer oname))))
919 (or (eq (current-buffer) obuf)
920 (kill-buffer obuf))))
922 (defun create-file-buffer (filename)
923 "Create a suitably named buffer for visiting FILENAME, and return it.
924 FILENAME (sans directory) is used unchanged if that name is free;
925 otherwise a string <2> or <3> or ... is appended to get an unused name."
926 (let ((handler (find-file-name-handler filename 'create-file-buffer)))
928 (funcall handler 'create-file-buffer filename)
929 (let ((lastname (file-name-nondirectory filename)))
930 (if (string= lastname "")
931 (setq lastname filename))
932 (generate-new-buffer lastname)))))
934 (defun generate-new-buffer (name)
935 "Create and return a buffer with a name based on NAME.
936 Choose the buffer's name using `generate-new-buffer-name'."
937 (get-buffer-create (generate-new-buffer-name name)))
939 (defvar abbreviated-home-dir nil
940 "The user's homedir abbreviated according to `directory-abbrev-alist'.")
942 (defun abbreviate-file-name (filename &optional hack-homedir)
943 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
944 See documentation of variable `directory-abbrev-alist' for more information.
945 If optional argument HACK-HOMEDIR is non-nil, then this also substitutes
946 \"~\" for the user's home directory."
947 (let ((handler (find-file-name-handler filename 'abbreviate-file-name)))
949 (funcall handler 'abbreviate-file-name filename hack-homedir)
950 ;; Get rid of the prefixes added by the automounter.
951 ;;(if (and (string-match automount-dir-prefix filename)
952 ;; (file-exists-p (file-name-directory
953 ;; (substring filename (1- (match-end 0))))))
954 ;; (setq filename (substring filename (1- (match-end 0)))))
955 (let ((tail directory-abbrev-alist))
956 ;; If any elt of directory-abbrev-alist matches this name,
957 ;; abbreviate accordingly.
959 (when (string-match (car (car tail)) filename)
961 (concat (cdr (car tail)) (substring filename (match-end 0)))))
962 (setq tail (cdr tail))))
964 ;; Compute and save the abbreviated homedir name.
965 ;; We defer computing this until the first time it's needed,
966 ;; to give time for directory-abbrev-alist to be set properly.
967 ;; We include the separator at the end, to avoid spurious
968 ;; matches such as `/usr/foobar' when the home dir is
970 (or abbreviated-home-dir
971 (setq abbreviated-home-dir
972 (let ((abbreviated-home-dir "$foo"))
975 (abbreviate-file-name (expand-file-name "~")))
977 (regexp-quote (string directory-sep-char))
979 ;; If FILENAME starts with the abbreviated homedir,
980 ;; make it start with `~' instead.
981 (if (and (string-match abbreviated-home-dir filename)
982 ;; If the home dir is just /, don't change it.
983 (not (and (= (match-end 0) 1)
984 (= (aref filename 0) directory-sep-char)))
985 (not (and (eq system-type 'windows-nt)
987 (string-match (concat "\\`[a-zA-Z]:"
989 (string directory-sep-char))
994 (match-string 1 filename)
995 (substring filename (match-end 0))))))
998 (defcustom find-file-not-true-dirname-list nil
999 "*List of logical names for which visiting shouldn't save the true dirname."
1000 :type '(repeat (string :tag "Name"))
1003 ;; This function is needed by FSF vc.el. I hope somebody can make it
1004 ;; work for XEmacs. -sb.
1005 ;; #### In what way does it not work? --hniksic
1006 (defun find-buffer-visiting (filename)
1007 "Return the buffer visiting file FILENAME (a string).
1008 This is like `get-file-buffer', except that it checks for any buffer
1009 visiting the same file, possibly under a different name.
1010 If there is no such live buffer, return nil."
1011 (let ((buf (get-file-buffer filename))
1012 (truename (abbreviate-file-name (file-truename filename))))
1014 (let ((list (buffer-list)) found)
1015 (while (and (not found) list)
1017 (set-buffer (car list))
1018 (if (and buffer-file-name
1019 (string= buffer-file-truename truename))
1020 (setq found (car list))))
1021 (setq list (cdr list)))
1023 (let ((number (nthcdr 10 (file-attributes truename)))
1024 (list (buffer-list)) found)
1025 (and buffer-file-numbers-unique
1027 (while (and (not found) list)
1029 (set-buffer (car list))
1030 (if (and buffer-file-number
1031 (equal buffer-file-number number)
1032 ;; Verify this buffer's file number
1033 ;; still belongs to its file.
1034 (file-exists-p buffer-file-name)
1035 (equal (nthcdr 10 (file-attributes buffer-file-name))
1037 (setq found (car list))))
1038 (setq list (cdr list))))
1041 (defun insert-file-contents-literally (filename &optional visit start end replace)
1042 "Like `insert-file-contents', q.v., but only reads in the file.
1043 A buffer may be modified in several ways after reading into the buffer due
1044 to advanced Emacs features, such as format decoding, character code
1045 conversion, find-file-hooks, automatic uncompression, etc.
1047 This function ensures that none of these modifications will take place."
1048 (let ((wrap-func (find-file-name-handler filename
1049 'insert-file-contents-literally)))
1051 (funcall wrap-func 'insert-file-contents-literally filename
1052 visit start end replace)
1053 (let ((file-name-handler-alist nil)
1055 (after-insert-file-functions nil)
1056 (coding-system-for-read 'binary)
1057 (coding-system-for-write 'binary)
1058 (find-buffer-file-type-function
1059 (if (fboundp 'find-buffer-file-type)
1060 (symbol-function 'find-buffer-file-type)
1064 (fset 'find-buffer-file-type (lambda (filename) t))
1065 (insert-file-contents filename visit start end replace))
1066 (if find-buffer-file-type-function
1067 (fset 'find-buffer-file-type find-buffer-file-type-function)
1068 (fmakunbound 'find-buffer-file-type)))))))
1070 (defun find-file-try-dired-noselect (filename)
1071 "Try to use dired to open FILENAME, which is directory."
1072 (if (and (fboundp 'dired-noselect) find-file-run-dired)
1073 (dired-noselect (if find-file-use-truenames
1074 (abbreviate-file-name (file-truename filename))
1076 (error "%s is a directory" filename)))
1078 (defun find-file-find-magic (filename)
1079 "Find entry in `find-file-magic-files-alist' that matches FILENAME."
1080 (find filename find-file-magic-files-alist :key #'car
1081 :test #'(lambda (fn predicate)
1082 (and (file-exists-p fn)
1083 (funcall predicate fn)))))
1085 ;;; Sync: XEmacs 21.5 (cb65bfaf7110 tip) 2015-07-03 --SY
1086 (defcustom find-file-wildcards t
1087 "*Non-nil means file-visiting commands should handle wildcards.
1088 For example, if you specify `*.c', that would visit all the files
1089 whose names match the pattern."
1094 (defcustom find-file-suppress-same-file-warnings nil
1095 "*Non-nil means suppress warning messages for symlinked files.
1096 When nil, Emacs prints a warning when visiting a file that is already
1097 visited, but with a different name. Setting this option to t
1098 suppresses this warning."
1103 ;;; FIXME: the #'loop here is generating one of those 'variable G26164
1104 ;;; bound but not referenced' warnings you get from cl loops. Might
1105 ;;; be able to fix this by using #'mapfam instead. --SY.
1106 (defun find-file-noselect (filename &optional nowarn rawfile wildcards)
1107 "Read file FILENAME into a buffer and return the buffer.
1108 If a buffer exists visiting FILENAME, return that one, but
1109 verify that the file has not changed since visited or saved.
1110 The buffer is not selected, just returned to the caller.
1111 If NOWARN is non-nil, warning messages will be suppressed.
1112 If RAWFILE is non-nil, the file is read literally."
1113 (setq filename (abbreviate-file-name (expand-file-name filename)))
1114 ;; SXEmacs addition:: Try magic files first
1115 (let ((mfa-item (find-file-find-magic filename)))
1117 (funcall (cdr mfa-item) filename)
1118 ;; End SXEmacs magic
1119 (if (file-directory-p filename)
1120 (or (and find-file-run-dired
1121 (loop for fn in find-directory-functions
1122 for x = (and (fboundp fn)
1124 (if find-file-use-truenames
1125 (abbreviate-file-name
1126 (file-truename filename))
1130 (error "%s is a directory" filename))
1133 (not (string-match "\\`/:" filename))
1134 (string-match "[[*?]" filename))
1135 (let ((files (condition-case nil
1136 (file-expand-wildcards filename t)
1137 (error (list filename))))
1138 (find-file-wildcards nil))
1140 (find-file-noselect filename)
1141 (mapcar #'find-file-noselect files)))
1142 (let* ((buf (get-file-buffer filename))
1143 (truename (abbreviate-file-name (file-truename filename)))
1144 (number (nthcdr 10 (file-attributes truename)))
1145 ; ;; Find any buffer for a file which has same truename.
1146 ; (other (and (not buf) (find-buffer-visiting filename)))
1149 ; ;; Let user know if there is a buffer with the same truename.
1153 ; find-file-suppress-same-file-warnings
1154 ; (string-equal filename (buffer-file-name other))
1155 ; (message "%s and %s are the same file"
1156 ; filename (buffer-file-name other)))
1157 ; ;; Optionally also find that buffer.
1158 ; (if (or find-file-existing-other-name find-file-visit-truename)
1159 ; (setq buf other))))
1162 (or find-file-compare-truenames find-file-use-truenames)
1163 (not find-file-suppress-same-file-warnings)
1167 (if (not (string-equal buffer-file-name filename))
1168 (message "%s and %s are the same file (%s)"
1169 filename buffer-file-name
1170 buffer-file-truename))))
1175 (verify-visited-file-modtime buf)
1176 (cond ((not (file-exists-p filename))
1177 (error "File %s no longer exists!" filename))
1178 ;; Certain files should be reverted automatically
1179 ;; if they have changed on disk and not in the buffer.
1180 ((and (not (buffer-modified-p buf))
1181 (dolist (rx revert-without-query nil)
1182 (when (string-match rx filename)
1184 (with-current-buffer buf
1185 (message "Reverting file %s..." filename)
1187 (message "Reverting file %s... done" filename)))
1189 (if (string= (file-name-nondirectory filename)
1192 (if (buffer-modified-p buf)
1193 (gettext "File %s changed on disk. Discard your edits? ")
1194 (gettext "File %s changed on disk. Reread from disk? "))
1195 (file-name-nondirectory filename))
1197 (if (buffer-modified-p buf)
1198 (gettext "File %s changed on disk. Discard your edits in %s? ")
1199 (gettext "File %s changed on disk. Reread from disk into %s? "))
1200 (file-name-nondirectory filename)
1201 (buffer-name buf))))
1202 (with-current-buffer buf
1203 (revert-buffer t t)))))
1204 (when (not (eq rawfile (not (null find-file-literally))))
1205 (with-current-buffer buf
1206 (if (buffer-modified-p)
1207 (if (y-or-n-p (if rawfile
1208 "Save file and revisit literally? "
1209 "Save file and revisit non-literally? "))
1212 (find-file-noselect-1 buf filename nowarn
1213 rawfile truename number))
1214 (if (y-or-n-p (if rawfile
1215 "Discard your edits and revisit file literally? "
1216 "Discard your edits and revisit file non-literally? "))
1217 (find-file-noselect-1 buf filename nowarn
1218 rawfile truename number)
1219 (error (if rawfile "File already visited non-literally"
1220 "File already visited literally"))))
1221 (if (y-or-n-p (if rawfile
1222 "Revisit file literally? "
1223 "Revisit file non-literally? "))
1224 (find-file-noselect-1 buf filename nowarn
1225 rawfile truename number)
1226 (error (if rawfile "File already visited non-literally"
1227 "File already visited literally"))))))
1228 ;; Return the buffer we are using.
1230 ;; Create a new buffer.
1231 (setq buf (create-file-buffer filename))
1232 ;; Catch various signals, such as QUIT, and kill the buffer
1234 (condition-case data
1236 (set-buffer-major-mode buf)
1237 ;; find-file-noselect-1 may use a different buffer.
1238 (find-file-noselect-1 buf filename nowarn
1239 rawfile truename number))
1242 (signal (car data) (cdr data)))))))))))
1244 (defun find-file-noselect-1 (buf filename nowarn rawfile truename number)
1245 (let ((inhibit-read-only t)
1247 (with-current-buffer buf
1248 (kill-local-variable 'find-file-literally)
1249 ;; Needed in case we are re-visiting the file with a different
1250 ;; text representation.
1251 (kill-local-variable 'buffer-file-coding-system)
1253 ; (and (default-value 'enable-multibyte-characters)
1255 ; (set-buffer-multibyte t))
1258 (insert-file-contents-literally filename t)
1259 (insert-file-contents filename t))
1261 (when (and (file-exists-p filename)
1262 (not (file-readable-p filename)))
1263 (signal 'file-error (list "File is not readable" filename)))
1265 ;; Unconditionally set error
1268 ;; Run find-file-not-found-hooks until one returns non-nil.
1269 (run-hook-with-args-until-success 'find-file-not-found-hooks)
1270 ;; If they fail too, set error.
1272 ;; Find the file's truename, and maybe use that as visited name.
1273 ;; automatically computed in XEmacs, unless jka-compr was used!
1274 (unless buffer-file-truename
1275 (setq buffer-file-truename truename))
1276 (setq buffer-file-number number)
1277 (and find-file-use-truenames
1278 ;; This should be in C. Put pathname
1279 ;; abbreviations that have been explicitly
1280 ;; requested back into the pathname. Most
1281 ;; importantly, strip out automounter /tmp_mnt
1282 ;; directories so that auto-save will work
1283 (setq buffer-file-name (abbreviate-file-name buffer-file-name)))
1284 ;; Set buffer's default directory to that of the file.
1285 (setq default-directory (file-name-directory buffer-file-name))
1286 ;; Turn off backup files for certain file names. Since
1287 ;; this is a permanent local, the major mode won't eliminate it.
1288 (and (not (funcall backup-enable-predicate buffer-file-name))
1290 (make-local-variable 'backup-inhibited)
1291 (setq backup-inhibited t)))
1294 (setq buffer-file-coding-system 'no-conversion)
1295 (make-local-variable 'find-file-literally)
1296 (setq find-file-literally t))
1297 (after-find-file error (not nowarn))
1298 (setq buf (current-buffer)))
1301 (defun insert-file-literally (filename)
1302 "Insert contents of file FILENAME into buffer after point with no conversion.
1304 This function is meant for the user to run interactively.
1305 Don't call it from programs! Use `insert-file-contents-literally' instead.
1306 \(Its calling sequence is different; see its documentation)."
1307 (interactive "*fInsert file literally: ")
1308 (if (file-directory-p filename)
1309 (signal 'file-error (list "Opening input file" "file is a directory"
1311 (let ((tem (insert-file-contents-literally filename)))
1312 (push-mark (+ (point) (car (cdr tem))))))
1314 (defvar find-file-literally nil
1315 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
1316 This is a permanent local.")
1317 (put 'find-file-literally 'permanent-local t)
1319 (defun find-file-literally (filename)
1320 "Visit file FILENAME with no conversion of any kind.
1321 Format conversion and character code conversion are both disabled,
1322 and multibyte characters are disabled in the resulting buffer.
1323 The major mode used is Fundamental mode regardless of the file name,
1324 and local variable specifications in the file are ignored.
1325 Automatic uncompression and adding a newline at the end of the
1326 file due to `require-final-newline' is also disabled.
1328 You cannot absolutely rely on this function to result in
1329 visiting the file literally. If Emacs already has a buffer
1330 which is visiting the file, you get the existing buffer,
1331 regardless of whether it was created literally or not.
1333 In a Lisp program, if you want to be sure of accessing a file's
1334 contents literally, you should create a temporary buffer and then read
1335 the file contents into it using `insert-file-contents-literally'."
1336 (interactive "FFind file literally: ")
1337 (switch-to-buffer (find-file-noselect filename nil t)))
1338 ;;; End Sync: XEmacs 21.5 (cb65bfaf7110 tip) 2015-07-03 --SY
1341 (defvar after-find-file-from-revert-buffer nil)
1343 (defun after-find-file (&optional error warn noauto
1344 after-find-file-from-revert-buffer
1346 "Called after finding a file and by the default revert function.
1347 Sets buffer mode, parses local variables.
1348 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
1349 error in reading the file. WARN non-nil means warn if there
1350 exists an auto-save file more recent than the visited file.
1351 NOAUTO means don't mess with auto-save mode.
1352 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1353 means this call was from `revert-buffer'.
1354 Fifth arg NOMODES non-nil means don't alter the file's modes.
1355 Finishes by calling the functions in `find-file-hooks'."
1356 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1361 (cond ((and error (file-attributes buffer-file-name))
1362 (setq buffer-read-only t)
1363 (gettext "File exists, but cannot be read."))
1364 ((not buffer-read-only)
1366 (file-newer-than-file-p (make-auto-save-file-name)
1368 (format "%s has auto save data; consider M-x recover-file"
1369 (file-name-nondirectory buffer-file-name))
1370 (setq not-serious t)
1371 (if error (gettext "(New file)") nil)))
1373 (setq not-serious t)
1374 (gettext "Note: file is write protected"))
1375 ((file-attributes (directory-file-name default-directory))
1376 (gettext "File not found and directory write-protected"))
1377 ((file-exists-p (file-name-directory buffer-file-name))
1378 (setq buffer-read-only nil))
1380 ;; If the directory the buffer is in doesn't exist,
1381 ;; offer to create it. It's better to do this now
1382 ;; than when we save the buffer, because we want
1383 ;; autosaving to work.
1384 (setq buffer-read-only nil)
1386 (or (file-exists-p (file-name-directory buffer-file-name))
1390 "The directory containing %s does not exist. Create? "
1391 (abbreviate-file-name buffer-file-name)))
1392 (make-directory (file-name-directory
1396 (kill-buffer (current-buffer))
1397 (signal 'quit nil))))
1402 (save-excursion (sit-for 1 t)))))
1403 (if (and auto-save-default (not noauto))
1404 (auto-save-mode t)))
1407 (run-hooks 'find-file-hooks)))
1409 (defun normal-mode (&optional find-file)
1410 "Choose the major mode for this buffer automatically.
1411 Also sets up any specified local variables of the file.
1412 Uses the visited file name, the -*- line, and the local variables spec.
1414 This function is called automatically from `find-file'. In that case,
1415 we may set up specified local variables depending on the value of
1416 `enable-local-variables': if it is t, we do; if it is nil, we don't;
1417 otherwise, we query. `enable-local-variables' is ignored if you
1418 run `normal-mode' explicitly."
1420 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1421 (and (condition-case err
1422 (progn (set-auto-mode)
1424 (error (message "File mode specification error: %s"
1425 (prin1-to-string err))
1428 (hack-local-variables (not find-file))
1429 (error (lwarn 'local-variables 'warning
1430 "File local-variables error: %s"
1431 (error-message-string err))))))
1433 ;; `auto-mode-alist' used to contain entries for modes in core and in packages.
1434 ;; The applicable entries are now located in the corresponding modes in
1435 ;; packages, the ones here are for core modes. Ditto for
1436 ;; `interpreter-mode-alist' below.
1437 ;; Per Abrahamsen suggested splitting auto-mode-alist to
1438 ;; several distinct variables such as, in order of precedence,
1439 ;; `user-auto-mode-alist' for users, `package-auto-mode-alist' for
1440 ;; packages and `auto-mode-alist' (which might also be called
1441 ;; `default-auto-mode-alist') for default stuff, such as some of the
1444 (defvar auto-mode-alist
1445 '((#r"\.te?xt\'" . text-mode)
1446 (#r"\.el\'" . emacs-lisp-mode)
1447 (#r"\.c?l\(?:i?sp\)?\'" . lisp-mode)
1448 (#r"\.article\'" . text-mode)
1449 (#r"\.letter\'" . text-mode)
1450 ;; Mailer puts message to be edited in /tmp/Re.... or Message
1451 ;; #### Unix-specific!
1452 ("\\`/tmp/Re" . text-mode)
1453 ("/Message[0-9]*\\'" . text-mode)
1454 ;; some news reader is reported to use this
1455 ("^/tmp/fol/" . text-mode)
1456 ;; .emacs following a directory delimiter in either Unix or
1458 (#r"[/\][._].*emacs\'" . emacs-lisp-mode)
1459 (#r"\.ml\'" . lisp-mode)
1461 "Alist of filename patterns vs. corresponding major mode functions.
1462 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1463 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1464 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1465 mode function to use. FUNCTION will be called, unless it is nil.
1467 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1468 calling FUNCTION (if it's not nil), we delete the suffix that matched
1469 REGEXP and search the list again for another match.")
1471 (defvar interpreter-mode-alist
1472 '(("emacs" . emacs-lisp-mode))
1473 "Alist mapping interpreter names to major modes.
1474 This alist is used to guess the major mode of a file based on the
1475 contents of the first line. This line often contains something like:
1477 but may contain something more imaginative like
1480 eval 'exec perl -w -S $0 ${1+\"$@\"}'.
1482 Each alist element looks like (INTERPRETER . MODE).
1483 The car of each element is a regular expression which is compared
1484 with the name of the interpreter specified in the first line.
1485 If it matches, mode MODE is selected.")
1487 (defvar binary-file-regexps
1488 '(#r"\.\(?:7[Zz]\|ARC\|E\(?:AR\|XE\)\|GIF\|J\(?:AR\|P\(?:E?G\)\)\|LZH\|PDF\|RAR\|WAR\|XPI\|Z\(?:IP\|OO\)\|arc\|bz2\|doc\|e\(?:ar\|lc\|xe\)\|g\(?:if\|z\)\|j\(?:ar\|p\(?:e?g\)\)\|l\(?:ha\|z\(?:h\|ma\)\)\|odt\|p\(?:bm\|df\|gm\|n[gm]\|pm\)\|s\(?:o\|x[cdimw]\)\|t\(?:ar\|gz\|iff\)\|war\|x\(?:pi\|z\)\|z\(?:ip\|oo\)\|[Zao]\)\'")
1489 "List of regexps of filenames containing binary (non-text) data.")
1492 ; (require 'regexp-opt)
1494 ; (format "\\.\\(?:%s\\)\\'"
1497 ; ;; Compressed files
1498 ; "7Z" "7z" "ARC" "EAR" "JAR" "LZH" "RAR" "WAR"
1499 ; "XPI" "Z" "ZIP" "ZOO" "arc" "bz2" "ear" "gz"
1500 ; "jar" "tar" "tgz" "tiff" "war" "xpi" "zip" "zoo"
1501 ; "zoo" "lha" "lzh" "lzma" "xz"
1503 ; "EXE" "exe" "elc" "o" "so" "a"
1505 ; "gif" "jpeg" "jpg" "pbm" "pgm" "png" "pnm" "ppm"
1506 ; "GIF" "JPEG" "JPG"
1508 ; "PDF" "odt" "pdf" "sxc" "sxd" "sxi" "sxm" "sxw" "doc")))))
1510 (defvar inhibit-first-line-modes-regexps
1512 "List of regexps; if one matches a file name, don't look for `-*-'.")
1514 (defvar inhibit-first-line-modes-suffixes nil
1515 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1516 When checking `inhibit-first-line-modes-regexps', we first discard
1517 from the end of the file name anything that matches one of these regexps.")
1519 (defvar user-init-file
1520 nil ; set by command-line
1521 "File name including directory of user's initialization file.
1523 This normally defaults to \"${XDG_CONFIG_HOME}/sxemacs/init.el\", if
1524 you are a XEmacs user you can get up and running quickly by symlinking
1525 your old \"~/.xemacs\" directory.")
1527 (defun set-auto-mode (&optional just-from-file-name)
1528 "Select major mode appropriate for current buffer.
1529 This checks for a -*- mode tag in the buffer's text,
1530 compares the filename against the entries in `auto-mode-alist',
1531 or checks the interpreter that runs this file against
1532 `interpreter-mode-alist'.
1534 It does not check for the `mode:' local variable in the
1535 Local Variables section of the file; for that, use `hack-local-variables'.
1537 If `enable-local-variables' is nil, this function does not check for a
1540 If the optional argument JUST-FROM-FILE-NAME is non-nil,
1541 then we do not set anything but the major mode,
1542 and we don't even do that unless it would come from the file name."
1544 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1545 ;; Do this by calling the hack-local-variables helper to avoid redundancy.
1546 ;; We bind enable-local-variables to nil this time because we're going to
1547 ;; call hack-local-variables-prop-line again later, "for real." Note that
1548 ;; this temporary binding does not prevent hack-local-variables-prop-line
1549 ;; from setting the major mode.
1550 (or (and enable-local-variables
1551 (let ((enable-local-variables nil))
1552 (hack-local-variables-prop-line nil))
1554 ;; It's not in the -*- line, so check the auto-mode-alist, unless
1555 ;; this buffer isn't associated with a file.
1556 (null buffer-file-name)
1557 (let ((name (file-name-sans-versions buffer-file-name))
1560 (setq keep-going nil)
1561 (let ((alist auto-mode-alist)
1564 ;; Find first matching alist entry.
1566 ;; #### This is incorrect. In NT, case sensitivity is a volume
1567 ;; property. For instance, NFS mounts *are* case sensitive.
1568 ;; Need internal function (file-name-case-sensitive f), F
1569 ;; being file or directory name. - kkm
1570 (let ((case-fold-search
1571 (eq system-type 'windows-nt)))
1572 (while (and (not mode) alist)
1573 (if (string-match (car (car alist)) name)
1574 (if (and (consp (cdr (car alist)))
1575 (nth 2 (car alist)))
1577 (setq mode (car (cdr (car alist)))
1578 name (substring name 0 (match-beginning 0))
1580 (setq mode (cdr (car alist))
1582 (setq alist (cdr alist))))
1583 (unless just-from-file-name
1584 ;; If we can't deduce a mode from the file name,
1585 ;; look for an interpreter specified in the first line.
1586 (if (and (null mode)
1587 (save-excursion ; XEmacs
1588 (goto-char (point-min))
1594 (goto-char (point-min)) (end-of-line) (point)))))
1595 (setq alist interpreter-mode-alist)
1597 (if (string-match (car (car alist)) firstline)
1599 (setq mode (cdr (car alist)))
1601 (setq alist (cdr alist)))))))
1603 (if (not (fboundp mode))
1604 (let ((name (declare-fboundp (package-get-package-provider mode))))
1606 (message "Mode %s is not installed. Download package %s" mode name)
1607 (message "Mode %s either doesn't exist or is not a known package" mode))
1610 (unless (and just-from-file-name
1612 ;; Don't reinvoke major mode.
1613 (eq mode major-mode)
1614 ;; Don't lose on minor modes.
1615 (assq mode minor-mode-alist)))
1616 (funcall mode))))))))))
1618 (defvar hack-local-variables-hook nil
1619 "Normal hook run after processing a file's local variables specs.
1620 Major modes can use this to examine user-specified local variables
1621 in order to initialize other data structure based on them.
1623 This hook runs even if there were no local variables or if their
1624 evaluation was suppressed. See also `enable-local-variables' and
1625 `enable-local-eval'.")
1627 (defun hack-local-variables (&optional force)
1628 "Parse, and bind or evaluate as appropriate, any local variables
1629 for current buffer."
1630 ;; Don't look for -*- if this file name matches any
1631 ;; of the regexps in inhibit-first-line-modes-regexps.
1632 (if (or (null buffer-file-name) ; don't lose if buffer has no file!
1633 (not (let ((temp inhibit-first-line-modes-regexps)
1634 (name (if buffer-file-name
1635 (file-name-sans-versions buffer-file-name)
1637 (while (let ((sufs inhibit-first-line-modes-suffixes))
1638 (while (and sufs (not
1639 (string-match (car sufs) name)))
1640 (setq sufs (cdr sufs)))
1642 (setq name (substring name 0 (match-beginning 0))))
1644 (not (string-match (car temp) name)))
1645 (setq temp (cdr temp))
1648 ;; Look for variables in the -*- line.
1649 (hack-local-variables-prop-line force)
1650 ;; Look for "Local variables:" block in last page.
1651 (hack-local-variables-last-page force)))
1652 (run-hooks 'hack-local-variables-hook))
1654 ;;; Local variables may be specified in the last page of the file (within 3k
1655 ;;; from the end of the file and after the last ^L) in the form
1657 ;;; Local variables:
1658 ;;; variable-name: variable-value
1661 ;;; The lines may begin with a common prefix, like ";;; " in the above
1662 ;;; example. They may also have a common suffix (" */" for example). In
1663 ;;; this form, the local variable "mode" can be used to change the major
1664 ;;; mode, and the local variable "eval" can be used to evaluate an arbitrary
1667 ;;; Local variables may also be specified in the first line of the file.
1668 ;;; Embedded in this line are a pair of "-*-" sequences. What lies between
1669 ;;; them are variable-name/variable-value pairs, like:
1671 ;;; -*- mode: emacs-lisp -*-
1672 ;;; or -*- mode: postscript; version-control: never -*-
1673 ;;; or -*- tags-file-name: "/foo/bar/TAGS" -*-
1675 ;;; The local variable "eval" is not used with this form. For hysterical
1676 ;;; reasons, the syntax "-*- modename -*-" is allowed as well.
1679 (defun hack-local-variables-p (modeline)
1680 (or (eq enable-local-variables t)
1681 (and enable-local-variables
1682 (save-window-excursion
1684 (switch-to-buffer (current-buffer))
1686 ;; If we fail to switch in the selected window,
1687 ;; it is probably a minibuffer.
1688 ;; So try another window.
1690 (switch-to-buffer-other-window (current-buffer))
1692 (switch-to-buffer-other-frame (current-buffer))))))
1693 (or modeline (save-excursion
1695 (set-window-start (selected-window) (point))))
1697 "Set local variables as specified %s of %s? "
1698 (if modeline "in -*- line" "at end")
1699 (if buffer-file-name
1700 (file-name-nondirectory buffer-file-name)
1701 (concat "buffer " (buffer-name)))))))))
1703 (defun hack-local-variables-last-page (&optional force)
1704 ;; Set local variables set in the "Local Variables:" block of the last page.
1706 (goto-char (point-max))
1707 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1708 (if (let ((case-fold-search t))
1709 (and (search-forward "Local Variables:" nil t)
1711 (hack-local-variables-p nil))))
1713 prefix prefixlen suffix start
1714 (enable-local-eval enable-local-eval))
1715 ;; The prefix is what comes before "local variables:" in its line.
1716 ;; The suffix is what comes after "local variables:" in its line.
1717 (skip-chars-forward " \t")
1719 (setq suffix (buffer-substring (point)
1720 (progn (end-of-line) (point)))))
1721 (goto-char (match-beginning 0))
1724 (buffer-substring (point)
1725 (progn (beginning-of-line) (point)))))
1726 (if prefix (setq prefixlen (length prefix)
1727 prefix (regexp-quote prefix)))
1728 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1730 ;; Look at next local variable spec.
1731 (if selective-display (re-search-forward "[\n\C-m]")
1733 ;; Skip the prefix, if any.
1735 (if (looking-at prefix)
1736 (forward-char prefixlen)
1737 (error "Local variables entry is missing the prefix")))
1738 ;; Find the variable name; strip whitespace.
1739 (skip-chars-forward " \t")
1740 (setq start (point))
1741 (skip-chars-forward "^:\n")
1742 (if (eolp) (error "Missing colon in local variables entry"))
1743 (skip-chars-backward " \t")
1744 (let* ((str (buffer-substring start (point)))
1747 ;; Setting variable named "end" means end of list.
1748 (if (string-equal (downcase str) "end")
1750 ;; Otherwise read the variable value.
1751 (skip-chars-forward "^:")
1753 (setq val (read (current-buffer)))
1754 (skip-chars-backward "\n")
1755 (skip-chars-forward " \t")
1756 (or (if suffix (looking-at suffix) (eolp))
1757 (error "Local variables entry is terminated incorrectly"))
1758 ;; Set the variable. "Variables" mode and eval are funny.
1759 (hack-one-local-variable var val))))))))
1761 ;; jwz - New Version 20.1/19.15
1762 (defun hack-local-variables-prop-line (&optional force)
1763 ;; Set local variables specified in the -*- line.
1764 ;; Returns t if mode was set.
1767 (goto-char (point-min))
1768 (skip-chars-forward " \t\n\r")
1769 (let ((end (save-excursion
1770 ;; If the file begins with "#!"
1771 ;; (un*x exec interpreter magic), look
1772 ;; for mode frobs in the first two
1773 ;; lines. You cannot necessarily
1774 ;; put them in the first line of
1775 ;; such a file without screwing up
1776 ;; the interpreter invocation.
1777 (end-of-line (and (looking-at "^#!") 2))
1779 ;; Parse the -*- line into the `result' alist.
1780 (cond ((not (search-forward "-*-" end t))
1781 ;; doesn't have one.
1783 ((looking-at "[ \t]*\\([^ \t\n\r:;]+?\\)\\([ \t]*-\\*-\\)")
1784 ;; Antiquated form: "-*- ModeName -*-".
1787 (intern (buffer-substring
1792 ;; Usual form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1793 ;; (last ";" is optional).
1795 (if (search-forward "-*-" end t)
1796 (setq end (- (point) 3))
1797 (error "-*- not terminated before end of line")))
1798 (while (< (point) end)
1799 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1800 (error "malformed -*- line"))
1801 (goto-char (match-end 0))
1802 ;; There used to be a downcase here,
1803 ;; but the manual didn't say so,
1804 ;; and people want to set var names that aren't all lc.
1805 (let ((key (intern (buffer-substring
1808 (val (save-restriction
1809 (narrow-to-region (point) end)
1810 (read (current-buffer)))))
1811 ;; Case sensitivity! Icepicks in my forehead!
1812 (if (equal (downcase (symbol-name key)) "mode")
1814 (setq result (cons (cons key val) result))
1815 (skip-chars-forward " \t;")))
1816 (setq result (nreverse result))))))
1818 (let ((set-any-p (or force
1819 ;; It's OK to force null specifications.
1821 ;; It's OK to force mode-only specifications.
1822 (let ((remaining result)
1823 (mode-specs-only t))
1825 (if (eq (car (car remaining)) 'mode)
1826 (setq remaining (cdr remaining))
1827 ;; Otherwise, we have a real local.
1828 (setq mode-specs-only nil
1832 ;; Otherwise, check.
1833 (hack-local-variables-p t)))
1836 (let ((key (car (car result)))
1837 (val (cdr (car result))))
1838 (cond ((eq key 'mode)
1840 (let ((mode (intern (concat (downcase (symbol-name val))
1842 ;; Without this guard, `normal-mode' would potentially run
1843 ;; the major mode function twice: once via `set-auto-mode'
1844 ;; and once via `hack-local-variables'.
1845 (if (not (eq mode major-mode))
1849 (hack-one-local-variable key val))
1852 (setq result (cdr result)))
1855 (defconst ignored-local-variables
1856 (list 'enable-local-eval)
1857 "Variables to be ignored in a file's local variable spec.")
1859 ;; Get confirmation before setting these variables as locals in a file.
1860 (put 'debugger 'risky-local-variable t)
1861 (put 'enable-local-eval 'risky-local-variable t)
1862 (put 'ignored-local-variables 'risky-local-variable t)
1863 (put 'eval 'risky-local-variable t)
1864 (put 'file-name-handler-alist 'risky-local-variable t)
1865 (put 'minor-mode-map-alist 'risky-local-variable t)
1866 (put 'after-load-alist 'risky-local-variable t)
1867 (put 'buffer-file-name 'risky-local-variable t)
1868 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1869 (put 'buffer-file-truename 'risky-local-variable t)
1870 (put 'exec-path 'risky-local-variable t)
1871 (put 'load-path 'risky-local-variable t)
1872 (put 'exec-directory 'risky-local-variable t)
1873 (put 'process-environment 'risky-local-variable t)
1874 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1875 (put 'outline-level 'risky-local-variable t)
1876 (put 'rmail-output-file-alist 'risky-local-variable t)
1878 ;; This one is safe because the user gets to check it before it is used.
1879 (put 'compile-command 'safe-local-variable t)
1881 ;(defun hack-one-local-variable-quotep (exp)
1882 ; (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1884 ;; "Set" one variable in a local variables spec.
1885 ;; A few variable names are treated specially.
1886 (defun hack-one-local-variable (var val)
1887 (cond ((eq var 'mode)
1888 (funcall (intern (concat (downcase (symbol-name val))
1890 ((memq var ignored-local-variables)
1892 ;; "Setting" eval means either eval it or do nothing.
1893 ;; Likewise for setting hook variables.
1894 ((or (get var 'risky-local-variable)
1896 (string-match #r"-hooks?$\|-functions?$\|-forms?$\|-program$\|-command$"
1898 (not (get var 'safe-local-variable))))
1899 ; ;; Permit evaling a put of a harmless property
1900 ; ;; if the args do nothing tricky.
1901 ; (if (or (and (eq var 'eval)
1903 ; (eq (car val) 'put)
1904 ; (hack-one-local-variable-quotep (nth 1 val))
1905 ; (hack-one-local-variable-quotep (nth 2 val))
1906 ; ;; Only allow safe values of lisp-indent-hook;
1908 ; (or (numberp (nth 3 val))
1909 ; (equal (nth 3 val) ''defun))
1910 ; (memq (nth 1 (nth 2 val))
1911 ; '(lisp-indent-hook)))
1912 (if (and (not (zerop (user-uid)))
1913 (or (eq enable-local-eval t)
1914 (and enable-local-eval
1915 (save-window-excursion
1916 (switch-to-buffer (current-buffer))
1919 (set-window-start (selected-window) (point)))
1920 (setq enable-local-eval
1921 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1922 (file-name-nondirectory buffer-file-name))))))))
1924 (save-excursion (eval val))
1925 (make-local-variable var)
1927 (message "Ignoring `eval:' in file's local variables")))
1928 ;; Ordinary variable, really set it.
1929 (t (make-local-variable var)
1932 (defcustom change-major-mode-with-file-name t
1933 "*Non-nil means \\[write-file] should set the major mode from the file name.
1934 However, the mode will not be changed if
1935 \(1) a local variables list or the `-*-' line specifies a major mode, or
1936 \(2) the current major mode is a \"special\" mode,
1937 \ not suitable for ordinary files, or
1938 \(3) the new file name does not particularly specify any mode."
1940 :group 'editing-basics)
1942 (defun set-visited-file-name (filename &optional no-query along-with-file)
1943 "Change name of file visited in current buffer to FILENAME.
1944 The next time the buffer is saved it will go in the newly specified file.
1945 nil or empty string as argument means make buffer not be visiting any file.
1946 Remember to delete the initial contents of the minibuffer
1947 if you wish to pass an empty string as the argument.
1949 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1950 confirmation in the case where another buffer is already visiting FILENAME.
1952 The optional third argument ALONG-WITH-FILE, if non-nil, means that
1953 the old visited file has been renamed to the new name FILENAME."
1954 (interactive "FSet visited file name: ")
1955 (if (buffer-base-buffer)
1956 (error "An indirect buffer cannot visit a file"))
1960 (if (string-equal filename "")
1962 (expand-file-name filename))))
1965 (setq truename (file-truename filename))
1966 ;; #### Do we need to check if truename is non-nil?
1967 (if find-file-use-truenames
1968 (setq filename truename))))
1969 (let ((buffer (and filename (find-buffer-visiting filename))))
1970 (and buffer (not (eq buffer (current-buffer)))
1972 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1975 (or (equal filename buffer-file-name)
1977 (and filename (lock-buffer filename))
1979 (setq buffer-file-name filename)
1980 (if filename ; make buffer name reflect filename.
1981 (let ((new-name (file-name-nondirectory buffer-file-name)))
1982 (if (string= new-name "")
1983 (error "Empty file name"))
1984 (setq default-directory (file-name-directory buffer-file-name))
1985 (or (string= new-name (buffer-name))
1986 (rename-buffer new-name t))))
1987 (setq buffer-backed-up nil)
1989 (clear-visited-file-modtime))
1990 (compute-buffer-file-truename) ; insert-file-contents does this too.
1991 ; ;; Abbreviate the file names of the buffer.
1994 ; (setq buffer-file-truename (abbreviate-file-name truename))
1995 ; (if find-file-visit-truename
1996 ; (setq buffer-file-name buffer-file-truename))))
1997 (setq buffer-file-number
1999 (nthcdr 10 (file-attributes buffer-file-name))
2001 ;; write-file-hooks is normally used for things like ftp-find-file
2002 ;; that visit things that are not local files as if they were files.
2003 ;; Changing to visit an ordinary local file instead should flush the hook.
2004 (kill-local-variable 'write-file-hooks)
2005 (kill-local-variable 'after-save-hook)
2006 (kill-local-variable 'local-write-file-hooks)
2007 (kill-local-variable 'write-file-data-hooks)
2008 (kill-local-variable 'revert-buffer-function)
2009 (kill-local-variable 'backup-inhibited)
2010 ;; If buffer was read-only because of version control,
2011 ;; that reason is gone now, so make it writable.
2015 (setq buffer-read-only nil))
2016 (kill-local-variable 'vc-mode)))
2017 ;; Turn off backup files for certain file names.
2018 ;; Since this is a permanent local, the major mode won't eliminate it.
2019 (and buffer-file-name
2020 (not (funcall backup-enable-predicate buffer-file-name))
2022 (make-local-variable 'backup-inhibited)
2023 (setq backup-inhibited t)))
2024 (let ((oauto buffer-auto-save-file-name))
2025 ;; If auto-save was not already on, turn it on if appropriate.
2026 (if (not buffer-auto-save-file-name)
2027 (and buffer-file-name auto-save-default
2029 ;; If auto save is on, start using a new name.
2030 ;; We deliberately don't rename or delete the old auto save
2031 ;; for the old visited file name. This is because perhaps
2032 ;; the user wants to save the new state and then compare with the
2033 ;; previous state from the auto save file.
2034 (setq buffer-auto-save-file-name
2035 (make-auto-save-file-name)))
2036 ;; Rename the old auto save file if any.
2037 (and oauto buffer-auto-save-file-name
2038 (file-exists-p oauto)
2039 (rename-file oauto buffer-auto-save-file-name t)))
2040 (if buffer-file-name
2041 (not along-with-file)
2042 (set-buffer-modified-p t))
2043 ;; Update the major mode, if the file name determines it.
2045 ;; Don't change the mode if it is special.
2046 (or (not change-major-mode-with-file-name)
2047 (get major-mode 'mode-class)
2048 ;; Don't change the mode if the local variable list specifies it.
2049 (hack-local-variables t)
2053 (run-hooks 'after-set-visited-file-name-hooks))
2055 (defun write-file (filename &optional confirm codesys)
2056 "Write current buffer into file FILENAME.
2057 Makes buffer visit that file, and marks it not modified.
2058 If the buffer is already visiting a file, you can specify
2059 a directory name as FILENAME, to write a file of the same
2060 old name in that directory.
2061 If optional second arg CONFIRM is non-nil,
2062 ask for confirmation for overwriting an existing file.
2063 Under XEmacs/Mule, optional third argument specifies the
2064 coding system to use when encoding the file. Interactively,
2065 with a prefix argument, you will be prompted for the coding system."
2066 ;; (interactive "FWrite file: ")
2068 (list (if buffer-file-name
2069 (read-file-name "Write file: "
2071 (read-file-name "Write file: "
2072 (cdr (assq 'default-directory
2073 (buffer-local-variables)))
2074 nil nil (buffer-name)))
2076 (if (and current-prefix-arg (featurep 'file-coding))
2077 (read-coding-system "Coding system: "))))
2078 (and (eq (current-buffer) mouse-grabbed-buffer)
2079 (error "Can't write minibuffer window"))
2080 (or (null filename) (string-equal filename "")
2082 ;; If arg is just a directory,
2083 ;; use same file name, but in that directory.
2084 (if (and (file-directory-p filename) buffer-file-name)
2085 (setq filename (concat (file-name-as-directory filename)
2086 (file-name-nondirectory buffer-file-name))))
2088 (file-exists-p filename)
2089 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
2090 (error "Canceled")))
2091 (set-visited-file-name filename)))
2092 (set-buffer-modified-p t)
2093 (setq buffer-read-only nil)
2095 (let ((buffer-file-coding-system (get-coding-system codesys)))
2099 (defun backup-buffer ()
2100 "Make a backup of the disk file visited by the current buffer, if appropriate.
2101 This is normally done before saving the buffer the first time.
2102 If the value is non-nil, it is the result of `file-modes' on the original file;
2103 this means that the caller, after saving the buffer, should change the modes
2104 of the new file to agree with the old modes."
2105 (if buffer-file-name
2106 (let ((handler (find-file-name-handler buffer-file-name 'backup-buffer)))
2108 (funcall handler 'backup-buffer)
2109 (if (and make-backup-files
2110 (not backup-inhibited)
2111 (not buffer-backed-up)
2112 (file-exists-p buffer-file-name)
2113 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
2115 (let ((real-file-name buffer-file-name)
2116 backup-info backupname targets setmodes)
2117 ;; If specified name is a symbolic link, chase it to the target.
2118 ;; Thus we make the backups in the directory where the real file is.
2119 (setq real-file-name (file-chase-links real-file-name))
2120 (setq backup-info (find-backup-file-name real-file-name)
2121 backupname (car backup-info)
2122 targets (cdr backup-info))
2123 ;;; (if (file-directory-p buffer-file-name)
2124 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
2127 (let ((delete-old-versions
2128 ;; If have old versions to maybe delete,
2129 ;; ask the user to confirm now, before doing anything.
2130 ;; But don't actually delete till later.
2132 (or (eq delete-old-versions t)
2133 (eq delete-old-versions nil))
2134 (or delete-old-versions
2135 (y-or-n-p (format "Delete excess backup versions of %s? "
2136 real-file-name))))))
2137 ;; Actually write the back up file.
2139 (if (or file-precious-flag
2140 ; (file-symlink-p buffer-file-name)
2142 (and backup-by-copying-when-linked
2143 (> (file-nlinks real-file-name) 1))
2144 (and backup-by-copying-when-mismatch
2145 (let ((attr (file-attributes real-file-name)))
2147 (not (file-ownership-preserved-p real-file-name))))))
2149 (copy-file real-file-name backupname t t)
2151 ;; If copying fails because file BACKUPNAME
2152 ;; is not writable, delete that file and try again.
2153 (if (and (file-exists-p backupname)
2154 (not (file-writable-p backupname)))
2155 (delete-file backupname))
2156 (copy-file real-file-name backupname t t)))
2157 ;; rename-file should delete old backup.
2158 (rename-file real-file-name backupname t)
2159 (setq setmodes (file-modes backupname)))
2161 ;; If trouble writing the backup, write
2162 ;; it in `auto-save-directory'. Fall
2163 ;; back to $HOME if that's not possible.
2165 (expand-file-name "%backup%~"
2166 (or (when (and auto-save-directory
2167 (file-writable-p auto-save-directory))
2168 auto-save-directory)
2170 (message "Cannot write backup file; backing up in %s" backupname)
2173 (copy-file real-file-name backupname t t)
2175 ;; If copying fails because file BACKUPNAME
2176 ;; is not writable, delete that file and try again.
2177 (if (and (file-exists-p backupname)
2178 (not (file-writable-p backupname)))
2179 (delete-file backupname))
2180 (copy-file real-file-name backupname t t)))))
2181 (setq buffer-backed-up t)
2182 ;; Now delete the old versions, if desired.
2183 (if delete-old-versions
2185 (ignore-file-errors (delete-file (car targets)))
2186 (setq targets (cdr targets))))
2188 (file-error nil)))))))))
2190 (defun file-name-sans-versions (name &optional keep-backup-version)
2191 "Return FILENAME sans backup versions or strings.
2192 This is a separate procedure so your site-init or startup file can
2194 If the optional argument KEEP-BACKUP-VERSION is non-nil,
2195 we do not remove backup version numbers, only true file version numbers."
2196 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
2198 (funcall handler 'file-name-sans-versions name keep-backup-version)
2200 (if keep-backup-version
2202 (or (string-match #r"\.~[0-9.]+~\'" name)
2203 ;; XEmacs - VC uses extensions like ".~tagname~" or ".~1.1.5.2~"
2204 (let ((pos (string-match "\\.~\\([^.~ \t]+\\|[0-9.]+\\)~\\'" name)))
2206 ;; #### - is this filesystem check too paranoid?
2207 (file-exists-p (substring name 0 pos))
2209 (string-match "~\\'" name)
2212 (defun file-ownership-preserved-p (file)
2213 "Return t if deleting FILE and rewriting it would preserve the owner."
2214 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
2216 (funcall handler 'file-ownership-preserved-p file)
2217 (let ((attributes (file-attributes file)))
2218 ;; Return t if the file doesn't exist, since it's true that no
2219 ;; information would be lost by an (attempted) delete and create.
2220 (or (null attributes)
2221 (= (nth 2 attributes) (user-uid)))))))
2223 (defun file-name-sans-extension (filename)
2224 "Return FILENAME sans final \"extension\".
2225 The extension, in a file name, is the part that follows the last `.'."
2227 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
2229 (if (string-match #r"\.[^.]*\'" file)
2230 (if (setq directory (file-name-directory filename))
2231 (expand-file-name (substring file 0 (match-beginning 0))
2233 (substring file 0 (match-beginning 0)))
2236 (defun file-name-extension (filename &optional period)
2237 "Return FILENAME's final \"extension\".
2238 The extension, in a file name, is the part that follows the last `.'.
2239 Return nil for extensionless file names such as `foo'.
2240 Return the empty string for file names such as `foo.'.
2242 If PERIOD is non-nil, then the returned value includes the period
2243 that delimits the extension, and if FILENAME has no extension,
2246 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
2247 (if (string-match #r"\.[^.]*\'" file)
2248 (substring file (+ (match-beginning 0) (if period 0 1)))
2252 (defun make-backup-file-name (file)
2253 "Create the non-numeric backup file name for FILE.
2254 This is a separate function so you can redefine it for customization."
2255 ;; FSF has code here for MS-DOS short filenames, not supported in XEmacs.
2258 (defun backup-file-name-p (file)
2259 "Return non-nil if FILE is a backup file name (numeric or not).
2260 This is a separate function so you can redefine it for customization.
2261 You may need to redefine `file-name-sans-versions' as well."
2262 (string-match "~\\'" file))
2264 ;; This is used in various files.
2265 ;; The usage of bv-length is not very clean,
2266 ;; but I can't see a good alternative,
2267 ;; so as of now I am leaving it alone.
2268 (defun backup-extract-version (fn)
2269 "Given the name of a numeric backup file, return the backup number.
2270 Uses the free variable `bv-length', whose value should be
2271 the index in the name where the version number begins."
2272 (declare (special bv-length))
2273 (if (and (string-match "[0-9]+~\\'" fn bv-length)
2274 (= (match-beginning 0) bv-length))
2275 (string-to-int (substring fn bv-length -1))
2278 (defun find-backup-file-name (fn)
2279 "Find a file name for a backup file, and suggestions for deletions.
2280 Value is a list whose car is the name for the backup file
2281 and whose cdr is a list of old versions to consider deleting now.
2282 If the value is nil, don't make a backup."
2283 (declare (special bv-length))
2284 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
2285 ;; Run a handler for this function so that ange-ftp can refuse to do it.
2287 (funcall handler 'find-backup-file-name fn)
2288 (if (eq version-control 'never)
2289 (list (make-backup-file-name fn))
2290 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
2291 ;; used by backup-extract-version:
2292 (bv-length (length base-versions))
2296 (deserve-versions-p nil)
2297 (number-to-delete 0))
2299 (setq possibilities (file-name-all-completions
2301 (file-name-directory fn))
2302 versions (sort (mapcar
2303 #'backup-extract-version
2306 high-water-mark (apply #'max 0 versions)
2307 deserve-versions-p (or version-control
2308 (> high-water-mark 0))
2309 number-to-delete (- (length versions)
2310 kept-old-versions kept-new-versions -1))
2312 (setq possibilities nil)))
2313 (if (not deserve-versions-p)
2314 (list (make-backup-file-name fn))
2315 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
2316 (if (and (> number-to-delete 0)
2317 ;; Delete nothing if there is overflow
2318 ;; in the number of versions to keep.
2319 (>= (+ kept-new-versions kept-old-versions -1) 0))
2320 (mapcar #'(lambda (n)
2321 (concat fn ".~" (int-to-string n) "~"))
2322 (let ((v (nthcdr kept-old-versions versions)))
2323 (rplacd (nthcdr (1- number-to-delete) v) ())
2326 (defun file-nlinks (filename)
2327 "Return number of names file FILENAME has."
2328 (car (cdr (file-attributes filename))))
2330 (defun file-relative-name (filename &optional directory)
2331 "Convert FILENAME to be relative to DIRECTORY (default: default-directory).
2332 This function returns a relative file name which is equivalent to FILENAME
2333 when used with that default directory as the default.
2334 If this is impossible (which can happen on MS Windows when the file name
2335 and directory use different drive names) then it returns FILENAME."
2337 (let ((fname (expand-file-name filename)))
2338 (setq directory (file-name-as-directory
2339 (expand-file-name (or directory default-directory))))
2340 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2341 ;; drive names, they can't be relative, so return the absolute name.
2342 (if (and (eq system-type 'windows-nt)
2343 (not (string-equal (substring fname 0 2)
2344 (substring directory 0 2))))
2346 (let ((ancestor ".")
2347 (fname-dir (file-name-as-directory fname)))
2348 (while (and (not (string-match (concat "^" (regexp-quote directory))
2350 (not (string-match (concat "^" (regexp-quote directory)) fname)))
2351 (setq directory (file-name-directory (substring directory 0 -1))
2352 ancestor (if (equal ancestor ".")
2354 (concat "../" ancestor))))
2355 ;; Now ancestor is empty, or .., or ../.., etc.
2356 (if (string-match (concat "^" (regexp-quote directory)) fname)
2357 ;; We matched within FNAME's directory part.
2358 ;; Add the rest of FNAME onto ANCESTOR.
2359 (let ((rest (substring fname (match-end 0))))
2360 (if (and (equal ancestor ".")
2361 (not (equal rest "")))
2362 ;; But don't bother with ANCESTOR if it would give us `./'.
2364 (concat (file-name-as-directory ancestor) rest)))
2365 ;; We matched FNAME's directory equivalent.
2368 (defun save-buffer (&optional args)
2369 "Save current buffer in visited file if modified. Versions described below.
2371 By default, makes the previous version into a backup file
2372 if previously requested or if this is the first save.
2373 With 1 or 3 \\[universal-argument]'s, marks this version
2374 to become a backup when the next save is done.
2375 With 2 or 3 \\[universal-argument]'s,
2376 unconditionally makes the previous version into a backup file.
2377 With argument of 0, never makes the previous version into a backup file.
2379 If a file's name is FOO, the names of its numbered backup versions are
2380 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2381 Numeric backups (rather than FOO~) will be made if value of
2382 `version-control' is not the atom `never' and either there are already
2383 numeric versions of the file being backed up, or `version-control' is
2385 We don't want excessive versions piling up, so there are variables
2386 `kept-old-versions', which tells XEmacs how many oldest versions to keep,
2387 and `kept-new-versions', which tells how many newest versions to keep.
2388 Defaults are 2 old versions and 2 new.
2389 `dired-kept-versions' controls dired's clean-directory (.) command.
2390 If `delete-old-versions' is nil, system will query user
2391 before trimming versions. Otherwise it does it silently."
2393 (let ((modp (buffer-modified-p))
2394 (large (> (buffer-size) 50000))
2395 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2396 (memq args '(16 64)))))
2397 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2398 (if (and modp large) (display-message
2399 'progress (format "Saving file %s..."
2400 (buffer-file-name))))
2402 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2404 (defun delete-auto-save-file-if-necessary (&optional force)
2405 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2406 Normally delete only if the file was written by this XEmacs
2407 since the last real save, but optional arg FORCE non-nil means delete anyway."
2408 (and buffer-auto-save-file-name delete-auto-save-files
2409 (not (string= buffer-file-name buffer-auto-save-file-name))
2410 (or force (recent-auto-save-p))
2412 (ignore-file-errors (delete-file buffer-auto-save-file-name))
2413 (set-buffer-auto-saved))))
2415 ;; XEmacs change (from Sun)
2416 ;; used to communicate with continue-save-buffer:
2417 (defvar continue-save-buffer-hooks-tail nil)
2420 (defun basic-write-file-data (realname truename)
2421 ;; call the hooks until the bytes are put
2422 ;; call write-region as a last resort
2423 (let ((region-written nil)
2424 (hooks write-file-data-hooks))
2425 (while (and hooks (not region-written))
2426 (setq region-written (funcall (car hooks) realname)
2428 (if (not region-written)
2429 (write-region (point-min) (point-max) realname nil t truename))))
2431 (put 'after-save-hook 'permanent-local t)
2432 (defvar after-save-hook nil
2433 "Normal hook that is run after a buffer is saved to its file.
2434 These hooks are considered to pertain to the visited file.
2435 So this list is cleared if you change the visited file name.")
2437 (defun files-fetch-hook-value (hook)
2438 (let ((localval (symbol-value hook))
2439 (globalval (default-value hook)))
2440 (if (memq t localval)
2441 (setq localval (append (delq t localval) (delq t globalval))))
2444 (defun basic-save-buffer ()
2445 "Save the current buffer in its visited file, if it has been modified.
2446 After saving the buffer, run `after-save-hook'."
2449 ;; In an indirect buffer, save its base buffer instead.
2450 (if (buffer-base-buffer)
2451 (set-buffer (buffer-base-buffer)))
2452 (if (buffer-modified-p)
2453 (let ((recent-save (recent-auto-save-p)))
2454 ;; If buffer has no file name, ask user for one.
2455 (or buffer-file-name
2458 (read-file-name "File to save in: ") nil)))
2459 (and (file-exists-p filename)
2460 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2462 (error "Canceled")))
2463 (set-visited-file-name filename)))
2464 (or (verify-visited-file-modtime (current-buffer))
2465 (not (file-exists-p buffer-file-name))
2467 (format "%s has changed since visited or saved. Save anyway? "
2468 (file-name-nondirectory buffer-file-name)))
2469 (error "Save not confirmed"))
2473 ;; Add final newline if required. See `require-final-newline'.
2474 (when (and (not (eq (char-before (point-max)) ?\n)) ; common case
2475 (char-before (point-max)) ; empty buffer?
2476 (not (and (eq selective-display t)
2477 (eq (char-before (point-max)) ?\r)))
2478 (or (eq require-final-newline t)
2479 (and require-final-newline
2481 (format "Buffer %s does not end in newline. Add one? "
2484 (goto-char (point-max))
2487 ;; Run the write-file-hooks until one returns non-nil.
2488 ;; Bind after-save-hook to nil while running the
2489 ;; write-file-hooks so that if this function is called
2490 ;; recursively (from inside a write-file-hook) the
2491 ;; after-hooks will only get run once (from the
2494 ;; Ugh, have to duplicate logic of run-hook-with-args-until-success
2495 (let ((hooks (append (files-fetch-hook-value 'write-contents-hooks)
2496 (files-fetch-hook-value
2497 'local-write-file-hooks)
2498 (files-fetch-hook-value 'write-file-hooks)))
2499 (after-save-hook nil)
2500 (local-write-file-hooks nil)
2501 (write-contents-hooks nil)
2502 (write-file-hooks nil)
2505 (let ((continue-save-buffer-hooks-tail hooks))
2506 (not (setq done (funcall (car hooks))))))
2507 (setq hooks (cdr hooks)))
2508 ;; If a hook returned t, file is already "written".
2509 ;; Otherwise, write it the usual way now.
2511 (basic-save-buffer-1)))
2512 ;; XEmacs: next two clauses (buffer-file-number setting and
2513 ;; set-file-modes) moved into basic-save-buffer-1.
2515 ;; If the auto-save file was recent before this command,
2517 (delete-auto-save-file-if-necessary recent-save)
2518 ;; Support VC `implicit' locking.
2519 (if-fboundp 'vc-after-save
2521 (run-hooks 'after-save-hook))
2522 (display-message 'no-log "(No changes need to be saved)"))))
2524 ;; This does the "real job" of writing a buffer into its visited file
2525 ;; and making a backup file. This is what is normally done
2526 ;; but inhibited if one of write-file-hooks returns non-nil.
2527 ;; It returns a value to store in setmodes.
2528 (defun basic-save-buffer-1 ()
2529 (let (setmodes tempsetmodes)
2530 (if (not (file-writable-p buffer-file-name))
2531 (let ((dir (file-name-directory buffer-file-name)))
2532 (if (not (file-directory-p dir))
2533 (error "%s is not a directory" dir)
2534 (if (not (file-exists-p buffer-file-name))
2535 (error "Directory %s write-protected" dir)
2537 (format "File %s is write-protected; try to save anyway? "
2538 (file-name-nondirectory
2540 (setq tempsetmodes t)
2542 "Attempt to save to a file which you aren't allowed to write"))))))
2543 (or buffer-backed-up
2544 (setq setmodes (backup-buffer)))
2545 (let ((dir (file-name-directory buffer-file-name)))
2546 (if (and file-precious-flag
2547 (file-writable-p dir))
2548 ;; If file is precious, write temp name, then rename it.
2549 ;; This requires write access to the containing dir,
2550 ;; which is why we don't try it if we don't have that access.
2551 (let ((realname buffer-file-name)
2552 tempname nogood i succeed
2553 (old-modtime (visited-file-modtime)))
2556 ;; Find the temporary name to write under.
2558 (setq tempname (format "%s#tmp#%d" dir i))
2559 (setq nogood (file-exists-p tempname))
2562 (progn (clear-visited-file-modtime)
2563 (write-region (point-min) (point-max)
2564 tempname nil realname
2565 buffer-file-truename)
2567 ;; If writing the temp file fails,
2568 ;; delete the temp file.
2571 (delete-file tempname)
2572 (set-visited-file-modtime old-modtime))))
2573 ;; Since we have created an entirely new file
2574 ;; and renamed it, make sure it gets the
2575 ;; right permission bits set.
2576 (setq setmodes (file-modes buffer-file-name))
2577 ;; We succeeded in writing the temp file,
2579 (rename-file tempname buffer-file-name t))
2580 ;; If file not writable, see if we can make it writable
2581 ;; temporarily while we write it.
2582 ;; But no need to do so if we have just backed it up
2583 ;; (setmodes is set) because that says we're superseding.
2584 (cond ((and tempsetmodes (not setmodes))
2585 ;; Change the mode back, after writing.
2586 (setq setmodes (file-modes buffer-file-name))
2587 (set-file-modes buffer-file-name 511)))
2588 (basic-write-file-data buffer-file-name buffer-file-truename)))
2589 (setq buffer-file-number
2590 (if buffer-file-name
2591 (nth 10 (file-attributes buffer-file-name))
2595 (set-file-modes buffer-file-name setmodes)
2598 ;; XEmacs change, from Sun
2599 (defun continue-save-buffer ()
2600 "Provide a clean way for a write-file-hook to wrap AROUND
2601 the execution of the remaining hooks and writing to disk.
2602 Do not call this function except from a functions
2603 on the `write-file-hooks' or `write-contents-hooks' list.
2604 A hook that calls this function must return non-nil,
2605 to signal completion to its caller. `continue-save-buffer'
2606 always returns non-nil."
2607 (let ((hooks (cdr (or continue-save-buffer-hooks-tail
2609 "continue-save-buffer called outside a write-file-hook!"))))
2611 ;; Do something like this:
2612 ;; (let ((write-file-hooks hooks)) (basic-save-buffer))
2613 ;; First run the rest of the hooks.
2615 (let ((continue-save-buffer-hooks-tail hooks))
2616 (not (setq done (funcall (car hooks))))))
2617 (setq hooks (cdr hooks)))
2619 ;; If a hook returned t, file is already "written".
2621 (basic-save-buffer-1))
2622 'continue-save-buffer))
2624 (defcustom save-some-buffers-query-display-buffer t
2625 "*Non-nil makes `\\[save-some-buffers]' switch to the buffer offered for saving."
2627 :group 'editing-basics)
2629 (defun save-some-buffers (&optional arg exiting)
2630 "Save some modified file-visiting buffers. Asks user about each one.
2631 Optional argument (the prefix) non-nil means save all with no questions.
2632 Optional second argument EXITING means ask about certain non-file buffers
2633 as well as about file buffers."
2636 ;; `delete-other-windows' can bomb during autoloads generation, so
2638 (if (or noninteractive
2639 (eq (selected-window) (minibuffer-window))
2640 (not save-some-buffers-query-display-buffer))
2641 ;; If playing with windows is unsafe or undesired, just do the
2643 (save-some-buffers-1 arg exiting nil)
2644 ;; Else, protect the windows.
2645 (when (save-window-excursion
2646 (save-some-buffers-1 arg exiting t))
2650 ;; XEmacs - do not use queried flag
2651 (defun save-some-buffers-1 (arg exiting switch-buffer)
2652 (let* ((switched nil)
2658 (and (buffer-modified-p buffer)
2659 (not (buffer-base-buffer buffer))
2661 (not (symbol-value-in-buffer 'save-buffers-skip buffer))
2663 (buffer-file-name buffer)
2667 (and buffer-offer-save (> (buffer-size) 0)))))
2670 ;; #### We should provide a per-buffer means to
2671 ;; disable the switching. For instance, you might
2672 ;; want to turn it off for buffers the contents of
2673 ;; which is meaningless to humans, such as
2675 (when (and switch-buffer
2676 ;; map-y-or-n-p is displaying help
2677 (not (eq last-buffer buffer)))
2678 (unless (one-window-p)
2679 (delete-other-windows))
2681 ;; #### Consider using `display-buffer' here for 21.1!
2682 ;;(display-buffer buffer nil (selected-frame)))
2683 (switch-to-buffer buffer t))
2684 (if (buffer-file-name buffer)
2685 (format "Save file %s? "
2686 (buffer-file-name buffer))
2687 (format "Save buffer %s? "
2688 (buffer-name buffer)))))
2689 (setq last-buffer buffer)))
2696 '("buffer" "buffers" "save")
2697 ;;instead of this we just say "yes all", "no all", etc.
2698 ;;"save all the rest"
2699 ;;"save only this buffer" "save no more buffers")
2700 ;; this is rather bogus. --ben
2701 ;; (it makes the dialog box too big, and you get an error
2702 ;; "wrong type argument: framep, nil" when you hit q after
2703 ;; choosing the option from the dialog box)
2705 ;; We should fix the dialog box rather than disabling
2707 (list (list ?\C-r (lambda (buf)
2708 ;; #### FSF has an EXIT-ACTION argument
2709 ;; to `view-buffer'.
2710 (declare-fboundp (view-buffer buf))
2711 (with-boundp 'view-exit-action
2712 (setq view-exit-action
2714 (exit-recursive-edit))))
2716 ;; Return nil to ask about BUF again.
2718 "%_Display Buffer"))))
2720 (and save-abbrevs abbrevs-changed
2723 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
2724 (write-abbrev-file nil))
2725 ;; Don't keep bothering user if he says no.
2726 (setq abbrevs-changed nil)
2728 (or (> files-done 0) abbrevs-done
2729 (display-message 'no-log "(No files need saving)"))
2733 (defun not-modified (&optional arg)
2734 "Mark current buffer as unmodified, not needing to be saved.
2735 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2737 It is not a good idea to use this function in Lisp programs, because it
2738 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2740 (if arg ;; rewritten for I18N3 snarfing
2741 (display-message 'command "Modification-flag set")
2742 (display-message 'command "Modification-flag cleared"))
2743 (set-buffer-modified-p arg))
2745 (defun toggle-read-only (&optional arg)
2746 "Toggle the current buffer's read-only status.
2747 With arg, set read-only iff arg is positive."
2749 (setq buffer-read-only
2751 (not buffer-read-only)
2752 (> (prefix-numeric-value arg) 0)))
2753 ;; Force modeline redisplay
2756 (defun insert-file (filename &optional codesys)
2757 "Insert contents of file FILENAME into buffer after point.
2758 Set mark after the inserted text.
2760 Under XEmacs/Mule, optional second argument specifies the
2761 coding system to use when decoding the file. Interactively,
2762 with a prefix argument, you will be prompted for the coding system.
2764 This function is meant for the user to run interactively.
2765 Don't call it from programs! Use `insert-file-contents' instead.
2766 \(Its calling sequence is different; see its documentation)."
2767 (interactive "*fInsert file: \nZCoding system: ")
2768 (if (file-directory-p filename)
2769 (signal 'file-error (list "Opening input file" "file is a directory"
2773 (let ((coding-system-for-read
2774 (get-coding-system codesys)))
2775 (insert-file-contents filename))
2776 (insert-file-contents filename))))
2777 (push-mark (+ (point) (car (cdr tem))))))
2779 (defun append-to-file (start end filename &optional codesys)
2780 "Append the contents of the region to the end of file FILENAME.
2781 When called from a function, expects three arguments,
2782 START, END and FILENAME. START and END are buffer positions
2783 saying what text to write.
2784 Under XEmacs/Mule, optional fourth argument specifies the
2785 coding system to use when encoding the file. Interactively,
2786 with a prefix argument, you will be prompted for the coding system."
2787 (interactive "r\nFAppend to file: \nZCoding system: ")
2789 (let ((buffer-file-coding-system (get-coding-system codesys)))
2790 (write-region start end filename t))
2791 (write-region start end filename t)))
2793 (defun file-newest-backup (filename)
2794 "Return most recent backup file for FILENAME or nil if no backups exist."
2795 (let* ((filename (expand-file-name filename))
2796 (file (file-name-nondirectory filename))
2797 (dir (file-name-directory filename))
2798 (comp (file-name-all-completions file dir))
2801 (setq file (concat dir (car comp))
2803 (if (and (backup-file-name-p file)
2804 (or (null newest) (file-newer-than-file-p file newest)))
2805 (setq newest file)))
2808 (defun rename-uniquely ()
2809 "Rename current buffer to a similar name not already taken.
2810 This function is useful for creating multiple shell process buffers
2811 or multiple mail buffers, etc."
2814 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2815 (not (and buffer-file-name
2816 (string= (buffer-name)
2817 (file-name-nondirectory
2818 buffer-file-name)))))
2819 ;; If the existing buffer name has a <NNN>,
2820 ;; which isn't part of the file name (if any),
2821 ;; then get rid of that.
2822 (substring (buffer-name) 0 (match-beginning 0))
2824 (new-buf (generate-new-buffer base-name))
2825 (name (buffer-name new-buf)))
2826 (kill-buffer new-buf)
2827 (rename-buffer name)
2828 (redraw-modeline))))
2830 (defun make-directory-path (path)
2831 "Create all the directories along path that don't exist yet."
2832 (interactive "Fdirectory path to create: ")
2833 (make-directory path t))
2835 (defun make-directory (dir &optional parents)
2836 "Create the directory DIR and any nonexistent parent dirs.
2837 Interactively, the default choice of directory to create
2838 is the current default directory for file names.
2839 That is useful when you have visited a file in a nonexistent directory.
2841 Noninteractively, the second (optional) argument PARENTS says whether
2842 to create parent directories if they don't exist."
2843 (interactive (list (let ((current-prefix-arg current-prefix-arg))
2844 (read-directory-name "Create directory: "))
2845 current-prefix-arg))
2846 (let ((handler (find-file-name-handler dir 'make-directory)))
2848 (funcall handler 'make-directory dir parents)
2850 (make-directory-internal dir)
2851 (let ((dir (directory-file-name (expand-file-name dir)))
2853 (while (not (file-exists-p dir))
2854 (setq create-list (cons dir create-list)
2855 dir (directory-file-name (file-name-directory dir))))
2857 (make-directory-internal (car create-list))
2858 (setq create-list (cdr create-list))))))))
2860 (put 'revert-buffer-function 'permanent-local t)
2861 (defvar revert-buffer-function nil
2862 "Function to use to revert this buffer, or nil to do the default.
2863 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2864 which are the arguments that `revert-buffer' received.")
2866 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2867 (defvar revert-buffer-insert-file-contents-function nil
2868 "Function to use to insert contents when reverting this buffer.
2869 Gets two args, first the nominal file name to use,
2870 and second, t if reading the auto-save file.
2871 If the current buffer contents are to be discarded, the function must do
2874 (defvar before-revert-hook nil
2875 "Normal hook for `revert-buffer' to run before reverting.
2876 If `revert-buffer-function' is used to override the normal revert
2877 mechanism, this hook is not used.")
2879 (defvar after-revert-hook nil
2880 "Normal hook for `revert-buffer' to run after reverting.
2881 Note that the hook value that it runs is the value that was in effect
2882 before reverting; that makes a difference if you have buffer-local
2885 If `revert-buffer-function' is used to override the normal revert
2886 mechanism, this hook is not used.")
2888 (defvar revert-buffer-internal-hook nil
2891 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2892 "Replace the buffer text with the text of the visited file on disk.
2893 This undoes all changes since the file was visited or saved.
2894 With a prefix argument, offer to revert from latest auto-save file, if
2895 that is more recent than the visited file.
2897 This command also refreshes certain special buffers that contain text
2898 which doesn't come from a file, but reflects some other data base
2899 instead: for example, Dired buffers and buffer-list buffers. This is
2900 implemented by having the modes set `revert-buffer-function'.
2902 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2903 to revert from the auto-save file when this is nil. Note that the
2904 sense of this argument is the reverse of the prefix argument, for the
2905 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2908 Optional second argument NOCONFIRM means don't ask for confirmation at
2911 Optional third argument PRESERVE-MODES non-nil means don't alter
2912 the buffer's modes. Otherwise, reinitialize them using `normal-mode'.
2914 If the value of `revert-buffer-function' is non-nil, it is called to
2915 do all the work for this command. Otherwise, the hooks
2916 `before-revert-hook' and `after-revert-hook' are run at the beginning
2917 and the end, and if `revert-buffer-insert-file-contents-function' is
2918 non-nil, it is called instead of rereading visited file contents.
2920 If the buffer-modified flag is nil, and we are not reverting from an
2921 auto-save file, then compare the contents of the buffer and the file.
2922 Revert only if they differ."
2924 ;; I admit it's odd to reverse the sense of the prefix argument, but
2925 ;; there is a lot of code out there which assumes that the first
2926 ;; argument should be t to avoid consulting the auto-save file, and
2927 ;; there's no straightforward way to encourage authors to notice a
2928 ;; reversal of the argument sense. So I'm just changing the user
2929 ;; interface, but leaving the programmatic interface the same.
2930 (interactive (list (not current-prefix-arg)))
2931 (if revert-buffer-function
2932 (funcall revert-buffer-function ignore-auto noconfirm)
2933 (let* ((opoint (point))
2937 (auto-save-p (and (not ignore-auto)
2938 (recent-auto-save-p)
2939 buffer-auto-save-file-name
2940 (file-readable-p buffer-auto-save-file-name)
2942 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2943 (file-name (if auto-save-p
2944 buffer-auto-save-file-name
2946 (cond ((null file-name)
2947 (error "Buffer does not seem to be associated with any file"))
2949 (and (not (buffer-modified-p))
2950 (dolist (rx revert-without-query found)
2951 (when (string-match rx file-name)
2953 ;; If we will call revert-buffer-internal, delay prompting
2954 (and (not auto-save-p)
2955 (not (buffer-modified-p))
2956 (setq delay-prompt t))
2957 (yes-or-no-p (format "Revert buffer from file %s? "
2959 (run-hooks 'before-revert-hook)
2960 (cond ((or auto-save-p
2962 ;; Do we need to do expensive reversion? Compare ...
2963 (and (setq newbuf (revert-buffer-internal
2965 ;; ... and if different, prompt
2969 (format "Revert buffer from file %s? "
2971 ;; If file was backed up but has changed since,
2972 ;; we should make another backup.
2973 (and (not auto-save-p)
2974 (not (verify-visited-file-modtime (current-buffer)))
2975 (setq buffer-backed-up nil))
2976 ;; Get rid of all undo records for this buffer.
2977 (or (eq buffer-undo-list t)
2978 (setq buffer-undo-list nil))
2979 ;; Effectively copy the after-revert-hook status,
2980 ;; since after-find-file will clobber it.
2981 (let ((global-hook (default-value 'after-revert-hook))
2982 (local-hook-p (local-variable-p 'after-revert-hook
2984 (local-hook (and (local-variable-p 'after-revert-hook
2986 after-revert-hook)))
2987 (let (buffer-read-only
2988 ;; Don't make undo records for the reversion.
2989 (buffer-undo-list t))
2990 (if revert-buffer-insert-file-contents-function
2991 (funcall revert-buffer-insert-file-contents-function
2992 file-name auto-save-p)
2993 (if (not (file-exists-p file-name))
2994 (error "File %s no longer exists!" file-name))
2995 ;; Bind buffer-file-name to nil
2996 ;; so that we don't try to lock the file.
2997 (let ((buffer-file-name nil))
3001 (insert-file-contents file-name (not auto-save-p)
3003 (goto-char (min opoint (point-max)))
3004 ;; Recompute the truename in case changes in symlinks
3005 ;; have changed the truename.
3006 ;;XEmacs: already done by insert-file-contents
3007 ;;(setq buffer-file-truename
3008 ;;(abbreviate-file-name (file-truename buffer-file-name)))
3009 (after-find-file nil nil t t preserve-modes)
3010 ;; Run after-revert-hook as it was before we reverted.
3011 (setq-default revert-buffer-internal-hook global-hook)
3014 (make-local-variable 'revert-buffer-internal-hook)
3015 (setq revert-buffer-internal-hook local-hook))
3016 (kill-local-variable 'revert-buffer-internal-hook))
3017 (run-hooks 'revert-buffer-internal-hook)))
3019 ;; The resultant buffer is identical, alter
3020 ;; modtime, update mods and exit
3021 (set-visited-file-modtime)
3022 (after-find-file nil nil t t t)
3023 ;; We preserved modes above so fixup the local
3024 ;; variables manually
3026 (hack-local-variables)
3027 (error (lwarn 'local-variables 'warning
3028 "File local-variables error: %s"
3029 (error-message-string err)))))
3033 ;; #### something like `revert-buffer-compare-with-file' is a better name
3034 ;; #### why is the argument optional?
3035 (defun revert-buffer-internal (&optional file-name)
3036 "Read contents of FILE-NAME into a buffer, and compare to current buffer.
3037 Return nil if identical, and the new buffer if different."
3039 (let* ((newbuf (get-buffer-create " *revert*"))
3043 (with-obsolete-variable '(before-change-function after-change-function)
3044 (let (buffer-read-only
3045 (buffer-undo-list t)
3046 after-change-function
3047 after-change-functions
3048 before-change-function
3049 before-change-functions)
3050 (if revert-buffer-insert-file-contents-function
3051 (funcall revert-buffer-insert-file-contents-function
3053 (if (not (file-exists-p file-name))
3054 (error "File %s no longer exists!" file-name))
3056 (insert-file-contents file-name nil nil nil t)
3057 (setq bmin (point-min)
3058 bmax (point-max))))))
3059 (if (not (and (eq bmin (point-min))
3060 (eq bmax (point-max))
3061 (eq (compare-buffer-substrings
3062 newbuf bmin bmax (current-buffer) bmin bmax) 0)))
3064 (and (kill-buffer newbuf) nil))))
3066 (defun recover-file (file)
3067 "Visit file FILE, but get contents from its last auto-save file."
3068 ;; Actually putting the file name in the minibuffer should be used
3070 ;; Not just because users often use the default.
3071 (interactive "FRecover file: ")
3072 (setq file (expand-file-name file))
3073 (let ((handler (or (find-file-name-handler file 'recover-file)
3074 (find-file-name-handler
3075 (let ((buffer-file-name file))
3076 (make-auto-save-file-name))
3079 (funcall handler 'recover-file file)
3080 (if (auto-save-file-name-p (file-name-nondirectory file))
3081 (error "%s is an auto-save file" file))
3082 (let ((file-name (let ((buffer-file-name file))
3083 (make-auto-save-file-name))))
3084 (cond ((if (file-exists-p file)
3085 (not (file-newer-than-file-p file-name file))
3086 (not (file-exists-p file-name)))
3087 (error "Auto-save file %s not current" file-name))
3088 ((save-window-excursion
3089 ;; XEmacs change: use insert-directory instead of
3090 ;; calling ls directly.
3091 (with-output-to-temp-buffer "*Directory*"
3092 (buffer-disable-undo standard-output)
3094 (set-buffer "*Directory*")
3095 (setq default-directory (file-name-directory file))
3096 (insert-directory file
3097 (if (file-symlink-p file) "-lL" "-l"))
3098 (setq default-directory (file-name-directory file-name))
3099 (insert-directory file-name "-l")))
3100 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3101 (switch-to-buffer (find-file-noselect file t))
3102 (let ((buffer-read-only nil))
3104 (insert-file-contents file-name nil))
3105 (after-find-file nil nil t))
3106 (t (error "Recover-file cancelled.")))))))
3108 (defun recover-session ()
3109 "Recover auto save files from a previous Emacs session.
3110 This command first displays a Dired buffer showing you the
3111 previous sessions that you could recover from.
3112 To choose one, move point to the proper line and then type C-c C-c.
3113 Then you'll be asked about a number of files to recover."
3115 (unless (fboundp 'dired)
3116 (error "recover-session requires dired"))
3117 (if (null auto-save-list-file-prefix)
3119 "You set `auto-save-list-file-prefix' to disable making session files"))
3120 (dired (concat auto-save-list-file-prefix "*"))
3121 (goto-char (point-min))
3122 (or (looking-at "Move to the session you want to recover,")
3123 (let ((inhibit-read-only t))
3124 (insert "Move to the session you want to recover,\n"
3125 "then type C-c C-c to select it.\n\n"
3126 "You can also delete some of these files;\n"
3127 "type d on a line to mark that file for deletion.\n\n")))
3128 (use-local-map (let ((map (make-sparse-keymap)))
3129 (set-keymap-parents map (list (current-local-map)))
3131 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
3133 (defun recover-session-finish ()
3134 "Choose one saved session to recover auto-save files from.
3135 This command is used in the special Dired buffer created by
3136 \\[recover-session]."
3138 ;; Get the name of the session file to recover from.
3139 (let ((file (declare-fboundp (dired-get-filename)))
3141 (buffer (get-buffer-create " *recover*")))
3142 ;; #### dired-do-flagged-delete in FSF.
3143 ;; This version is for ange-ftp
3144 ;;(dired-do-deletions t)
3145 ;; This version is for efs
3146 (declare-fboundp (dired-expunge-deletions))
3149 ;; Read in the auto-save-list file.
3152 (insert-file-contents file)
3153 ;; Loop thru the text of that file
3154 ;; and get out the names of the files to recover.
3156 (let (thisfile autofile)
3158 ;; This is a pair of lines for a non-file-visiting buffer.
3159 ;; Get the auto-save file name and manufacture
3160 ;; a "visited file name" from that.
3164 (buffer-substring-no-properties
3172 (file-name-nondirectory autofile)
3174 (file-name-directory autofile)))
3176 ;; This pair of lines is a file-visiting
3177 ;; buffer. Use the visited file name.
3180 (buffer-substring-no-properties
3181 (point) (progn (end-of-line) (point))))
3184 (buffer-substring-no-properties
3185 (point) (progn (end-of-line) (point))))
3187 ;; Ignore a file if its auto-save file does not exist now.
3188 (if (file-exists-p autofile)
3189 (setq files (cons thisfile files)))))
3190 (setq files (nreverse files))
3191 ;; The file contains a pair of line for each auto-saved buffer.
3192 ;; The first line of the pair contains the visited file name
3193 ;; or is empty if the buffer was not visiting a file.
3194 ;; The second line is the auto-save file name.
3196 (map-y-or-n-p "Recover %s? "
3199 (save-excursion (recover-file file))
3201 "Failed to recover `%s'" file)))
3203 '("file" "files" "recover"))
3204 (message "No files can be recovered from this session now")))
3205 (kill-buffer buffer))))
3207 (defun kill-some-buffers (&optional list)
3208 "For each buffer in LIST, ask whether to kill it.
3209 LIST defaults to all existing live buffers."
3212 (setq list (buffer-list)))
3214 (let* ((buffer (car list))
3215 (name (buffer-name buffer)))
3216 (and (not (string-equal name ""))
3217 (/= (aref name 0) ?\ )
3220 (if (buffer-modified-p buffer)
3221 (gettext "Buffer %s HAS BEEN EDITED. Kill? ")
3222 (gettext "Buffer %s is unmodified. Kill? "))
3224 (kill-buffer buffer)))
3225 (setq list (cdr list))))
3227 (defun auto-save-mode (arg)
3228 "Toggle auto-saving of contents of current buffer.
3229 With prefix argument ARG, turn auto-saving on if positive, else off."
3231 (setq buffer-auto-save-file-name
3233 (or (not buffer-auto-save-file-name)
3234 ;; If autosave is off because buffer has shrunk,
3235 ;; then toggling should turn it on.
3236 (< buffer-saved-size 0))
3237 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
3238 (if (and buffer-file-name auto-save-visited-file-name
3239 (not buffer-read-only))
3241 (make-auto-save-file-name))))
3242 ;; If -1 was stored here, to temporarily turn off saving,
3244 (and (< buffer-saved-size 0)
3245 (setq buffer-saved-size 0))
3247 (if buffer-auto-save-file-name ;; rewritten for I18N3 snarfing
3248 (display-message 'command "Auto-save on (in this buffer)")
3249 (display-message 'command "Auto-save off (in this buffer)")))
3250 buffer-auto-save-file-name)
3252 (defun rename-auto-save-file ()
3253 "Adjust current buffer's auto save file name for current conditions.
3254 Also rename any existing auto save file, if it was made in this session."
3255 (let ((osave buffer-auto-save-file-name))
3256 (setq buffer-auto-save-file-name
3257 (make-auto-save-file-name))
3258 (if (and osave buffer-auto-save-file-name
3259 (not (string= buffer-auto-save-file-name buffer-file-name))
3260 (not (string= buffer-auto-save-file-name osave))
3261 (file-exists-p osave)
3262 (recent-auto-save-p))
3263 (rename-file osave buffer-auto-save-file-name t))))
3265 ;; make-auto-save-file-name and auto-save-file-name-p are now only in
3269 (defun wildcard-to-regexp (wildcard)
3270 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
3271 The generated regexp will match a filename iff the filename
3272 matches that wildcard according to shell rules. Only wildcards known
3273 by `sh' are supported."
3274 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
3275 ;; Copy the initial run of non-special characters.
3276 (result (substring wildcard 0 i))
3277 (len (length wildcard)))
3278 ;; If no special characters, we're almost done.
3281 (let ((ch (aref wildcard i))
3287 ((eq ch ?\[) ; [...] maps to regexp char class
3292 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
3295 (if (eq (aref wildcard i) ?\])
3300 ((eq (aref wildcard i) ?^)
3301 ;; Found "[^". Insert a `\0' character
3302 ;; (which cannot happen in a filename)
3303 ;; into the character class, so that `^'
3304 ;; is not the first character after `[',
3305 ;; and thus non-special in a regexp.
3309 ((eq (aref wildcard i) ?\])
3310 ;; I don't think `]' can appear in a
3311 ;; character class in a wildcard, but
3312 ;; let's be general here.
3317 (prog1 ; copy everything upto next `]'.
3320 (setq j (string-match
3322 (setq i (if j (1- j) (1- len)))))))
3324 ((eq ch ?*) "[^\000]*")
3328 ((eq ch ?\\) #r"\\") ; probably cannot happen...
3329 ((eq ch ??) "[^\000]")
3330 (t (char-to-string ch)))))
3332 ;; Shell wildcards should match the entire filename,
3333 ;; not its part. Make the regexp say so.
3334 (concat "\\`" result "\\'")))
3336 (defcustom list-directory-brief-switches "-CF"
3337 "*Switches for list-directory to pass to `ls' for brief listing."
3341 (defcustom list-directory-verbose-switches "-l"
3342 "*Switches for list-directory to pass to `ls' for verbose listing,"
3346 ;;; Sync: XEmacs 21.5 (cb65bfaf7110 tip) 2015-07-03 --SY
3347 (defun file-expand-wildcards (pattern &optional full)
3348 "Expand wildcard pattern PATTERN.
3349 This returns a list of file names which match the pattern.
3351 If PATTERN is written as an absolute relative file name,
3352 the values are absolute also.
3354 If PATTERN is written as a relative file name, it is interpreted
3355 relative to the current default directory, `default-directory'.
3356 The file names returned are normally also relative to the current
3357 default directory. However, if FULL is non-nil, they are absolute."
3358 (let* ((nondir (file-name-nondirectory pattern))
3359 (dirpart (file-name-directory pattern))
3360 ;; A list of all dirs that DIRPART specifies.
3361 ;; This can be more than one dir
3362 ;; if DIRPART contains wildcards.
3363 (dirs (if (and dirpart (string-match "[[*?]" dirpart))
3364 (mapcar 'file-name-as-directory
3365 (file-expand-wildcards (directory-file-name dirpart)))
3369 (when (or (null (car dirs)) ; Possible if DIRPART is not wild.
3370 (file-directory-p (directory-file-name (car dirs))))
3371 (let ((this-dir-contents
3372 ;; Filter out "." and ".."
3373 (nset-difference (directory-files (or (car dirs) ".") full
3374 (wildcard-to-regexp nondir))
3375 '("." "..") :test #'equal)))
3378 (if (and (car dirs) (not full))
3379 (mapcar (function (lambda (name) (concat (car dirs) name)))
3383 (setq dirs (cdr dirs)))
3385 ;;; End Sync: XEmacs 21.5 (cb65bfaf7110 tip) 2015-07-03 --SY
3387 (defun list-directory (dirname &optional verbose)
3388 "Display a list of files in or matching DIRNAME, a la `ls'.
3389 DIRNAME is globbed by the shell if necessary.
3390 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
3391 Actions controlled by variables `list-directory-brief-switches'
3392 and `list-directory-verbose-switches'."
3393 (interactive (let ((pfx current-prefix-arg))
3394 (list (read-file-name (if pfx (gettext "List directory (verbose): ")
3395 (gettext "List directory (brief): "))
3396 nil default-directory nil)
3398 (let ((switches (if verbose list-directory-verbose-switches
3399 list-directory-brief-switches)))
3400 (or dirname (setq dirname default-directory))
3401 (setq dirname (expand-file-name dirname))
3402 (with-output-to-temp-buffer "*Directory*"
3403 (buffer-disable-undo standard-output)
3404 (princ "Directory ")
3408 (set-buffer "*Directory*")
3409 (setq default-directory (file-name-directory dirname))
3410 (let ((wildcard (not (file-directory-p dirname))))
3411 (insert-directory dirname switches wildcard (not wildcard)))))))
3413 ;;; Sync: XEmacs 21.5 (cb65bfaf7110 tip) 2015-07-03 --SY
3414 (defun shell-quote-wildcard-pattern (pattern)
3415 "Quote characters special to the shell in PATTERN, leave wildcards alone.
3417 PATTERN is assumed to represent a file-name wildcard suitable for the
3418 underlying filesystem. For Unix and GNU/Linux, the characters from the
3419 set [ \\t\\n;<>&|()#$] are quoted with a backslash; for DOS/Windows, all
3420 the parts of the pattern which don't include wildcard characters are
3421 quoted with double quotes.
3422 Existing quote characters in PATTERN are left alone, so you can pass
3423 PATTERN that already quotes some of the special characters."
3426 ((memq system-type '(ms-dos windows-nt))
3427 ;; DOS/Windows don't allow `"' in file names. So if the
3428 ;; argument has quotes, we can safely assume it is already
3429 ;; quoted by the caller.
3430 (if (or (string-match "[\"]" pattern)
3431 ;; We quote [&()#$'] in case their shell is a port of a
3432 ;; Unixy shell. We quote [,=+] because stock DOS and
3433 ;; Windows shells require that in some cases, such as
3434 ;; passing arguments to batch files that use positional
3435 ;; arguments like %1.
3436 (not (string-match "[ \t;&()#$',=+]" pattern)))
3441 (while (string-match "[*?]+" pattern beg)
3442 (setq end (match-beginning 0)
3443 result (concat result (substring pattern beg end)
3445 (substring pattern end (match-end 0))
3448 (concat result (substring pattern beg) "\""))))
3451 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
3453 (concat (substring pattern 0 (match-beginning 0))
3455 (substring pattern (match-beginning 0)))
3456 beg (1+ (match-end 0)))))
3458 ;;; End Sync: XEmacs 21.5 (cb65bfaf7110 tip) 2015-07-03 --SY
3460 (defvar insert-directory-program "ls"
3461 "Absolute or relative name of the `ls' program used by `insert-directory'.")
3464 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
3465 ;; FULL-DIRECTORY-P is nil.
3466 ;; The single line of output must display FILE's name as it was
3467 ;; given, namely, an absolute path name.
3468 ;; - must insert exactly one line for each file if WILDCARD or
3469 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
3470 ;; before the file lines, plus optional text after the file lines.
3471 ;; Lines are delimited by "\n", so filenames containing "\n" are not
3473 ;; File lines should display the basename.
3474 ;; - must be consistent with
3475 ;; - functions dired-move-to-filename, (these two define what a file line is)
3476 ;; dired-move-to-end-of-filename,
3477 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
3478 ;; dired-insert-headerline
3479 ;; dired-after-subdir-garbage (defines what a "total" line is)
3480 ;; - variable dired-subdir-regexp
3481 (defun insert-directory (file switches &optional wildcard full-directory-p)
3482 "Insert directory listing for FILE, formatted according to SWITCHES.
3483 Leaves point after the inserted text.
3484 SWITCHES may be a string of options, or a list of strings.
3485 Optional third arg WILDCARD means treat FILE as shell wildcard.
3486 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
3487 switches do not contain `d', so that a full listing is expected.
3489 This works by running a directory listing program
3490 whose name is in the variable `insert-directory-program'.
3491 If WILDCARD, it also runs the shell specified by `shell-file-name'."
3492 ;; We need the directory in order to find the right handler.
3493 (let ((handler (find-file-name-handler (expand-file-name file)
3494 'insert-directory)))
3497 (funcall handler 'insert-directory file switches
3498 wildcard full-directory-p))
3500 (let* ((beg (point))
3503 ;; Run ls in the directory of the file pattern we asked for.
3504 (let ((default-directory
3505 (if (file-name-absolute-p file)
3506 (file-name-directory file)
3507 (file-name-directory (expand-file-name file))))
3508 (pattern (file-name-nondirectory file))
3510 ;; Quote some characters that have special meanings in shells;
3511 ;; but don't quote the wildcards--we want them to be special.
3512 ;; We also currently don't quote the quoting characters
3513 ;; in case people want to use them explicitly to quote
3514 ;; wildcard characters.
3515 ;;#### Unix-specific
3516 (while (string-match "[ \t\n;<>&|()#$]" pattern start)
3518 (concat (substring pattern 0 (match-beginning 0))
3520 (substring pattern (match-beginning 0)))
3521 start (1+ (match-end 0))))
3522 (call-process shell-file-name nil t nil
3523 "-c" (concat "\\" ;; Disregard shell aliases!
3524 insert-directory-program
3526 (if (stringp switches)
3528 (mapconcat 'identity switches " "))
3531 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
3532 ;; directory if FILE is a symbolic link.
3533 (apply 'call-process
3534 insert-directory-program nil t nil
3536 (if (listp switches)
3537 (setq list switches)
3538 (if (not (equal switches ""))
3539 (let ((switches switches))
3540 ;; Split the switches at any spaces
3541 ;; so we can pass separate options as separate args.
3542 (while (string-match " " switches)
3543 (setq list (cons (substring switches 0 (match-beginning 0))
3545 switches (substring switches (match-end 0))))
3546 (setq list (cons switches list)))))
3549 (if full-directory-p
3550 (concat (file-name-as-directory file)
3551 ;;#### Unix-specific
3554 ;; If `insert-directory-program' failed, signal an error.
3556 ;; On non-Posix systems, we cannot open a directory, so
3557 ;; don't even try, because that will always result in
3558 ;; the ubiquitous "Access denied". Instead, show the
3559 ;; command line so the user can try to guess what went wrong.
3560 (error "Listing directory failed."))
3562 (when (or (and (listp switches)
3563 (member "--dired" switches))
3564 (string-match "--dired\\>" switches))
3566 (when (looking-at "//SUBDIRED//")
3567 (delete-region (point) (progn (forward-line 1) (point)))
3569 (let ((end (line-end-position)))
3572 (while (< (point) end)
3573 (let ((start (+ beg (read (current-buffer))))
3574 (end (+ beg (read (current-buffer)))))
3575 (if (= (char-after end) ?\n)
3576 (let ((filename-extent (make-extent start end)))
3577 (set-extent-property filename-extent 'dired-file-name t)
3578 (set-extent-property filename-extent 'start-open t)
3579 (set-extent-property filename-extent 'end-open t))
3580 ;; It seems that we can't trust ls's output as to
3581 ;; byte positions of filenames.
3583 #'(lambda (extent maparg)
3584 (delete-extent extent)
3586 nil beg (point) nil nil 'dired-file-name)
3590 (delete-region (point) (progn (forward-line 2) (point))))))))))
3592 (defvar kill-emacs-query-functions nil
3593 "Functions to call with no arguments to query about killing XEmacs.
3594 If any of these functions returns nil, killing Emacs is cancelled.
3595 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
3596 but `kill-emacs', the low level primitive, does not.
3597 See also `kill-emacs-hook'.")
3599 (defun save-buffers-kill-emacs (&optional arg)
3600 "Offer to save each buffer, then kill this XEmacs process.
3601 With prefix arg, silently save all file-visiting buffers, then kill."
3603 (save-some-buffers arg t)
3604 (and (or (not (memq t (mapcar #'(lambda (buf) (and (buffer-file-name buf)
3605 (buffer-modified-p buf)))
3607 (yes-or-no-p "Modified buffers exist; exit anyway? "))
3608 (or (not (fboundp 'process-list))
3609 ;; process-list is not defined on VMS.
3610 (let ((processes (process-list))
3613 (and (memq (process-status (car processes)) '(run stop open))
3614 (let ((val (process-kill-without-query (car processes))))
3615 (process-kill-without-query (car processes) val)
3618 (setq processes (cdr processes)))
3622 (save-window-excursion
3623 (delete-other-windows)
3626 "Active processes exist; kill them and exit anyway? "))))))
3627 ;; Query the user for other things, perhaps.
3628 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
3631 (defun symlink-expand-file-name (filename)
3632 "If FILENAME is a symlink, return its non-symlink equivalent.
3633 Unlike `file-truename', this doesn't chase symlinks in directory
3634 components of the file or expand a relative pathname into an
3637 (while (and (> count 0) (file-symlink-p filename))
3638 (setq filename (file-symlink-p filename)
3642 (error "Apparently circular symlink path"))))
3644 ;; Suggested by Michael Kifer <kifer@CS.SunySB.EDU>
3645 (defun file-remote-p (file-name)
3646 "Test whether FILE-NAME is looked for on a remote system."
3647 (cond ((not (declare-boundp allow-remote-paths)) nil)
3648 ((fboundp 'ange-ftp-ftp-path)
3649 (declare-fboundp (ange-ftp-ftp-path file-name)))
3650 ((fboundp 'efs-ftp-path)
3651 (declare-fboundp (efs-ftp-path file-name)))
3654 ;; #### FSF has file-name-non-special here.
3656 ;;; files.el ends here