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