1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985, 86, 87, 92, 93,
4 ;; 94, 95, 96, 97, 98, 99, 2000 Free Software Foundation, Inc.
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; Defines most of Emacs's file- and directory-handling functions,
28 ;; including basic file visiting, backup generation, link handling,
29 ;; ITS-id version control, load- and write-hook handling, and the like.
34 "Backups of edited data files."
37 (defgroup find-file nil
42 (defcustom delete-auto-save-files t
43 "*Non-nil means delete auto-save file when a buffer is saved or killed.
45 Note that auto-save file will not be deleted if the buffer is killed
46 when it has unsaved changes."
50 (defcustom directory-abbrev-alist
52 "*Alist of abbreviations for file directories.
53 A list of elements of the form (FROM . TO), each meaning to replace
54 FROM with TO when it appears in a directory name. This replacement is
55 done when setting up the default directory of a newly visited file.
56 *Every* FROM string should start with `^'.
58 Do not use `~' in the TO strings.
59 They should be ordinary absolute directory names.
61 Use this feature when you have directories which you normally refer to
62 via absolute symbolic links. Make TO the name of the link, and FROM
63 the name it is linked to."
64 :type '(repeat (cons :format "%v"
71 ;;; Turn off backup files on VMS since it has version numbers.
72 (defcustom make-backup-files (not (eq system-type 'vax-vms))
73 "*Non-nil means make a backup of a file the first time it is saved.
74 This can be done by renaming the file or by copying.
76 Renaming means that Emacs renames the existing file so that it is a
77 backup file, then writes the buffer into a new file. Any other names
78 that the old file had will now refer to the backup file. The new file
79 is owned by you and its group is defaulted.
81 Copying means that Emacs copies the existing file into the backup
82 file, then writes the buffer on top of the existing file. Any other
83 names that the old file had will now refer to the new (edited) file.
84 The file's owner and group are unchanged.
86 The choice of renaming or copying is controlled by the variables
87 `backup-by-copying', `backup-by-copying-when-linked',
88 `backup-by-copying-when-mismatch' and
89 `backup-by-copying-when-privileged-mismatch'. See also `backup-inhibited'."
93 ;; Do this so that local variables based on the file name
94 ;; are not overridden by the major mode.
95 (defvar backup-inhibited nil
96 "Non-nil means don't make a backup, regardless of the other parameters.
97 This variable is intended for use by making it local to a buffer.
98 But it is local only if you make it local.")
99 (put 'backup-inhibited 'permanent-local t)
101 (defcustom backup-by-copying nil
102 "*Non-nil means always use copying to create backup files.
103 See documentation of variable `make-backup-files'."
107 (defcustom backup-by-copying-when-linked nil
108 "*Non-nil means use copying to create backups for files with multiple names.
109 This causes the alternate names to refer to the latest version as edited.
110 This variable is relevant only if `backup-by-copying' is nil."
114 (defcustom backup-by-copying-when-mismatch nil
115 "*Non-nil means create backups by copying if this preserves owner or group.
116 Renaming may still be used (subject to control of other variables)
117 when it would not result in changing the owner or group of the file;
118 that is, for files which are owned by you and whose group matches
119 the default for a new file created there by you.
120 This variable is relevant only if `backup-by-copying' is nil."
124 (defcustom backup-by-copying-when-privileged-mismatch 200
125 "*Non-nil means create backups by copying to preserve a privileged owner.
126 Renaming may still be used (subject to control of other variables)
127 when it would not result in changing the owner of the file or if the owner
128 has a user id greater than the value of this variable. This is useful
129 when low-numbered uid's are used for special system users (such as root)
130 that must maintain ownership of certain files.
131 This variable is relevant only if `backup-by-copying' and
132 `backup-by-copying-when-mismatch' are nil."
133 :type '(choice (const nil) integer)
136 (defvar backup-enable-predicate
138 (and (let ((comp (compare-strings temporary-file-directory 0 nil
140 (and (not (eq comp t))
142 (if small-temporary-file-directory
143 (let ((comp (compare-strings small-temporary-file-directory 0 nil
145 (and (not (eq comp t))
148 "Predicate that looks at a file name and decides whether to make backups.
149 Called with an absolute file name as argument, it returns t to enable backup.
150 The default version checks for files in `temporary-file-directory' or
151 `small-temporary-file-directory'.")
153 (defcustom buffer-offer-save nil
154 "*Non-nil in a buffer means always offer to save buffer on exit.
155 Do so even if the buffer is not visiting a file.
156 Automatically local in all buffers."
159 (make-variable-buffer-local 'buffer-offer-save)
161 (defcustom find-file-existing-other-name t
162 "*Non-nil means find a file under alternative names, in existing buffers.
163 This means if any existing buffer is visiting the file you want
164 under another name, you get the existing buffer instead of a new buffer."
168 (defcustom find-file-visit-truename nil
169 "*Non-nil means visit a file under its truename.
170 The truename of a file is found by chasing all links
171 both at the file level and at the levels of the containing directories."
175 (defcustom revert-without-query
177 "*Specify which files should be reverted without query.
178 The value is a list of regular expressions.
179 If the file name matches one of these regular expressions,
180 then `revert-buffer' reverts the file without querying
181 if the file has changed on disk and you have not edited the buffer."
182 :type '(repeat regexp)
185 (defvar buffer-file-number nil
186 "The device number and file number of the file visited in the current buffer.
187 The value is a list of the form (FILENUM DEVNUM).
188 This pair of numbers uniquely identifies the file.
189 If the buffer is visiting a new file, the value is nil.")
190 (make-variable-buffer-local 'buffer-file-number)
191 (put 'buffer-file-number 'permanent-local t)
193 (defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
194 "Non-nil means that buffer-file-number uniquely identifies files.")
196 (defvar file-name-invalid-regexp
197 (cond ((and (eq system-type 'ms-dos) (not (msdos-long-file-names)))
198 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
199 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
200 "[\000-\031]\\|" ; control characters
201 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
202 "\\(/[^/.]+\\.[^/.]*\\.\\)")) ; more than a single dot
203 ((memq system-type '(ms-dos windows-nt))
204 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
205 "[|<>\"?*\000-\031]")) ; invalid characters
207 "Regexp recognizing file names which aren't allowed by the filesystem.")
209 (defcustom file-precious-flag nil
210 "*Non-nil means protect against I/O errors while saving files.
211 Some modes set this non-nil in particular buffers.
213 This feature works by writing the new contents into a temporary file
214 and then renaming the temporary file to replace the original.
215 In this way, any I/O error in writing leaves the original untouched,
216 and there is never any instant where the file is nonexistent.
218 Note that this feature forces backups to be made by copying.
219 Yet, at the same time, saving a precious file
220 breaks any hard links between it and other files."
224 (defcustom version-control nil
225 "*Control use of version numbers for backup files.
226 t means make numeric backup versions unconditionally.
227 nil means make them for files that have some already.
228 `never' means do not make them."
229 :type '(choice (const :tag "Never" never)
230 (const :tag "If existing" nil)
231 (other :tag "Always" t))
235 (defcustom dired-kept-versions 2
236 "*When cleaning directory, number of versions to keep."
241 (defcustom delete-old-versions nil
242 "*If t, delete excess backup versions silently.
243 If nil, ask confirmation. Any other value prevents any trimming."
244 :type '(choice (const :tag "Delete" t)
245 (const :tag "Ask" nil)
246 (other :tag "Leave" other))
249 (defcustom kept-old-versions 2
250 "*Number of oldest versions to keep when a new numbered backup is made."
254 (defcustom kept-new-versions 2
255 "*Number of newest versions to keep when a new numbered backup is made.
256 Includes the new backup. Must be > 0"
260 (defcustom require-final-newline nil
261 "*Value of t says silently ensure a file ends in a newline when it is saved.
262 Non-nil but not t says ask user whether to add a newline when there isn't one.
263 nil means don't add newlines."
264 :type '(choice (const :tag "Off" nil)
266 (other :tag "Ask" ask))
267 :group 'editing-basics)
269 (defcustom auto-save-default t
270 "*Non-nil says by default do auto-saving of every file-visiting buffer."
274 (defcustom auto-save-visited-file-name nil
275 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
276 Normally auto-save files are written under other names."
280 (defcustom save-abbrevs nil
281 "*Non-nil means save word abbrevs too when files are saved.
282 Loading an abbrev file sets this to t."
286 (defcustom find-file-run-dired t
287 "*Non-nil means allow `find-file' to visit directories.
288 To visit the directory, `find-file' runs `find-directory-functions'."
292 (defcustom find-directory-functions '(cvs-dired-noselect dired-noselect)
293 "*List of functions to try in sequence to visit a directory.
294 Each function is called with the directory name as the sole argument
295 and should return either a buffer or nil."
296 :type '(hook :options (cvs-dired-noselect dired-noselect))
299 ;;;It is not useful to make this a local variable.
300 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
301 (defvar find-file-not-found-hooks nil
302 "List of functions to be called for `find-file' on nonexistent file.
303 These functions are called as soon as the error is detected.
304 Variable `buffer-file-name' is already set up.
305 The functions are called in the order given until one of them returns non-nil.")
307 ;;;It is not useful to make this a local variable.
308 ;;;(put 'find-file-hooks 'permanent-local t)
309 (defvar find-file-hooks nil
310 "List of functions to be called after a buffer is loaded from a file.
311 The buffer's local variables (if any) will have been processed before the
312 functions are called.")
314 (defvar write-file-hooks nil
315 "List of functions to be called before writing out a buffer to a file.
316 If one of them returns non-nil, the file is considered already written
317 and the rest are not called.
318 These hooks are considered to pertain to the visited file.
319 So any buffer-local binding of `write-file-hooks' is
320 discarded if you change the visited file name with \\[set-visited-file-name].
322 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.
323 See also `write-contents-hooks'.")
324 ;;; However, in case someone does make it local...
325 (put 'write-file-hooks 'permanent-local t)
327 (defvar local-write-file-hooks nil
328 "Just like `write-file-hooks', except intended for per-buffer use.
329 The functions in this list are called before the ones in
332 This variable is meant to be used for hooks that have to do with a
333 particular visited file. Therefore, it is a permanent local, so that
334 changing the major mode does not clear it. However, calling
335 `set-visited-file-name' does clear it.")
336 (make-variable-buffer-local 'local-write-file-hooks)
337 (put 'local-write-file-hooks 'permanent-local t)
339 (defvar write-contents-hooks nil
340 "List of functions to be called before writing out a buffer to a file.
341 If one of them returns non-nil, the file is considered already written
342 and the rest are not called.
344 This variable is meant to be used for hooks that pertain to the
345 buffer's contents, not to the particular visited file; thus,
346 `set-visited-file-name' does not clear this variable; but changing the
347 major mode does clear it.
349 This variable automatically becomes buffer-local whenever it is set.
350 If you use `add-hook' to add elements to the list, use nil for the
353 See also `write-file-hooks'.")
354 (make-variable-buffer-local 'write-contents-hooks)
356 (defcustom enable-local-variables t
357 "*Control use of local variables in files you visit.
358 The value can be t, nil or something else.
359 A value of t means file local variables specifications are obeyed;
360 nil means they are ignored; anything else means query.
361 This variable also controls use of major modes specified in
364 The command \\[normal-mode], when used interactively,
365 always obeys file local variable specifications and the -*- line,
366 and ignores this variable."
367 :type '(choice (const :tag "Obey" t)
368 (const :tag "Ignore" nil)
369 (other :tag "Query" other))
372 (defvar local-enable-local-variables t
373 "Like `enable-local-variables' but meant for buffer-local bindings.
374 The meaningful values are nil and non-nil. The default is non-nil.
375 If a major mode sets this to nil, buffer-locally, then any local
376 variables list in the file will be ignored.
378 This variable does not affect the use of major modes
379 specified in a -*- line.")
381 (defcustom enable-local-eval 'maybe
382 "*Control processing of the \"variable\" `eval' in a file's local variables.
383 The value can be t, nil or something else.
384 A value of t means obey `eval' variables;
385 nil means ignore them; anything else means query.
387 The command \\[normal-mode] always obeys local-variables lists
388 and ignores this variable."
389 :type '(choice (const :tag "Obey" t)
390 (const :tag "Ignore" nil)
391 (other :tag "Query" other))
394 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
395 (or (fboundp 'lock-buffer)
396 (defalias 'lock-buffer 'ignore))
397 (or (fboundp 'unlock-buffer)
398 (defalias 'unlock-buffer 'ignore))
399 (or (fboundp 'file-locked-p)
400 (defalias 'file-locked-p 'ignore))
402 (defvar view-read-only nil
403 "*Non-nil means buffers visiting files read-only, do it in view mode.")
405 (defvar temporary-file-directory
406 (file-name-as-directory
407 (cond ((memq system-type '(ms-dos windows-nt))
408 (or (getenv "TEMP") (getenv "TMPDIR") (getenv "TMP") "c:/temp"))
409 ((memq system-type '(vax-vms axp-vms))
410 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "SYS$SCRATCH:"))
412 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "/tmp"))))
413 "The directory for writing temporary files.")
415 (defvar small-temporary-file-directory
416 (if (eq system-type 'ms-dos) (getenv "TMPDIR"))
417 "The directory for writing small temporary files.
418 If non-nil, this directory is used instead of `temporary-file-directory'
419 by programs that create small temporary files. This is for systems that
420 have fast storage with limited space, such as a RAM disk.")
422 ;; The system null device. (Should reference NULL_DEVICE from C.)
423 (defvar null-device "/dev/null" "The system null device.")
425 (defun ange-ftp-completion-hook-function (op &rest args)
426 "Provides support for ange-ftp host name completion.
427 Runs the usual ange-ftp hook, but only for completion operations."
428 ;; Having this here avoids the need to load ange-ftp when it's not
430 (if (memq op '(file-name-completion file-name-all-completions))
431 (apply 'ange-ftp-hook-function op args)
432 (let ((inhibit-file-name-handlers
433 (cons 'ange-ftp-completion-hook-function
434 (and (eq inhibit-file-name-operation op)
435 inhibit-file-name-handlers)))
436 (inhibit-file-name-operation op))
439 (defun convert-standard-filename (filename)
440 "Convert a standard file's name to something suitable for the current OS.
441 This function's standard definition is trivial; it just returns the argument.
442 However, on some systems, the function is redefined
443 with a definition that really does change some file names."
447 "Show the current default directory."
449 (message "Directory %s" default-directory))
452 "Value of the CDPATH environment variable, as a list.
453 Not actually set up until the first time you you use it.")
455 (defun parse-colon-path (cd-path)
456 "Explode a colon-separated search path into a list of directory names."
458 (let (cd-prefix cd-list (cd-start 0) cd-colon)
459 (setq cd-path (concat cd-path path-separator))
460 (while (setq cd-colon (string-match path-separator cd-path cd-start))
463 (list (if (= cd-start cd-colon)
465 (substitute-in-file-name
466 (file-name-as-directory
467 (substring cd-path cd-start cd-colon)))))))
468 (setq cd-start (+ cd-colon 1)))
471 (defun cd-absolute (dir)
472 "Change current directory to given absolute file name DIR."
473 ;; Put the name into directory syntax now,
474 ;; because otherwise expand-file-name may give some bad results.
475 (if (not (eq system-type 'vax-vms))
476 (setq dir (file-name-as-directory dir)))
477 (setq dir (abbreviate-file-name (expand-file-name dir)))
478 (if (not (file-directory-p dir))
479 (if (file-exists-p dir)
480 (error "%s is not a directory" dir)
481 (error "%s: no such directory" dir))
482 (if (file-executable-p dir)
483 (setq default-directory dir)
484 (error "Cannot cd to %s: Permission denied" dir))))
487 "Make DIR become the current buffer's default directory.
488 If your environment includes a `CDPATH' variable, try each one of that
489 colon-separated list of directories when resolving a relative directory name."
491 (list (read-file-name "Change default directory: "
492 default-directory default-directory
493 (and (member cd-path '(nil ("./")))
494 (null (getenv "CDPATH"))))))
495 (if (file-name-absolute-p dir)
496 (cd-absolute (expand-file-name dir))
498 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
499 (setq cd-path (or trypath (list "./")))))
500 (if (not (catch 'found
502 (function (lambda (x)
503 (let ((f (expand-file-name (concat x dir))))
504 (if (file-directory-p f)
507 (throw 'found t))))))
510 (error "No such directory found via CDPATH environment variable"))))
512 (defun load-file (file)
513 "Load the Lisp file named FILE."
514 (interactive "fLoad file: ")
515 (let ((completion-ignored-extensions
516 (delete ".elc" completion-ignored-extensions)))
517 (load (expand-file-name file) nil nil t)))
519 (defun load-library (library)
520 "Load the library named LIBRARY.
521 This is an interface to the function `load'."
522 (interactive "sLoad library: ")
525 (defun file-local-copy (file)
526 "Copy the file FILE into a temporary file on this machine.
527 Returns the name of the local copy, or nil, if FILE is directly
529 ;; This formerly had an optional BUFFER argument that wasn't used by
531 (let ((handler (find-file-name-handler file 'file-local-copy)))
533 (funcall handler 'file-local-copy file)
536 (defun file-truename (filename &optional counter prev-dirs)
537 "Return the truename of FILENAME, which should be absolute.
538 The truename of a file name is found by chasing symbolic links
539 both at the level of the file and at the level of the directories
540 containing it, until no links are left at any level.
542 The arguments COUNTER and PREV-DIRS are used only in recursive calls.
543 Do not specify them in other calls."
544 ;; COUNTER can be a cons cell whose car is the count of how many more links
545 ;; to chase before getting an error.
546 ;; PREV-DIRS can be a cons cell whose car is an alist
547 ;; of truenames we've just recently computed.
549 ;; The last test looks dubious, maybe `+' is meant here? --simon.
550 (if (or (string= filename "") (string= filename "~")
551 (and (string= (substring filename 0 1) "~")
552 (string-match "~[^/]*" filename)))
554 (setq filename (expand-file-name filename))
555 (if (string= filename "")
556 (setq filename "/"))))
557 (or counter (setq counter (list 100)))
559 ;; For speed, remove the ange-ftp completion handler from the list.
560 ;; We know it's not needed here.
561 ;; For even more speed, do this only on the outermost call.
562 (file-name-handler-alist
563 (if prev-dirs file-name-handler-alist
564 (let ((tem (copy-sequence file-name-handler-alist)))
565 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
566 (or prev-dirs (setq prev-dirs (list nil)))
568 ;; andrewi@harlequin.co.uk - none of the following code (except for
569 ;; invoking the file-name handler) currently applies on Windows
570 ;; (ie. there are no native symlinks), but there is an issue with
571 ;; case differences being ignored by the OS, and short "8.3 DOS"
572 ;; name aliases existing for all files. (The short names are not
573 ;; reported by directory-files, but can be used to refer to files.)
574 ;; It seems appropriate for file-truename to resolve these issues in
575 ;; the most natural way, which on Windows is to call the function
576 ;; `w32-long-file-name' - this returns the exact name of a file as
577 ;; it is stored on disk (expanding short name aliases with the full
578 ;; name in the process).
579 (if (eq system-type 'windows-nt)
580 (let ((handler (find-file-name-handler filename 'file-truename))
582 ;; For file name that has a special handler, call handler.
583 ;; This is so that ange-ftp can save time by doing a no-op.
585 (setq filename (funcall handler 'file-truename filename))
586 ;; If filename contains a wildcard, newname will be the old name.
587 (if (string-match "[[*?]" filename)
588 (setq newname filename)
589 ;; If filename doesn't exist, newname will be nil.
590 (setq newname (w32-long-file-name filename)))
591 (setq filename (or newname filename)))
594 ;; If this file directly leads to a link, process that iteratively
595 ;; so that we don't use lots of stack.
597 (setcar counter (1- (car counter)))
598 (if (< (car counter) 0)
599 (error "Apparent cycle of symbolic links for %s" filename))
600 (let ((handler (find-file-name-handler filename 'file-truename)))
601 ;; For file name that has a special handler, call handler.
602 ;; This is so that ange-ftp can save time by doing a no-op.
604 (setq filename (funcall handler 'file-truename filename)
606 (let ((dir (or (file-name-directory filename) default-directory))
608 ;; Get the truename of the directory.
609 (setq dirfile (directory-file-name dir))
610 ;; If these are equal, we have the (or a) root directory.
611 (or (string= dir dirfile)
612 ;; If this is the same dir we last got the truename for,
613 ;; save time--don't recalculate.
614 (if (assoc dir (car prev-dirs))
615 (setq dir (cdr (assoc dir (car prev-dirs))))
617 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
618 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
620 (if (equal ".." (file-name-nondirectory filename))
622 (directory-file-name (file-name-directory (directory-file-name dir)))
624 (if (equal "." (file-name-nondirectory filename))
625 (setq filename (directory-file-name dir)
627 ;; Put it back on the file name.
628 (setq filename (concat dir (file-name-nondirectory filename)))
629 ;; Is the file name the name of a link?
630 (setq target (file-symlink-p filename))
632 ;; Yes => chase that link, then start all over
633 ;; since the link may point to a directory name that uses links.
634 ;; We can't safely use expand-file-name here
635 ;; since target might look like foo/../bar where foo
636 ;; is itself a link. Instead, we handle . and .. above.
638 (if (file-name-absolute-p target)
646 (defun file-chase-links (filename)
647 "Chase links in FILENAME until a name that is not a link.
648 Does not examine containing directories for links,
649 unlike `file-truename'."
650 (let (tem (count 100) (newname filename))
651 (while (setq tem (file-symlink-p newname))
654 (error "Apparent cycle of symbolic links for %s" filename))
655 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
656 (while (string-match "//+" tem)
657 (setq tem (replace-match "/" nil nil tem)))
658 ;; Handle `..' by hand, since it needs to work in the
659 ;; target of any directory symlink.
660 ;; This code is not quite complete; it does not handle
661 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
662 (while (string-match "\\`\\.\\./" tem)
663 (setq tem (substring tem 3))
664 (setq newname (expand-file-name newname))
665 ;; Chase links in the default dir of the symlink.
668 (directory-file-name (file-name-directory newname))))
669 ;; Now find the parent of that dir.
670 (setq newname (file-name-directory newname)))
671 (setq newname (expand-file-name tem (file-name-directory newname)))
672 (setq count (1- count))))
675 (defun switch-to-buffer-other-window (buffer &optional norecord)
676 "Select buffer BUFFER in another window.
677 Optional second arg NORECORD non-nil means
678 do not put this buffer at the front of the list of recently selected ones."
679 (interactive "BSwitch to buffer in other window: ")
680 (let ((pop-up-windows t))
681 (pop-to-buffer buffer t norecord)))
683 (defun switch-to-buffer-other-frame (buffer &optional norecord)
684 "Switch to buffer BUFFER in another frame.
685 Optional second arg NORECORD non-nil means
686 do not put this buffer at the front of the list of recently selected ones."
687 (interactive "BSwitch to buffer in other frame: ")
688 (let ((pop-up-frames t))
689 (pop-to-buffer buffer t norecord)
690 (raise-frame (window-frame (selected-window)))))
692 (defun find-file (filename &optional wildcards)
694 Switch to a buffer visiting file FILENAME,
695 creating one if none already exists.
696 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
697 expand wildcards (if any) and visit multiple files. Wildcard expansion
698 can be suppressed by setting `find-file-wildcards'."
699 (interactive "FFind file: \np")
700 (let ((value (find-file-noselect filename nil nil wildcards)))
702 (mapcar 'switch-to-buffer (nreverse value))
703 (switch-to-buffer value))))
705 (defun find-file-other-window (filename &optional wildcards)
706 "Edit file FILENAME, in another window.
707 May create a new window, or reuse an existing one.
708 See the function `display-buffer'.
709 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
710 expand wildcards (if any) and visit multiple files."
711 (interactive "FFind file in other window: \np")
712 (let ((value (find-file-noselect filename nil nil wildcards)))
715 (setq value (nreverse value))
716 (switch-to-buffer-other-window (car value))
717 (mapcar 'switch-to-buffer (cdr value)))
718 (switch-to-buffer-other-window value))))
720 (defun find-file-other-frame (filename &optional wildcards)
721 "Edit file FILENAME, in another frame.
722 May create a new frame, or reuse an existing one.
723 See the function `display-buffer'.
724 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
725 expand wildcards (if any) and visit multiple files."
726 (interactive "FFind file in other frame: \np")
727 (let ((value (find-file-noselect filename nil nil wildcards)))
730 (setq value (nreverse value))
731 (switch-to-buffer-other-frame (car value))
732 (mapcar 'switch-to-buffer (cdr value)))
733 (switch-to-buffer-other-frame value))))
735 (defun find-file-read-only (filename &optional wildcards)
736 "Edit file FILENAME but don't allow changes.
737 Like `find-file' but marks buffer as read-only.
738 Use \\[toggle-read-only] to permit editing."
739 (interactive "fFind file read-only: \np")
740 (find-file filename wildcards)
744 (defun find-file-read-only-other-window (filename &optional wildcards)
745 "Edit file FILENAME in another window but don't allow changes.
746 Like \\[find-file-other-window] but marks buffer as read-only.
747 Use \\[toggle-read-only] to permit editing."
748 (interactive "fFind file read-only other window: \np")
749 (find-file-other-window filename wildcards)
753 (defun find-file-read-only-other-frame (filename &optional wildcards)
754 "Edit file FILENAME in another frame but don't allow changes.
755 Like \\[find-file-other-frame] but marks buffer as read-only.
756 Use \\[toggle-read-only] to permit editing."
757 (interactive "fFind file read-only other frame: \np")
758 (find-file-other-frame filename wildcards)
762 (defun find-alternate-file-other-window (filename)
763 "Find file FILENAME as a replacement for the file in the next window.
764 This command does not select that window."
766 (save-selected-window
768 (let ((file buffer-file-name)
772 (setq file-name (file-name-nondirectory file)
773 file-dir (file-name-directory file)))
774 (list (read-file-name
775 "Find alternate file: " file-dir nil nil file-name)))))
777 (find-file-other-window filename)
778 (save-selected-window
780 (find-alternate-file filename))))
782 (defun find-alternate-file (filename)
783 "Find file FILENAME, select its buffer, kill previous buffer.
784 If the current buffer now contains an empty file that you just visited
785 \(presumably by mistake), use this command to visit the file you really want."
787 (let ((file buffer-file-name)
791 (setq file-name (file-name-nondirectory file)
792 file-dir (file-name-directory file)))
793 (list (read-file-name
794 "Find alternate file: " file-dir nil nil file-name))))
795 (and (buffer-modified-p) (buffer-file-name)
796 ;; (not buffer-read-only)
797 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
800 (let ((obuf (current-buffer))
801 (ofile buffer-file-name)
802 (onum buffer-file-number)
803 (otrue buffer-file-truename)
804 (oname (buffer-name)))
805 (if (get-buffer " **lose**")
806 (kill-buffer " **lose**"))
807 (rename-buffer " **lose**")
811 (setq buffer-file-name nil)
812 (setq buffer-file-number nil)
813 (setq buffer-file-truename nil)
814 (find-file filename))
815 (cond ((eq obuf (current-buffer))
816 (setq buffer-file-name ofile)
817 (setq buffer-file-number onum)
818 (setq buffer-file-truename otrue)
820 (rename-buffer oname))))
821 (or (eq (current-buffer) obuf)
822 (kill-buffer obuf))))
824 (defun create-file-buffer (filename)
825 "Create a suitably named buffer for visiting FILENAME, and return it.
826 FILENAME (sans directory) is used unchanged if that name is free;
827 otherwise a string <2> or <3> or ... is appended to get an unused name."
828 (let ((lastname (file-name-nondirectory filename)))
829 (if (string= lastname "")
830 (setq lastname filename))
831 (generate-new-buffer lastname)))
833 (defun generate-new-buffer (name)
834 "Create and return a buffer with a name based on NAME.
835 Choose the buffer's name using `generate-new-buffer-name'."
836 (get-buffer-create (generate-new-buffer-name name)))
838 (defcustom automount-dir-prefix "^/tmp_mnt/"
839 "Regexp to match the automounter prefix in a directory name."
843 (defvar abbreviated-home-dir nil
844 "The user's homedir abbreviated according to `directory-abbrev-alist'.")
846 (defun abbreviate-file-name (filename)
847 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
848 This also substitutes \"~\" for the user's home directory.
849 Type \\[describe-variable] directory-abbrev-alist RET for more information."
850 ;; Get rid of the prefixes added by the automounter.
851 (if (and automount-dir-prefix
852 (string-match automount-dir-prefix filename)
853 (file-exists-p (file-name-directory
854 (substring filename (1- (match-end 0))))))
855 (setq filename (substring filename (1- (match-end 0)))))
856 (let ((tail directory-abbrev-alist))
857 ;; If any elt of directory-abbrev-alist matches this name,
858 ;; abbreviate accordingly.
860 (if (string-match (car (car tail)) filename)
862 (concat (cdr (car tail)) (substring filename (match-end 0)))))
863 (setq tail (cdr tail)))
864 ;; Compute and save the abbreviated homedir name.
865 ;; We defer computing this until the first time it's needed, to
866 ;; give time for directory-abbrev-alist to be set properly.
867 ;; We include a slash at the end, to avoid spurious matches
868 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
869 (or abbreviated-home-dir
870 (setq abbreviated-home-dir
871 (let ((abbreviated-home-dir "$foo"))
872 (concat "^" (abbreviate-file-name (expand-file-name "~"))
875 ;; If FILENAME starts with the abbreviated homedir,
876 ;; make it start with `~' instead.
877 (if (and (string-match abbreviated-home-dir filename)
878 ;; If the home dir is just /, don't change it.
879 (not (and (= (match-end 0) 1)
880 (= (aref filename 0) ?/)))
881 ;; MS-DOS root directories can come with a drive letter;
882 ;; Novell Netware allows drive letters beyond `Z:'.
883 (not (and (or (eq system-type 'ms-dos)
884 (eq system-type 'windows-nt))
886 (string-match "^[a-zA-`]:/$" filename)))))
889 (substring filename (match-beginning 1) (match-end 1))
890 (substring filename (match-end 0)))))
893 (defcustom find-file-not-true-dirname-list nil
894 "*List of logical names for which visiting shouldn't save the true dirname.
895 On VMS, when you visit a file using a logical name that searches a path,
896 you may or may not want the visited file name to record the specific
897 directory where the file was found. If you *do not* want that, add the logical
898 name to this list as a string."
899 :type '(repeat (string :tag "Name"))
902 (defun find-buffer-visiting (filename)
903 "Return the buffer visiting file FILENAME (a string).
904 This is like `get-file-buffer', except that it checks for any buffer
905 visiting the same file, possibly under a different name.
906 If there is no such live buffer, return nil."
907 (let ((buf (get-file-buffer filename))
908 (truename (abbreviate-file-name (file-truename filename))))
910 (let ((list (buffer-list)) found)
911 (while (and (not found) list)
913 (set-buffer (car list))
914 (if (and buffer-file-name
915 (string= buffer-file-truename truename))
916 (setq found (car list))))
917 (setq list (cdr list)))
919 (let ((number (nthcdr 10 (file-attributes truename)))
920 (list (buffer-list)) found)
921 (and buffer-file-numbers-unique
923 (while (and (not found) list)
925 (set-buffer (car list))
926 (if (and buffer-file-name
927 (equal buffer-file-number number)
928 ;; Verify this buffer's file number
929 ;; still belongs to its file.
930 (file-exists-p buffer-file-name)
931 (equal (nthcdr 10 (file-attributes buffer-file-name))
933 (setq found (car list))))
934 (setq list (cdr list))))
937 (defcustom find-file-wildcards t
938 "*Non-nil means file-visiting commands should handle wildcards.
939 For example, if you specify `*.c', that would visit all the files
940 whose names match the pattern."
945 (defun find-file-noselect (filename &optional nowarn rawfile wildcards)
946 "Read file FILENAME into a buffer and return the buffer.
947 If a buffer exists visiting FILENAME, return that one, but
948 verify that the file has not changed since visited or saved.
949 The buffer is not selected, just returned to the caller.
950 Optional first arg NOWARN non-nil means suppress any warning messages.
951 Optional second arg RAWFILE non-nil means the file is read literally.
952 Optional third arg WILDCARDS non-nil means do wildcard processing
953 and visit all the matching files. When wildcards are actually
954 used and expanded, the value is a list of buffers
955 that are visiting the various files."
957 (abbreviate-file-name
958 (expand-file-name filename)))
959 (if (file-directory-p filename)
960 (or (and find-file-run-dired
961 (run-hook-with-args-until-success
962 'find-directory-functions
963 (if find-file-visit-truename
964 (abbreviate-file-name (file-truename filename))
966 (error "%s is a directory" filename))
969 (not (string-match "\\`/:" filename))
970 (string-match "[[*?]" filename))
971 (let ((files (condition-case nil
972 (file-expand-wildcards filename t)
973 (error (list filename))))
974 (find-file-wildcards nil))
976 (find-file-noselect filename)
977 (car (mapcar #'find-file-noselect files))))
978 (let* ((buf (get-file-buffer filename))
979 (truename (abbreviate-file-name (file-truename filename)))
980 (number (nthcdr 10 (file-attributes truename)))
981 ;; Find any buffer for a file which has same truename.
982 (other (and (not buf) (find-buffer-visiting filename))))
983 ;; Let user know if there is a buffer with the same truename.
987 (string-equal filename (buffer-file-name other))
988 (message "%s and %s are the same file"
989 filename (buffer-file-name other)))
990 ;; Optionally also find that buffer.
991 (if (or find-file-existing-other-name find-file-visit-truename)
994 ;; We are using an existing buffer.
997 (verify-visited-file-modtime buf)
998 (cond ((not (file-exists-p filename))
999 (error "File %s no longer exists!" filename))
1000 ;; Certain files should be reverted automatically
1001 ;; if they have changed on disk and not in the buffer.
1002 ((and (not (buffer-modified-p buf))
1003 (let ((tail revert-without-query)
1006 (if (string-match (car tail) filename)
1008 (setq tail (cdr tail)))
1010 (with-current-buffer buf
1011 (message "Reverting file %s..." filename)
1013 (message "Reverting file %s...done" filename)))
1015 (if (string= (file-name-nondirectory filename)
1018 (if (buffer-modified-p buf)
1019 "File %s changed on disk. Discard your edits? "
1020 "File %s changed on disk. Reread from disk? ")
1021 (file-name-nondirectory filename))
1023 (if (buffer-modified-p buf)
1024 "File %s changed on disk. Discard your edits in %s? "
1025 "File %s changed on disk. Reread from disk into %s? ")
1026 (file-name-nondirectory filename)
1027 (buffer-name buf))))
1028 (with-current-buffer buf
1029 (revert-buffer t t)))))
1030 (with-current-buffer buf
1031 (when (not (eq (not (null rawfile))
1032 (not (null find-file-literally))))
1033 (if (buffer-modified-p)
1034 (if (y-or-n-p (if rawfile
1035 "Save file and revisit literally? "
1036 "Save file and revisit non-literally? "))
1039 (find-file-noselect-1 buf filename nowarn
1040 rawfile truename number))
1041 (if (y-or-n-p (if rawfile
1042 "Discard your edits and revisit file literally? "
1043 "Discard your edits and revisit file non-literally? "))
1044 (find-file-noselect-1 buf filename nowarn
1045 rawfile truename number)
1046 (error (if rawfile "File already visited non-literally"
1047 "File already visited literally"))))
1048 (if (y-or-n-p (if rawfile
1049 "Revisit file literally? "
1050 "Revisit file non-literally? "))
1051 (find-file-noselect-1 buf filename nowarn
1052 rawfile truename number)
1053 (error (if rawfile "File already visited non-literally"
1054 "File already visited literally"))))))
1055 ;; Return the buffer we are using.
1057 ;; Create a new buffer.
1058 (setq buf (create-file-buffer filename))
1059 (set-buffer-major-mode buf)
1060 ;; find-file-noselect-1 may use a different buffer.
1061 (find-file-noselect-1 buf filename nowarn
1062 rawfile truename number))))))
1064 (defun find-file-noselect-1 (buf filename nowarn rawfile truename number)
1065 (let ((inhibit-read-only t)
1067 (with-current-buffer buf
1068 (kill-local-variable 'find-file-literally)
1069 ;; Needed in case we are re-visiting the file with a different
1070 ;; text representation.
1071 (kill-local-variable 'buffer-file-coding-system)
1073 (and (default-value 'enable-multibyte-characters)
1075 (set-buffer-multibyte t))
1078 (insert-file-contents-literally filename t)
1080 (when (and (file-exists-p filename)
1081 (not (file-readable-p filename)))
1083 (signal 'file-error (list "File is not readable"
1085 ;; Unconditionally set error
1088 (insert-file-contents filename t)
1090 (when (and (file-exists-p filename)
1091 (not (file-readable-p filename)))
1093 (signal 'file-error (list "File is not readable"
1095 ;; Run find-file-not-found-hooks until one returns non-nil.
1096 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
1097 ;; If they fail too, set error.
1099 ;; Record the file's truename, and maybe use that as visited name.
1100 (if (equal filename buffer-file-name)
1101 (setq buffer-file-truename truename)
1102 (setq buffer-file-truename
1103 (abbreviate-file-name (file-truename buffer-file-name))))
1104 (setq buffer-file-number number)
1105 ;; On VMS, we may want to remember which directory in a search list
1106 ;; the file was found in.
1107 (and (eq system-type 'vax-vms)
1109 (if (string-match ":" (file-name-directory filename))
1110 (setq logical (substring (file-name-directory filename)
1111 0 (match-beginning 0))))
1112 (not (member logical find-file-not-true-dirname-list)))
1113 (setq buffer-file-name buffer-file-truename))
1114 (if find-file-visit-truename
1115 (setq buffer-file-name
1117 (expand-file-name buffer-file-truename))))
1118 ;; Set buffer's default directory to that of the file.
1119 (setq default-directory (file-name-directory buffer-file-name))
1120 ;; Turn off backup files for certain file names. Since
1121 ;; this is a permanent local, the major mode won't eliminate it.
1122 (and (not (funcall backup-enable-predicate buffer-file-name))
1124 (make-local-variable 'backup-inhibited)
1125 (setq backup-inhibited t)))
1128 (set-buffer-multibyte nil)
1129 (setq buffer-file-coding-system 'no-conversion)
1130 (make-local-variable 'find-file-literally)
1131 (setq find-file-literally t))
1132 (after-find-file error (not nowarn)))
1135 (defun insert-file-contents-literally (filename &optional visit beg end replace)
1136 "Like `insert-file-contents', but only reads in the file literally.
1137 A buffer may be modified in several ways after reading into the buffer,
1138 to Emacs features such as format decoding, character code
1139 conversion, find-file-hooks, automatic uncompression, etc.
1141 This function ensures that none of these modifications will take place."
1142 (let ((format-alist nil)
1143 (after-insert-file-functions nil)
1144 (coding-system-for-read 'no-conversion)
1145 (coding-system-for-write 'no-conversion)
1146 (jka-compr-compression-info-list nil)
1147 (find-buffer-file-type-function
1148 (if (fboundp 'find-buffer-file-type)
1149 (symbol-function 'find-buffer-file-type)
1153 (fset 'find-buffer-file-type (lambda (filename) t))
1154 (insert-file-contents filename visit beg end replace))
1155 (if find-buffer-file-type-function
1156 (fset 'find-buffer-file-type find-buffer-file-type-function)
1157 (fmakunbound 'find-buffer-file-type)))))
1159 (defun insert-file-literally (filename)
1160 "Insert contents of file FILENAME into buffer after point with no conversion.
1162 This function is meant for the user to run interactively.
1163 Don't call it from programs! Use `insert-file-contents-literally' instead.
1164 \(Its calling sequence is different; see its documentation)."
1165 (interactive "*fInsert file literally: ")
1166 (if (file-directory-p filename)
1167 (signal 'file-error (list "Opening input file" "file is a directory"
1169 (let ((tem (insert-file-contents-literally filename)))
1170 (push-mark (+ (point) (car (cdr tem))))))
1172 (defvar find-file-literally nil
1173 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
1174 This is a permanent local.")
1175 (put 'find-file-literally 'permanent-local t)
1177 (defun find-file-literally (filename)
1178 "Visit file FILENAME with no conversion of any kind.
1179 Format conversion and character code conversion are both disabled,
1180 and multibyte characters are disabled in the resulting buffer.
1181 The major mode used is Fundamental mode regardless of the file name,
1182 and local variable specifications in the file are ignored.
1183 Automatic uncompression is also disabled.
1185 You cannot absolutely rely on this function to result in
1186 visiting the file literally. If Emacs already has a buffer
1187 which is visiting the file, you get the existing buffer,
1188 regardless of whether it was created literally or not.
1190 In a Lisp program, if you want to be sure of accessing a file's
1191 contents literally, you should create a temporary buffer and then read
1192 the file contents into it using `insert-file-contents-literally'."
1193 (interactive "FFind file literally: ")
1194 (switch-to-buffer (find-file-noselect filename nil t)))
1196 (defvar after-find-file-from-revert-buffer nil)
1198 (defun after-find-file (&optional error warn noauto
1199 after-find-file-from-revert-buffer
1201 "Called after finding a file and by the default revert function.
1202 Sets buffer mode, parses local variables.
1203 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
1204 error in reading the file. WARN non-nil means warn if there
1205 exists an auto-save file more recent than the visited file.
1206 NOAUTO means don't mess with auto-save mode.
1207 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1208 means this call was from `revert-buffer'.
1209 Fifth arg NOMODES non-nil means don't alter the file's modes.
1210 Finishes by calling the functions in `find-file-hooks'
1211 unless NOMODES is non-nil."
1212 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1217 (cond ((and error (file-attributes buffer-file-name))
1218 (setq buffer-read-only t)
1219 "File exists, but cannot be read")
1220 ((not buffer-read-only)
1222 ;; No need to warn if buffer is auto-saved
1223 ;; under the name of the visited file.
1224 (not (and buffer-file-name
1225 auto-save-visited-file-name))
1226 (file-newer-than-file-p (or buffer-auto-save-file-name
1227 (make-auto-save-file-name))
1229 (format "%s has auto save data; consider M-x recover-file"
1230 (file-name-nondirectory buffer-file-name))
1231 (setq not-serious t)
1232 (if error "(New file)" nil)))
1234 (setq not-serious t)
1235 "Note: file is write protected")
1236 ((file-attributes (directory-file-name default-directory))
1237 "File not found and directory write-protected")
1238 ((file-exists-p (file-name-directory buffer-file-name))
1239 (setq buffer-read-only nil))
1241 (setq buffer-read-only nil)
1242 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
1243 "Use M-x make-directory RET RET to create the directory"
1244 "Use C-u M-x make-directory RET RET to create directory and its parents")))))
1248 (or not-serious (sit-for 1 nil t)))))
1249 (if (and auto-save-default (not noauto))
1250 (auto-save-mode t)))
1251 ;; Make people do a little extra work (C-x C-q)
1252 ;; before altering a backup file.
1253 (if (backup-file-name-p buffer-file-name)
1254 (setq buffer-read-only t))
1257 (and view-read-only view-mode
1258 (view-mode-disable))
1260 (if (and buffer-read-only view-read-only
1261 (not (eq (get major-mode 'mode-class) 'special)))
1263 (run-hooks 'find-file-hooks)))
1265 (defun normal-mode (&optional find-file)
1266 "Choose the major mode for this buffer automatically.
1267 Also sets up any specified local variables of the file.
1268 Uses the visited file name, the -*- line, and the local variables spec.
1270 This function is called automatically from `find-file'. In that case,
1271 we may set up the file-specified mode and local variables,
1272 depending on the value of `enable-local-variables': if it is t, we do;
1273 if it is nil, we don't; otherwise, we query.
1274 In addition, if `local-enable-local-variables' is nil, we do
1275 not set local variables (though we do notice a mode specified with -*-.)
1277 `enable-local-variables' is ignored if you run `normal-mode' interactively,
1278 or from Lisp without specifying the optional argument FIND-FILE;
1279 in that case, this function acts as if `enable-local-variables' were t."
1281 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1284 (error (message "File mode specification error: %s"
1285 (prin1-to-string err))))
1287 (let ((enable-local-variables (or (not find-file)
1288 enable-local-variables)))
1289 (hack-local-variables))
1290 (error (message "File local-variables error: %s"
1291 (prin1-to-string err)))))
1293 (defvar auto-mode-alist
1294 '(("\\.te?xt\\'" . text-mode)
1295 ("\\.c\\'" . c-mode)
1296 ("\\.h\\'" . c-mode)
1297 ("\\.tex\\'" . tex-mode)
1298 ("\\.ltx\\'" . latex-mode)
1299 ("\\.el\\'" . emacs-lisp-mode)
1300 ("\\.scm\\'" . scheme-mode)
1301 ("\\.l\\'" . lisp-mode)
1302 ("\\.lisp\\'" . lisp-mode)
1303 ("\\.f\\'" . fortran-mode)
1304 ("\\.F\\'" . fortran-mode)
1305 ("\\.for\\'" . fortran-mode)
1306 ("\\.p\\'" . pascal-mode)
1307 ("\\.pas\\'" . pascal-mode)
1308 ("\\.ad[abs]\\'" . ada-mode)
1309 ("\\.\\([pP][Llm]\\|al\\)\\'" . perl-mode)
1310 ("\\.s?html?\\'" . html-mode)
1311 ("\\.cc\\'" . c++-mode)
1312 ("\\.hh\\'" . c++-mode)
1313 ("\\.hpp\\'" . c++-mode)
1314 ("\\.C\\'" . c++-mode)
1315 ("\\.H\\'" . c++-mode)
1316 ("\\.cpp\\'" . c++-mode)
1317 ("\\.cxx\\'" . c++-mode)
1318 ("\\.hxx\\'" . c++-mode)
1319 ("\\.c\\+\\+\\'" . c++-mode)
1320 ("\\.h\\+\\+\\'" . c++-mode)
1321 ("\\.m\\'" . objc-mode)
1322 ("\\.java\\'" . java-mode)
1323 ("\\.mk\\'" . makefile-mode)
1324 ("\\(M\\|m\\|GNUm\\)akefile\\(\\.in\\)?\\'" . makefile-mode)
1325 ("\\.am\\'" . makefile-mode) ;For Automake.
1326 ;;; Less common extensions come here
1327 ;;; so more common ones above are found faster.
1328 ("\\.texinfo\\'" . texinfo-mode)
1329 ("\\.te?xi\\'" . texinfo-mode)
1330 ("\\.s\\'" . asm-mode)
1331 ("\\.S\\'" . asm-mode)
1332 ("\\.asm\\'" . asm-mode)
1333 ("ChangeLog\\'" . change-log-mode)
1334 ("change\\.log\\'" . change-log-mode)
1335 ("changelo\\'" . change-log-mode)
1336 ("ChangeLog\\.[0-9]+\\'" . change-log-mode)
1337 ;; for MSDOS and MS-Windows (which are case-insensitive)
1338 ("changelog\\'" . change-log-mode)
1339 ("changelog\\.[0-9]+\\'" . change-log-mode)
1340 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
1341 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
1342 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
1343 ("\\(/\\|\\`\\)\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
1344 ("\\(/\\|\\`\\)\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
1345 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
1346 ("\\.m?spec$" . sh-mode)
1347 ("\\.mm\\'" . nroff-mode)
1348 ("\\.me\\'" . nroff-mode)
1349 ("\\.ms\\'" . nroff-mode)
1350 ("\\.man\\'" . nroff-mode)
1351 ("\\.\\(u?lpc\\|pike\\|pmod\\)\\'" . pike-mode)
1352 ;;; The following should come after the ChangeLog pattern
1353 ;;; for the sake of ChangeLog.1, etc.
1354 ;;; and after the .scm.[0-9] pattern too.
1355 ("\\.[12345678]\\'" . nroff-mode)
1356 ("\\.TeX\\'" . tex-mode)
1357 ("\\.sty\\'" . latex-mode)
1358 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
1359 ("\\.clo\\'" . latex-mode) ;LaTeX 2e class option
1360 ("\\.bbl\\'" . latex-mode)
1361 ("\\.bib\\'" . bibtex-mode)
1362 ("\\.sql\\'" . sql-mode)
1363 ("\\.m4\\'" . m4-mode)
1364 ("\\.mc\\'" . m4-mode)
1365 ("\\.mf\\'" . metafont-mode)
1366 ("\\.mp\\'" . metapost-mode)
1367 ("\\.vhdl?\\'" . vhdl-mode)
1368 ("\\.article\\'" . text-mode)
1369 ("\\.letter\\'" . text-mode)
1370 ("\\.tcl\\'" . tcl-mode)
1371 ("\\.exp\\'" . tcl-mode)
1372 ("\\.itcl\\'" . tcl-mode)
1373 ("\\.itk\\'" . tcl-mode)
1374 ("\\.icn\\'" . icon-mode)
1375 ("\\.sim\\'" . simula-mode)
1376 ("\\.mss\\'" . scribe-mode)
1377 ("\\.f90\\'" . f90-mode)
1378 ("\\.pro\\'" . idlwave-mode)
1379 ("\\.lsp\\'" . lisp-mode)
1380 ("\\.awk\\'" . awk-mode)
1381 ("\\.prolog\\'" . prolog-mode)
1382 ("\\.tar\\'" . tar-mode)
1383 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\|jar\\)\\'" . archive-mode)
1384 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\|JAR\\)\\'" . archive-mode)
1385 ;; Mailer puts message to be edited in
1386 ;; /tmp/Re.... or Message
1387 ("\\`/tmp/Re" . text-mode)
1388 ("/Message[0-9]*\\'" . text-mode)
1389 ("/drafts/[0-9]+\\'" . mh-letter-mode)
1390 ("\\.zone\\'" . zone-mode)
1391 ;; some news reader is reported to use this
1392 ("\\`/tmp/fol/" . text-mode)
1393 ("\\.y\\'" . c-mode)
1394 ("\\.lex\\'" . c-mode)
1395 ("\\.oak\\'" . scheme-mode)
1396 ("\\.sgml?\\'" . sgml-mode)
1397 ("\\.xml\\'" . sgml-mode)
1398 ("\\.dtd\\'" . sgml-mode)
1399 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
1400 ("\\.idl\\'" . idl-mode)
1401 ;; .emacs following a directory delimiter
1402 ;; in Unix, MSDOG or VMS syntax.
1403 ("[]>:/\\]\\..*emacs\\'" . emacs-lisp-mode)
1404 ("\\`\\..*emacs\\'" . emacs-lisp-mode)
1405 ;; _emacs following a directory delimiter
1407 ("[:/]_emacs\\'" . emacs-lisp-mode)
1408 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode)
1409 ("\\.ml\\'" . lisp-mode)
1410 ("\\.asn$" . snmp-mode)
1411 ("\\.mib$" . snmp-mode)
1412 ("\\.smi$" . snmp-mode)
1413 ("\\.as2$" . snmpv2-mode)
1414 ("\\.mi2$" . snmpv2-mode)
1415 ("\\.sm2$" . snmpv2-mode)
1416 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode)
1417 ("\\.[eE]?[pP][sS]$" . ps-mode)
1418 ("configure\\.in\\'" . autoconf-mode))
1420 Alist of filename patterns vs corresponding major mode functions.
1421 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1422 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1423 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1424 mode function to use. FUNCTION will be called, unless it is nil.
1426 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1427 calling FUNCTION (if it's not nil), we delete the suffix that matched
1428 REGEXP and search the list again for another match.")
1431 (defvar interpreter-mode-alist
1432 '(("perl" . perl-mode)
1433 ("perl5" . perl-mode)
1434 ("miniperl" . perl-mode)
1436 ("wishx" . tcl-mode)
1438 ("tclsh" . tcl-mode)
1443 ("scm" . scheme-mode)
1462 ("tail" . text-mode)
1463 ("more" . text-mode)
1464 ("less" . text-mode)
1466 ("make" . makefile-mode) ; Debian uses this
1467 ("guile" . scheme-mode)
1468 ("clisp" . lisp-mode))
1469 "Alist mapping interpreter names to major modes.
1470 This alist applies to files whose first line starts with `#!'.
1471 Each element looks like (INTERPRETER . MODE).
1472 The car of each element is compared with
1473 the name of the interpreter specified in the first line.
1474 If it matches, mode MODE is selected.")
1476 (defvar inhibit-first-line-modes-regexps '("\\.tar\\'" "\\.tgz\\'")
1477 "List of regexps; if one matches a file name, don't look for `-*-'.")
1479 (defvar inhibit-first-line-modes-suffixes nil
1480 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1481 When checking `inhibit-first-line-modes-regexps', we first discard
1482 from the end of the file name anything that matches one of these regexps.")
1484 (defun set-auto-mode (&optional just-from-file-name)
1485 "Select major mode appropriate for current buffer.
1486 This checks for a -*- mode tag in the buffer's text,
1487 compares the filename against the entries in `auto-mode-alist',
1488 or checks the interpreter that runs this file against
1489 `interpreter-mode-alist'.
1491 It does not check for the `mode:' local variable in the
1492 Local Variables section of the file; for that, use `hack-local-variables'.
1494 If `enable-local-variables' is nil, this function does not check for a
1497 If the optional argument JUST-FROM-FILE-NAME is non-nil,
1498 then we do not set anything but the major mode,
1499 and we don't even do that unless it would come from the file name."
1500 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1501 (let (beg end done modes)
1503 (goto-char (point-min))
1504 (skip-chars-forward " \t\n")
1505 (and enable-local-variables
1506 ;; Don't look for -*- if this file name matches any
1507 ;; of the regexps in inhibit-first-line-modes-regexps.
1508 (let ((temp inhibit-first-line-modes-regexps)
1509 (name (if buffer-file-name
1510 (file-name-sans-versions buffer-file-name)
1512 (while (let ((sufs inhibit-first-line-modes-suffixes))
1513 (while (and sufs (not (string-match (car sufs) name)))
1514 (setq sufs (cdr sufs)))
1516 (setq name (substring name 0 (match-beginning 0))))
1518 (not (string-match (car temp) name)))
1519 (setq temp (cdr temp)))
1521 (search-forward "-*-" (save-excursion
1522 ;; If the file begins with "#!"
1523 ;; (exec interpreter magic), look
1524 ;; for mode frobs in the first two
1525 ;; lines. You cannot necessarily
1526 ;; put them in the first line of
1527 ;; such a file without screwing up
1528 ;; the interpreter invocation.
1529 (end-of-line (and (looking-at "^#!") 2))
1532 (skip-chars-forward " \t")
1534 (search-forward "-*-"
1535 (save-excursion (end-of-line) (point))
1539 (skip-chars-backward " \t")
1542 (if (save-excursion (search-forward ":" end t))
1543 ;; Find all specifications for the `mode:' variable
1544 ;; and execute them left to right.
1545 (while (let ((case-fold-search t))
1546 (or (and (looking-at "mode:")
1547 (goto-char (match-end 0)))
1548 (re-search-forward "[ \t;]mode:" end t)))
1549 (skip-chars-forward " \t")
1551 (if (search-forward ";" end t)
1554 (skip-chars-backward " \t")
1555 (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1557 ;; Simple -*-MODE-*- case.
1558 (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
1561 ;; If we found modes to use, invoke them now,
1562 ;; outside the save-excursion.
1564 (unless just-from-file-name
1565 (mapcar 'funcall (nreverse modes)))
1567 ;; If we didn't find a mode from a -*- line, try using the file name.
1568 (if (and (not done) buffer-file-name)
1569 (let ((name buffer-file-name)
1571 ;; Remove backup-suffixes from file name.
1572 (setq name (file-name-sans-versions name))
1574 (setq keep-going nil)
1575 (let ((alist auto-mode-alist)
1577 ;; Find first matching alist entry.
1578 (let ((case-fold-search
1579 (memq system-type '(vax-vms windows-nt))))
1580 (while (and (not mode) alist)
1581 (if (string-match (car (car alist)) name)
1582 (if (and (consp (cdr (car alist)))
1583 (nth 2 (car alist)))
1584 (setq mode (car (cdr (car alist)))
1585 name (substring name 0 (match-beginning 0))
1587 (setq mode (cdr (car alist))
1589 (setq alist (cdr alist))))
1591 ;; When JUST-FROM-FILE-NAME is set,
1592 ;; we are working on behalf of set-visited-file-name.
1593 ;; In that case, if the major mode specified is the
1594 ;; same one we already have, don't actually reset it.
1595 ;; We don't want to lose minor modes such as Font Lock.
1596 (unless (and just-from-file-name (eq mode major-mode))
1598 ;; If we can't deduce a mode from the file name,
1599 ;; look for an interpreter specified in the first line.
1600 ;; As a special case, allow for things like "#!/bin/env perl",
1601 ;; which finds the interpreter anywhere in $PATH.
1604 (goto-char (point-min))
1605 (if (looking-at "#![ \t]?\\([^ \t\n]*\
1606 /bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1610 ;; Map interpreter name to a mode.
1611 (setq elt (assoc (file-name-nondirectory interpreter)
1612 interpreter-mode-alist))
1613 (unless just-from-file-name
1615 (funcall (cdr elt))))))))))))
1617 (defun hack-local-variables-prop-line ()
1618 "Set local variables specified in the -*- line.
1619 Ignore any specification for `mode:' and `coding:';
1620 `set-auto-mode' should already have handled `mode:',
1621 `set-auto-coding' should already have handled `coding:'."
1623 (goto-char (point-min))
1625 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point)))
1626 (enable-local-variables
1627 (and local-enable-local-variables enable-local-variables)))
1628 ;; Parse the -*- line into the `result' alist.
1629 (cond ((not (search-forward "-*-" end t))
1630 ;; doesn't have one.
1632 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1633 ;; Simple form: "-*- MODENAME -*-". Already handled.
1636 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1637 ;; (last ";" is optional).
1639 (if (search-forward "-*-" end t)
1640 (setq end (- (point) 3))
1641 (error "-*- not terminated before end of line")))
1642 (while (< (point) end)
1643 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1644 (error "Malformed -*- line"))
1645 (goto-char (match-end 0))
1646 ;; There used to be a downcase here,
1647 ;; but the manual didn't say so,
1648 ;; and people want to set var names that aren't all lc.
1649 (let ((key (intern (buffer-substring
1652 (val (save-restriction
1653 (narrow-to-region (point) end)
1654 (read (current-buffer)))))
1655 ;; It is traditional to ignore
1656 ;; case when checking for `mode' in set-auto-mode,
1657 ;; so we must do that here as well.
1658 ;; That is inconsistent, but we're stuck with it.
1659 ;; The same can be said for `coding' in set-auto-coding.
1660 (or (equal (downcase (symbol-name key)) "mode")
1661 (equal (downcase (symbol-name key)) "coding")
1662 (setq result (cons (cons key val) result)))
1663 (skip-chars-forward " \t;")))
1664 (setq result (nreverse result))))
1667 (or (eq enable-local-variables t)
1668 (and enable-local-variables
1669 (save-window-excursion
1671 (switch-to-buffer (current-buffer))
1673 ;; If we fail to switch in the selected window,
1674 ;; it is probably a minibuffer.
1675 ;; So try another window.
1677 (switch-to-buffer-other-window (current-buffer))
1679 (switch-to-buffer-other-frame (current-buffer))))))
1680 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1681 (file-name-nondirectory buffer-file-name)))))))
1682 (let ((enable-local-eval enable-local-eval))
1684 (hack-one-local-variable (car (car result)) (cdr (car result)))
1685 (setq result (cdr result))))))))
1687 (defvar hack-local-variables-hook nil
1688 "Normal hook run after processing a file's local variables specs.
1689 Major modes can use this to examine user-specified local variables
1690 in order to initialize other data structure based on them.")
1692 (defun hack-local-variables (&optional mode-only)
1693 "Parse and put into effect this buffer's local variables spec.
1694 If MODE-ONLY is non-nil, all we do is check whether the major mode
1695 is specified, returning t if it is specified."
1697 (hack-local-variables-prop-line))
1698 ;; Look for "Local variables:" line in last page.
1699 (let (mode-specified
1700 (enable-local-variables
1701 (and local-enable-local-variables enable-local-variables)))
1703 (goto-char (point-max))
1704 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1705 (if (let ((case-fold-search t))
1706 (and (search-forward "Local Variables:" nil t)
1707 (or (eq enable-local-variables t)
1709 (and enable-local-variables
1710 (save-window-excursion
1711 (switch-to-buffer (current-buffer))
1714 (set-window-start (selected-window) (point)))
1715 (y-or-n-p (format "Set local variables as specified at end of %s? "
1716 (if buffer-file-name
1717 (file-name-nondirectory
1720 (buffer-name))))))))))
1722 prefix prefixlen suffix beg
1724 (enable-local-eval enable-local-eval))
1725 ;; The prefix is what comes before "local variables:" in its line.
1726 ;; The suffix is what comes after "local variables:" in its line.
1727 (skip-chars-forward " \t")
1729 (setq suffix (buffer-substring (point)
1730 (progn (end-of-line) (point)))))
1731 (goto-char (match-beginning 0))
1734 (buffer-substring (point)
1735 (progn (beginning-of-line) (point)))))
1737 (if prefix (setq prefixlen (length prefix)
1738 prefix (regexp-quote prefix)))
1739 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1741 ;; Look at next local variable spec.
1742 (if selective-display (re-search-forward "[\n\C-m]")
1744 ;; Skip the prefix, if any.
1746 (if (looking-at prefix)
1747 (forward-char prefixlen)
1748 (error "Local variables entry is missing the prefix")))
1749 ;; Find the variable name; strip whitespace.
1750 (skip-chars-forward " \t")
1752 (skip-chars-forward "^:\n")
1753 (if (eolp) (error "Missing colon in local variables entry"))
1754 (skip-chars-backward " \t")
1755 (let* ((str (buffer-substring beg (point)))
1758 ;; Setting variable named "end" means end of list.
1759 (if (string-equal (downcase str) "end")
1761 ;; Otherwise read the variable value.
1762 (skip-chars-forward "^:")
1764 (setq val (read (current-buffer)))
1765 (skip-chars-backward "\n")
1766 (skip-chars-forward " \t")
1767 (or (if suffix (looking-at suffix) (eolp))
1768 (error "Local variables entry is terminated incorrectly"))
1771 (setq mode-specified t))
1772 ;; Set the variable. "Variables" mode and eval are funny.
1773 (hack-one-local-variable var val))))))))
1775 (run-hooks 'hack-local-variables-hook))
1778 (defvar ignored-local-variables
1779 '(enable-local-eval)
1780 "Variables to be ignored in a file's local variable spec.")
1782 ;; Get confirmation before setting these variables as locals in a file.
1783 (put 'debugger 'risky-local-variable t)
1784 (put 'enable-local-eval 'risky-local-variable t)
1785 (put 'ignored-local-variables 'risky-local-variable t)
1786 (put 'eval 'risky-local-variable t)
1787 (put 'file-name-handler-alist 'risky-local-variable t)
1788 (put 'minor-mode-map-alist 'risky-local-variable t)
1789 (put 'after-load-alist 'risky-local-variable t)
1790 (put 'buffer-file-name 'risky-local-variable t)
1791 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1792 (put 'buffer-file-truename 'risky-local-variable t)
1793 (put 'exec-path 'risky-local-variable t)
1794 (put 'load-path 'risky-local-variable t)
1795 (put 'exec-directory 'risky-local-variable t)
1796 (put 'process-environment 'risky-local-variable t)
1797 (put 'dabbrev-case-fold-search 'risky-local-variable t)
1798 (put 'dabbrev-case-replace 'risky-local-variable t)
1799 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1800 (put 'outline-level 'risky-local-variable t)
1801 (put 'rmail-output-file-alist 'risky-local-variable t)
1803 ;; This one is safe because the user gets to check it before it is used.
1804 (put 'compile-command 'safe-local-variable t)
1806 (defun hack-one-local-variable-quotep (exp)
1807 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1809 (defun hack-one-local-variable (var val)
1810 "\"Set\" one variable in a local variables spec.
1811 A few variable names are treated specially."
1812 (cond ((eq var 'mode)
1813 (funcall (intern (concat (downcase (symbol-name val))
1816 ;; We have already handled coding: tag in set-auto-coding.
1818 ((memq var ignored-local-variables)
1820 ;; "Setting" eval means either eval it or do nothing.
1821 ;; Likewise for setting hook variables.
1822 ((or (get var 'risky-local-variable)
1824 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$\\|-predicate$"
1826 (not (get var 'safe-local-variable))))
1827 ;; Permit evalling a put of a harmless property.
1828 ;; if the args do nothing tricky.
1829 (if (or (and (eq var 'eval)
1832 (hack-one-local-variable-quotep (nth 1 val))
1833 (hack-one-local-variable-quotep (nth 2 val))
1834 ;; Only allow safe values of lisp-indent-hook;
1836 (or (numberp (nth 3 val))
1837 (equal (nth 3 val) ''defun))
1838 (memq (nth 1 (nth 2 val))
1839 '(lisp-indent-hook)))
1840 ;; Permit eval if not root and user says ok.
1841 (and (not (zerop (user-uid)))
1842 (or (eq enable-local-eval t)
1843 (and enable-local-eval
1844 (save-window-excursion
1845 (switch-to-buffer (current-buffer))
1848 (set-window-start (selected-window) (point)))
1849 (setq enable-local-eval
1850 (y-or-n-p (format "Process `eval' or hook local variables in %s? "
1851 (if buffer-file-name
1852 (concat "file " (file-name-nondirectory buffer-file-name))
1853 (concat "buffer " (buffer-name)))))))))))
1855 (save-excursion (eval val))
1856 (make-local-variable var)
1858 (message "Ignoring `eval:' in the local variables list")))
1859 ;; Ordinary variable, really set it.
1860 (t (make-local-variable var)
1864 (defcustom change-major-mode-with-file-name t
1865 "*Non-nil means \\[write-file] should set the major mode from the file name.
1866 However, the mode will not be changed if
1867 \(1) a local variables list or the `-*-' line specifies a major mode, or
1868 \(2) the current major mode is a \"special\" mode,
1869 \ not suitable for ordinary files, or
1870 \(3) the new file name does not particularly specify any mode."
1872 :group 'editing-basics)
1874 (defun set-visited-file-name (filename &optional no-query along-with-file)
1875 "Change name of file visited in current buffer to FILENAME.
1876 The next time the buffer is saved it will go in the newly specified file.
1877 nil or empty string as argument means make buffer not be visiting any file.
1878 Remember to delete the initial contents of the minibuffer
1879 if you wish to pass an empty string as the argument.
1881 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1882 confirmation in the case where another buffer is already visiting FILENAME.
1884 The optional third argument ALONG-WITH-FILE, if non-nil, means that
1885 the old visited file has been renamed to the new name FILENAME."
1886 (interactive "FSet visited file name: ")
1887 (if (buffer-base-buffer)
1888 (error "An indirect buffer cannot visit a file"))
1892 (if (string-equal filename "")
1894 (expand-file-name filename))))
1897 (setq truename (file-truename filename))
1898 (if find-file-visit-truename
1899 (setq filename truename))))
1900 (let ((buffer (and filename (find-buffer-visiting filename))))
1901 (and buffer (not (eq buffer (current-buffer)))
1903 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1906 (or (equal filename buffer-file-name)
1908 (and filename (lock-buffer filename))
1910 (setq buffer-file-name filename)
1911 (if filename ; make buffer name reflect filename.
1912 (let ((new-name (file-name-nondirectory buffer-file-name)))
1913 (if (string= new-name "")
1914 (error "Empty file name"))
1915 (if (eq system-type 'vax-vms)
1916 (setq new-name (downcase new-name)))
1917 (setq default-directory (file-name-directory buffer-file-name))
1918 (or (string= new-name (buffer-name))
1919 (rename-buffer new-name t))))
1920 (setq buffer-backed-up nil)
1922 (clear-visited-file-modtime))
1923 ;; Abbreviate the file names of the buffer.
1926 (setq buffer-file-truename (abbreviate-file-name truename))
1927 (if find-file-visit-truename
1928 (setq buffer-file-name buffer-file-truename))))
1929 (setq buffer-file-number
1931 (nthcdr 10 (file-attributes buffer-file-name))
1933 ;; write-file-hooks is normally used for things like ftp-find-file
1934 ;; that visit things that are not local files as if they were files.
1935 ;; Changing to visit an ordinary local file instead should flush the hook.
1936 (kill-local-variable 'write-file-hooks)
1937 (kill-local-variable 'local-write-file-hooks)
1938 (kill-local-variable 'revert-buffer-function)
1939 (kill-local-variable 'backup-inhibited)
1940 ;; If buffer was read-only because of version control,
1941 ;; that reason is gone now, so make it writable.
1943 (setq buffer-read-only nil))
1944 (kill-local-variable 'vc-mode)
1945 ;; Turn off backup files for certain file names.
1946 ;; Since this is a permanent local, the major mode won't eliminate it.
1947 (and buffer-file-name
1948 (not (funcall backup-enable-predicate buffer-file-name))
1950 (make-local-variable 'backup-inhibited)
1951 (setq backup-inhibited t)))
1952 (let ((oauto buffer-auto-save-file-name))
1953 ;; If auto-save was not already on, turn it on if appropriate.
1954 (if (not buffer-auto-save-file-name)
1955 (and buffer-file-name auto-save-default
1957 ;; If auto save is on, start using a new name.
1958 ;; We deliberately don't rename or delete the old auto save
1959 ;; for the old visited file name. This is because perhaps
1960 ;; the user wants to save the new state and then compare with the
1961 ;; previous state from the auto save file.
1962 (setq buffer-auto-save-file-name
1963 (make-auto-save-file-name)))
1964 ;; Rename the old auto save file if any.
1965 (and oauto buffer-auto-save-file-name
1966 (file-exists-p oauto)
1967 (rename-file oauto buffer-auto-save-file-name t)))
1968 (and buffer-file-name
1969 (not along-with-file)
1970 (set-buffer-modified-p t))
1971 ;; Update the major mode, if the file name determines it.
1973 ;; Don't change the mode if it is special.
1974 (or (not change-major-mode-with-file-name)
1975 (get major-mode 'mode-class)
1976 ;; Don't change the mode if the local variable list specifies it.
1977 (hack-local-variables t)
1981 (defun write-file (filename &optional confirm)
1982 "Write current buffer into file FILENAME.
1983 This makes the buffer visit that file, and marks it as not modified.
1985 If you specify just a directory name as FILENAME, that means to use
1986 the default file name but in that directory. You can also yank
1987 the default file name into the minibuffer to edit it, using M-n.
1989 If the buffer is not already visiting a file, the default file name
1990 for the output file is the buffer name.
1992 If optional second arg CONFIRM is non-nil, this function
1993 asks for confirmation before overwriting an existing file.
1994 Interactively, confirmation is required unless you supply a prefix argument."
1995 ;; (interactive "FWrite file: ")
1997 (list (if buffer-file-name
1998 (read-file-name "Write file: "
2000 (read-file-name "Write file: " default-directory
2002 (file-name-nondirectory (buffer-name))
2005 (not current-prefix-arg)))
2006 (or (null filename) (string-equal filename "")
2008 ;; If arg is just a directory,
2009 ;; use the default file name, but in that directory.
2010 (if (file-directory-p filename)
2011 (setq filename (concat (file-name-as-directory filename)
2012 (file-name-nondirectory
2013 (or buffer-file-name (buffer-name))))))
2015 (file-exists-p filename)
2016 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
2017 (error "Canceled")))
2018 (set-visited-file-name filename (not confirm))))
2019 (set-buffer-modified-p t)
2020 ;; Make buffer writable if file is writable.
2021 (and buffer-file-name
2022 (file-writable-p buffer-file-name)
2023 (setq buffer-read-only nil))
2026 (defun backup-buffer ()
2027 "Make a backup of the disk file visited by the current buffer, if appropriate.
2028 This is normally done before saving the buffer the first time.
2029 If the value is non-nil, it is the result of `file-modes' on the original
2030 file; this means that the caller, after saving the buffer, should change
2031 the modes of the new file to agree with the old modes.
2033 A backup may be done by renaming or by copying; see documentation of
2034 variable `make-backup-files'. If it's done by renaming, then the file is
2035 no longer accessible under its old name."
2036 (if (and make-backup-files (not backup-inhibited)
2037 (not buffer-backed-up)
2038 (file-exists-p buffer-file-name)
2039 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
2041 (let ((real-file-name buffer-file-name)
2042 backup-info backupname targets setmodes)
2043 ;; If specified name is a symbolic link, chase it to the target.
2044 ;; Thus we make the backups in the directory where the real file is.
2045 (setq real-file-name (file-chase-links real-file-name))
2046 (setq backup-info (find-backup-file-name real-file-name)
2047 backupname (car backup-info)
2048 targets (cdr backup-info))
2049 ;;; (if (file-directory-p buffer-file-name)
2050 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
2053 (let ((delete-old-versions
2054 ;; If have old versions to maybe delete,
2055 ;; ask the user to confirm now, before doing anything.
2056 ;; But don't actually delete til later.
2058 (or (eq delete-old-versions t) (eq delete-old-versions nil))
2059 (or delete-old-versions
2060 (y-or-n-p (format "Delete excess backup versions of %s? "
2061 real-file-name))))))
2062 ;; Actually write the back up file.
2064 (if (or file-precious-flag
2065 ; (file-symlink-p buffer-file-name)
2067 (and backup-by-copying-when-linked
2068 (> (file-nlinks real-file-name) 1))
2069 (and (or backup-by-copying-when-mismatch
2070 (integerp backup-by-copying-when-privileged-mismatch))
2071 (let ((attr (file-attributes real-file-name)))
2072 (and (or backup-by-copying-when-mismatch
2073 (and (integerp (nth 2 attr))
2074 (integerp backup-by-copying-when-privileged-mismatch)
2075 (<= (nth 2 attr) backup-by-copying-when-privileged-mismatch)))
2077 (not (file-ownership-preserved-p real-file-name)))))))
2079 (copy-file real-file-name backupname t t)
2081 ;; If copying fails because file BACKUPNAME
2082 ;; is not writable, delete that file and try again.
2083 (if (and (file-exists-p backupname)
2084 (not (file-writable-p backupname)))
2085 (delete-file backupname))
2086 (copy-file real-file-name backupname t t)))
2087 ;; rename-file should delete old backup.
2088 (rename-file real-file-name backupname t)
2089 (setq setmodes (file-modes backupname)))
2091 ;; If trouble writing the backup, write it in ~.
2092 (setq backupname (expand-file-name
2093 (convert-standard-filename
2095 (message "Cannot write backup file; backing up in %s"
2096 (file-name-nondirectory backupname))
2099 (copy-file real-file-name backupname t t)
2101 ;; If copying fails because file BACKUPNAME
2102 ;; is not writable, delete that file and try again.
2103 (if (and (file-exists-p backupname)
2104 (not (file-writable-p backupname)))
2105 (delete-file backupname))
2106 (copy-file real-file-name backupname t t)))))
2107 (setq buffer-backed-up t)
2108 ;; Now delete the old versions, if desired.
2109 (if delete-old-versions
2112 (delete-file (car targets))
2114 (setq targets (cdr targets))))
2116 (file-error nil))))))
2118 (defun file-name-sans-versions (name &optional keep-backup-version)
2119 "Return file NAME sans backup versions or strings.
2120 This is a separate procedure so your site-init or startup file can
2122 If the optional argument KEEP-BACKUP-VERSION is non-nil,
2123 we do not remove backup version numbers, only true file version numbers."
2124 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
2126 (funcall handler 'file-name-sans-versions name keep-backup-version)
2128 (if (eq system-type 'vax-vms)
2129 ;; VMS version number is (a) semicolon, optional
2130 ;; sign, zero or more digits or (b) period, option
2131 ;; sign, zero or more digits, provided this is the
2132 ;; second period encountered outside of the
2133 ;; device/directory part of the file name.
2134 (or (string-match ";[-+]?[0-9]*\\'" name)
2135 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
2137 (match-beginning 1))
2139 (if keep-backup-version
2141 (or (string-match "\\.~[0-9.]+~\\'" name)
2142 (string-match "~\\'" name)
2143 (length name))))))))
2145 (defun file-ownership-preserved-p (file)
2146 "Return t if deleting FILE and rewriting it would preserve the owner."
2147 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
2149 (funcall handler 'file-ownership-preserved-p file)
2150 (let ((attributes (file-attributes file)))
2151 ;; Return t if the file doesn't exist, since it's true that no
2152 ;; information would be lost by an (attempted) delete and create.
2153 (or (null attributes)
2154 (= (nth 2 attributes) (user-uid)))))))
2156 (defun file-name-sans-extension (filename)
2157 "Return FILENAME sans final \"extension\".
2158 The extension, in a file name, is the part that follows the last `.'."
2160 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
2162 (if (string-match "\\.[^.]*\\'" file)
2163 (if (setq directory (file-name-directory filename))
2164 (expand-file-name (substring file 0 (match-beginning 0))
2166 (substring file 0 (match-beginning 0)))
2169 (defun file-name-extension (filename &optional period)
2170 "Return FILENAME's final \"extension\".
2171 The extension, in a file name, is the part that follows the last `.'.
2172 Return nil for extensionless file names such as `foo'.
2173 Return the empty string for file names such as `foo.'.
2175 If PERIOD is non-nil, then the returned value includes the period
2176 that delimits the extension, and if FILENAME has no extension,
2179 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
2180 (if (string-match "\\.[^.]*\\'" file)
2181 (substring file (+ (match-beginning 0) (if period 0 1)))
2185 (defcustom make-backup-file-name-function nil
2186 "A function to use instead of the default `make-backup-file-name'.
2187 A value of nil gives the default `make-backup-file-name' behaviour.
2189 This could be buffer-local to do something special for for specific
2190 files. If you define it, you may need to change `backup-file-name-p'
2191 and `file-name-sans-versions' too.
2193 See also `backup-directory-alist'."
2195 :type '(choice (const :tag "Default" nil)
2196 (function :tag "Your function")))
2198 (defcustom backup-directory-alist nil
2199 "Alist of filename patterns and backup directory names.
2200 Each element looks like (REGEXP . DIRECTORY). Backups of files with
2201 names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
2202 relative or absolute. If it is absolute, so that all matching files
2203 are backed up into the same directory, the file names in this
2204 directory will be the full name of the file backed up with all
2205 directory separators changed to `|' to prevent clashes. This will not
2206 work correctly if your filesystem truncates the resulting name.
2208 For the common case of all backups going into one directory, the alist
2209 should contain a single element pairing \".\" with the appropriate
2212 If this variable is nil, or it fails to match a filename, the backup
2213 is made in the original file's directory.
2215 On MS-DOS filesystems without long names this variable is always
2218 :type '(repeat (cons (regexp :tag "Regexp macthing filename")
2219 (directory :tag "Backup directory name"))))
2221 (defun make-backup-file-name (file)
2222 "Create the non-numeric backup file name for FILE.
2223 Normally this will just be the file's name with `~' appended.
2224 Customization hooks are provided as follows.
2226 If the variable `make-backup-file-name-function' is non-nil, its value
2227 should be a function which will be called with FILE as its argument;
2228 the resulting name is used.
2230 Otherwise a match for FILE is sought in `backup-directory-alist'; see
2231 the documentation of that variable. If the directory for the backup
2232 doesn't exist, it is created."
2233 (if make-backup-file-name-function
2234 (funcall make-backup-file-name-function file)
2235 (if (and (eq system-type 'ms-dos)
2236 (not (msdos-long-file-names)))
2237 (let ((fn (file-name-nondirectory file)))
2238 (concat (file-name-directory file)
2239 (or (and (string-match "\\`[^.]+\\'" fn)
2240 (concat (match-string 0 fn) ".~"))
2241 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
2242 (concat (match-string 0 fn) "~")))))
2243 (concat (make-backup-file-name-1 file) "~"))))
2245 (defun make-backup-file-name-1 (file)
2246 "Subroutine of `make-backup-file-name' and `find-backup-file-name'."
2247 (let ((alist backup-directory-alist)
2248 elt backup-directory)
2250 (setq elt (pop alist))
2251 (if (string-match (car elt) file)
2252 (setq backup-directory (cdr elt)
2254 (if (null backup-directory)
2256 (unless (file-exists-p backup-directory)
2258 (make-directory backup-directory 'parents)
2260 (if (file-name-absolute-p backup-directory)
2261 ;; Make the name unique by substituting directory
2262 ;; separators. It may not really be worth bothering about
2263 ;; doubling `|'s in the original name...
2265 (subst-char-in-string
2266 directory-sep-char ?|
2267 (replace-regexp-in-string "|" "||" file))
2269 (expand-file-name (file-name-nondirectory file)
2270 (file-name-as-directory
2271 (expand-file-name backup-directory
2272 (file-name-directory file))))))))
2274 (defun backup-file-name-p (file)
2275 "Return non-nil if FILE is a backup file name (numeric or not).
2276 This is a separate function so you can redefine it for customization.
2277 You may need to redefine `file-name-sans-versions' as well."
2278 (string-match "~\\'" file))
2280 (defvar backup-extract-version-start)
2282 ;; This is used in various files.
2283 ;; The usage of backup-extract-version-start is not very clean,
2284 ;; but I can't see a good alternative, so as of now I am leaving it alone.
2285 (defun backup-extract-version (fn)
2286 "Given the name of a numeric backup file, FN, return the backup number.
2287 Uses the free variable `backup-extract-version-start', whose value should be
2288 the index in the name where the version number begins."
2289 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start)
2290 (= (match-beginning 0) backup-extract-version-start))
2291 (string-to-int (substring fn backup-extract-version-start -1))
2294 ;; I believe there is no need to alter this behavior for VMS;
2295 ;; since backup files are not made on VMS, it should not get called.
2296 (defun find-backup-file-name (fn)
2297 "Find a file name for a backup file FN, and suggestions for deletions.
2298 Value is a list whose car is the name for the backup file
2299 and whose cdr is a list of old versions to consider deleting now.
2300 If the value is nil, don't make a backup.
2301 Uses `backup-directory-alist' in the same way as does
2302 `make-backup-file-name'."
2303 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
2304 ;; Run a handler for this function so that ange-ftp can refuse to do it.
2306 (funcall handler 'find-backup-file-name fn)
2307 (if (eq version-control 'never)
2308 (list (make-backup-file-name fn))
2309 (let* ((basic-name (make-backup-file-name-1 fn))
2310 (base-versions (concat (file-name-nondirectory basic-name)
2312 (backup-extract-version-start (length base-versions))
2314 (number-to-delete 0)
2315 possibilities deserve-versions-p versions)
2317 (setq possibilities (file-name-all-completions
2319 (file-name-directory basic-name))
2320 versions (sort (mapcar #'backup-extract-version
2323 high-water-mark (apply 'max 0 versions)
2324 deserve-versions-p (or version-control
2325 (> high-water-mark 0))
2326 number-to-delete (- (length versions)
2330 (file-error (setq possibilities nil)))
2331 (if (not deserve-versions-p)
2332 (list (concat basic-name "~"))
2333 (cons (format "%s.~%d~" basic-name (1+ high-water-mark))
2334 (if (and (> number-to-delete 0)
2335 ;; Delete nothing if there is overflow
2336 ;; in the number of versions to keep.
2337 (>= (+ kept-new-versions kept-old-versions -1) 0))
2339 (format "%s.~%d~" basic-name n))
2340 (let ((v (nthcdr kept-old-versions versions)))
2341 (rplacd (nthcdr (1- number-to-delete) v) ())
2344 (defun file-nlinks (filename)
2345 "Return number of names file FILENAME has."
2346 (car (cdr (file-attributes filename))))
2348 (defun file-relative-name (filename &optional directory)
2349 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
2350 This function returns a relative file name which is equivalent to FILENAME
2351 when used with that default directory as the default.
2352 If this is impossible (which can happen on MSDOS and Windows
2353 when the file name and directory use different drive names)
2354 then it returns FILENAME."
2356 (let ((fname (expand-file-name filename)))
2357 (setq directory (file-name-as-directory
2358 (expand-file-name (or directory default-directory))))
2359 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2360 ;; drive names, they can't be relative, so return the absolute name.
2361 (if (and (or (eq system-type 'ms-dos)
2362 (eq system-type 'windows-nt))
2363 (not (string-equal (substring fname 0 2)
2364 (substring directory 0 2))))
2366 (let ((ancestor ".")
2367 (fname-dir (file-name-as-directory fname)))
2368 (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
2369 (not (string-match (concat "^" (regexp-quote directory)) fname)))
2370 (setq directory (file-name-directory (substring directory 0 -1))
2371 ancestor (if (equal ancestor ".")
2373 (concat "../" ancestor))))
2374 ;; Now ancestor is empty, or .., or ../.., etc.
2375 (if (string-match (concat "^" (regexp-quote directory)) fname)
2376 ;; We matched within FNAME's directory part.
2377 ;; Add the rest of FNAME onto ANCESTOR.
2378 (let ((rest (substring fname (match-end 0))))
2379 (if (and (equal ancestor ".")
2380 (not (equal rest "")))
2381 ;; But don't bother with ANCESTOR if it would give us `./'.
2383 (concat (file-name-as-directory ancestor) rest)))
2384 ;; We matched FNAME's directory equivalent.
2387 (defun save-buffer (&optional args)
2388 "Save current buffer in visited file if modified. Versions described below.
2389 By default, makes the previous version into a backup file
2390 if previously requested or if this is the first save.
2391 With 1 \\[universal-argument], marks this version
2392 to become a backup when the next save is done.
2393 With 2 \\[universal-argument]'s,
2394 unconditionally makes the previous version into a backup file.
2395 With 3 \\[universal-argument]'s, marks this version
2396 to become a backup when the next save is done,
2397 and unconditionally makes the previous version into a backup file.
2399 With argument of 0, never make the previous version into a backup file.
2401 If a file's name is FOO, the names of its numbered backup versions are
2402 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2403 Numeric backups (rather than FOO~) will be made if value of
2404 `version-control' is not the atom `never' and either there are already
2405 numeric versions of the file being backed up, or `version-control' is
2407 We don't want excessive versions piling up, so there are variables
2408 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2409 and `kept-new-versions', which tells how many newest versions to keep.
2410 Defaults are 2 old versions and 2 new.
2411 `dired-kept-versions' controls dired's clean-directory (.) command.
2412 If `delete-old-versions' is nil, system will query user
2413 before trimming versions. Otherwise it does it silently.
2415 If `vc-make-backup-files' is nil, which is the default,
2416 no backup files are made for files managed by version control.
2417 (This is because the version control system itself records previous versions.)
2419 See the subroutine `basic-save-buffer' for more information."
2421 (let ((modp (buffer-modified-p))
2422 (large (> (buffer-size) 50000))
2423 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2424 (memq args '(16 64)))))
2425 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2426 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
2428 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2430 (defun delete-auto-save-file-if-necessary (&optional force)
2431 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2432 Normally delete only if the file was written by this Emacs since
2433 the last real save, but optional arg FORCE non-nil means delete anyway."
2434 (and buffer-auto-save-file-name delete-auto-save-files
2435 (not (string= buffer-file-name buffer-auto-save-file-name))
2436 (or force (recent-auto-save-p))
2439 (delete-file buffer-auto-save-file-name)
2441 (set-buffer-auto-saved))))
2443 (defvar auto-save-hook nil
2444 "Normal hook run just before auto-saving.")
2446 (defvar after-save-hook nil
2447 "Normal hook that is run after a buffer is saved to its file.")
2449 (defvar save-buffer-coding-system nil
2450 "If non-nil, use this coding system for saving the buffer.
2451 More precisely, use this coding system in place of the
2452 value of `buffer-file-coding-system', when saving the buffer.
2453 Calling `write-region' for any purpose other than saving the buffer
2454 will still use `buffer-file-coding-system'; this variable has no effect
2457 (make-variable-buffer-local 'save-buffer-coding-system)
2458 (put 'save-buffer-coding-system 'permanent-local t)
2460 (defun basic-save-buffer ()
2461 "Save the current buffer in its visited file, if it has been modified.
2462 The hooks `write-contents-hooks', `local-write-file-hooks' and
2463 `write-file-hooks' get a chance to do the job of saving; if they do not,
2464 then the buffer is saved in the visited file file in the usual way.
2465 After saving the buffer, this function runs `after-save-hook'."
2467 (save-current-buffer
2468 ;; In an indirect buffer, save its base buffer instead.
2469 (if (buffer-base-buffer)
2470 (set-buffer (buffer-base-buffer)))
2471 (if (buffer-modified-p)
2472 (let ((recent-save (recent-auto-save-p))
2473 setmodes tempsetmodes)
2474 ;; On VMS, rename file and buffer to get rid of version number.
2475 (if (and (eq system-type 'vax-vms)
2476 (not (string= buffer-file-name
2477 (file-name-sans-versions buffer-file-name))))
2478 (let (buffer-new-name)
2479 ;; Strip VMS version number before save.
2480 (setq buffer-file-name
2481 (file-name-sans-versions buffer-file-name))
2482 ;; Construct a (unique) buffer name to correspond.
2483 (let ((buf (create-file-buffer (downcase buffer-file-name))))
2484 (setq buffer-new-name (buffer-name buf))
2486 (rename-buffer buffer-new-name)))
2487 ;; If buffer has no file name, ask user for one.
2488 (or buffer-file-name
2491 (read-file-name "File to save in: ") nil)))
2492 (and (file-exists-p filename)
2493 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2495 (error "Canceled")))
2496 (set-visited-file-name filename)))
2497 (or (verify-visited-file-modtime (current-buffer))
2498 (not (file-exists-p buffer-file-name))
2500 (format "%s has changed since visited or saved. Save anyway? "
2501 (file-name-nondirectory buffer-file-name)))
2502 (error "Save not confirmed"))
2506 (and (> (point-max) 1)
2507 (/= (char-after (1- (point-max))) ?\n)
2508 (not (and (eq selective-display t)
2509 (= (char-after (1- (point-max))) ?\r)))
2510 (or (eq require-final-newline t)
2511 (and require-final-newline
2513 (format "Buffer %s does not end in newline. Add one? "
2516 (goto-char (point-max))
2518 (or (run-hook-with-args-until-success 'write-contents-hooks)
2519 (run-hook-with-args-until-success 'local-write-file-hooks)
2520 (run-hook-with-args-until-success 'write-file-hooks)
2521 ;; If a hook returned t, file is already "written".
2522 ;; Otherwise, write it the usual way now.
2523 (setq setmodes (basic-save-buffer-1)))
2524 ;; Now we have saved the current buffer. Let's make sure
2525 ;; that buffer-file-coding-system is fixed to what
2526 ;; actually used for saving by binding it locally.
2527 (if save-buffer-coding-system
2528 (setq save-buffer-coding-system last-coding-system-used)
2529 (setq buffer-file-coding-system last-coding-system-used))
2530 (setq buffer-file-number
2531 (nthcdr 10 (file-attributes buffer-file-name)))
2534 (set-file-modes buffer-file-name setmodes)
2536 ;; If the auto-save file was recent before this command,
2538 (delete-auto-save-file-if-necessary recent-save)
2539 ;; Support VC `implicit' locking.
2541 (run-hooks 'after-save-hook))
2542 (message "(No changes need to be saved)"))))
2544 ;; This does the "real job" of writing a buffer into its visited file
2545 ;; and making a backup file. This is what is normally done
2546 ;; but inhibited if one of write-file-hooks returns non-nil.
2547 ;; It returns a value to store in setmodes.
2548 (defun basic-save-buffer-1 ()
2549 (if save-buffer-coding-system
2550 (let ((coding-system-for-write save-buffer-coding-system))
2551 (basic-save-buffer-2))
2552 (basic-save-buffer-2)))
2554 (defun basic-save-buffer-2 ()
2555 (let (tempsetmodes setmodes)
2556 (if (not (file-writable-p buffer-file-name))
2557 (let ((dir (file-name-directory buffer-file-name)))
2558 (if (not (file-directory-p dir))
2559 (if (file-exists-p dir)
2560 (error "%s is not a directory" dir)
2561 (error "%s: no such directory" buffer-file-name))
2562 (if (not (file-exists-p buffer-file-name))
2563 (error "Directory %s write-protected" dir)
2565 (format "File %s is write-protected; try to save anyway? "
2566 (file-name-nondirectory
2568 (setq tempsetmodes t)
2569 (error "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 temp nogood i succeed
2580 (old-modtime (visited-file-modtime)))
2583 ;; Find the temporary name to write under.
2585 (setq tempname (format
2586 (if (and (eq system-type 'ms-dos)
2587 (not (msdos-long-file-names)))
2588 "%s#%d.tm#" ; MSDOS limits files to 8+3
2591 (setq nogood (file-exists-p tempname))
2594 (progn (clear-visited-file-modtime)
2595 (write-region (point-min) (point-max)
2596 tempname nil realname
2597 buffer-file-truename)
2599 ;; If writing the temp file fails,
2600 ;; delete the temp file.
2603 (delete-file tempname)
2604 (set-visited-file-modtime old-modtime))))
2605 ;; Since we have created an entirely new file
2606 ;; and renamed it, make sure it gets the
2607 ;; right permission bits set.
2608 (setq setmodes (file-modes buffer-file-name))
2609 ;; We succeeded in writing the temp file,
2611 (rename-file tempname buffer-file-name t))
2612 ;; If file not writable, see if we can make it writable
2613 ;; temporarily while we write it.
2614 ;; But no need to do so if we have just backed it up
2615 ;; (setmodes is set) because that says we're superseding.
2616 (cond ((and tempsetmodes (not setmodes))
2617 ;; Change the mode back, after writing.
2618 (setq setmodes (file-modes buffer-file-name))
2619 (set-file-modes buffer-file-name 511)))
2620 (write-region (point-min) (point-max)
2621 buffer-file-name nil t buffer-file-truename)))
2624 (defun save-some-buffers (&optional arg pred)
2625 "Save some modified file-visiting buffers. Asks user about each one.
2626 Optional argument (the prefix) non-nil means save all with no questions.
2627 Optional second argument PRED determines which buffers are considered:
2628 If PRED is nil, all the file-visiting buffers are considered.
2629 If PRED is t, then certain non-file buffers will also be considered.
2630 If PRED is a zero-argument function, it indicates for each buffer whether
2631 to consider it or not when called with that buffer current."
2633 (save-window-excursion
2634 (let* ((queried nil)
2639 (and (buffer-modified-p buffer)
2640 (not (buffer-base-buffer buffer))
2642 (buffer-file-name buffer)
2646 (and buffer-offer-save (> (buffer-size) 0)))))
2647 (or (not (functionp pred))
2648 (with-current-buffer buffer (funcall pred)))
2652 (if (buffer-file-name buffer)
2653 (format "Save file %s? "
2654 (buffer-file-name buffer))
2655 (format "Save buffer %s? "
2656 (buffer-name buffer)))))))
2662 '("buffer" "buffers" "save")
2663 (list (list ?\C-r (lambda (buf)
2667 (exit-recursive-edit))))
2669 ;; Return nil to ask about BUF again.
2671 "display the current buffer"))))
2673 (and save-abbrevs abbrevs-changed
2676 (y-or-n-p (format "Save abbrevs in %s? "
2678 (write-abbrev-file nil))
2679 ;; Don't keep bothering user if he says no.
2680 (setq abbrevs-changed nil)
2682 (or queried (> files-done 0) abbrevs-done
2683 (message "(No files need saving)")))))
2685 (defun not-modified (&optional arg)
2686 "Mark current buffer as unmodified, not needing to be saved.
2687 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2689 It is not a good idea to use this function in Lisp programs, because it
2690 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2692 (message (if arg "Modification-flag set"
2693 "Modification-flag cleared"))
2694 (set-buffer-modified-p arg))
2696 (defun toggle-read-only (&optional arg)
2697 "Change whether this buffer is visiting its file read-only.
2698 With arg, set read-only iff arg is positive.
2699 If visiting file read-only and `view-read-only' is non-nil, enter view mode."
2702 ((and arg (if (> (prefix-numeric-value arg) 0) buffer-read-only
2703 (not buffer-read-only))) ; If buffer-read-only is set correctly,
2706 ((and buffer-read-only view-mode)
2707 (View-exit-and-edit)
2708 (make-local-variable 'view-read-only)
2709 (setq view-read-only t)) ; Must leave view mode.
2710 ((and (not buffer-read-only) view-read-only
2711 (not (eq (get major-mode 'mode-class) 'special)))
2713 (t (setq buffer-read-only (not buffer-read-only))
2714 (force-mode-line-update))))
2716 (defun insert-file (filename)
2717 "Insert contents of file FILENAME into buffer after point.
2718 Set mark after the inserted text.
2720 This function is meant for the user to run interactively.
2721 Don't call it from programs! Use `insert-file-contents' instead.
2722 \(Its calling sequence is different; see its documentation)."
2723 (interactive "*fInsert file: ")
2724 (if (file-directory-p filename)
2725 (signal 'file-error (list "Opening input file" "file is a directory"
2727 (let ((tem (insert-file-contents filename)))
2728 (push-mark (+ (point) (car (cdr tem))))))
2730 (defun append-to-file (start end filename)
2731 "Append the contents of the region to the end of file FILENAME.
2732 When called from a function, expects three arguments,
2733 START, END and FILENAME. START and END are buffer positions
2734 saying what text to write."
2735 (interactive "r\nFAppend to file: ")
2736 (write-region start end filename t))
2738 (defun file-newest-backup (filename)
2739 "Return most recent backup file for FILENAME or nil if no backups exist."
2740 ;; `make-backup-file-name' will get us the right directory for
2741 ;; ordinary or numeric backups. It might create a directory for
2742 ;; backups as a side-effect, according to `backup-directory-alist'.
2743 (let* ((filename (file-name-sans-versions
2744 (make-backup-file-name filename)))
2745 (file (file-name-nondirectory filename))
2746 (dir (file-name-directory filename))
2747 (comp (file-name-all-completions file dir))
2751 (setq tem (pop comp))
2752 (cond ((and (backup-file-name-p tem)
2753 (string= (file-name-sans-versions tem) file))
2754 (setq tem (concat dir tem))
2755 (if (or (null newest)
2756 (file-newer-than-file-p tem newest))
2757 (setq newest tem)))))
2760 (defun rename-uniquely ()
2761 "Rename current buffer to a similar name not already taken.
2762 This function is useful for creating multiple shell process buffers
2763 or multiple mail buffers, etc."
2766 (let ((base-name (buffer-name)))
2767 (and (string-match "<[0-9]+>\\'" base-name)
2768 (not (and buffer-file-name
2770 (file-name-nondirectory buffer-file-name))))
2771 ;; If the existing buffer name has a <NNN>,
2772 ;; which isn't part of the file name (if any),
2773 ;; then get rid of that.
2774 (setq base-name (substring base-name 0 (match-beginning 0))))
2775 (rename-buffer (generate-new-buffer-name base-name))
2776 (force-mode-line-update))))
2778 (defun make-directory (dir &optional parents)
2779 "Create the directory DIR and any nonexistent parent dirs.
2780 Interactively, the default choice of directory to create
2781 is the current default directory for file names.
2782 That is useful when you have visited a file in a nonexistent directory.
2784 Noninteractively, the second (optional) argument PARENTS says whether
2785 to create parent directories if they don't exist."
2787 (list (read-file-name "Make directory: " default-directory default-directory
2790 (let ((handler (find-file-name-handler dir 'make-directory)))
2792 (funcall handler 'make-directory dir parents)
2794 (make-directory-internal dir)
2795 (let ((dir (directory-file-name (expand-file-name dir)))
2797 (while (not (file-exists-p dir))
2798 (setq create-list (cons dir create-list)
2799 dir (directory-file-name (file-name-directory dir))))
2801 (make-directory-internal (car create-list))
2802 (setq create-list (cdr create-list))))))))
2804 (put 'revert-buffer-function 'permanent-local t)
2805 (defvar revert-buffer-function nil
2806 "Function to use to revert this buffer, or nil to do the default.
2807 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2808 which are the arguments that `revert-buffer' received.")
2810 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2811 (defvar revert-buffer-insert-file-contents-function nil
2812 "Function to use to insert contents when reverting this buffer.
2813 Gets two args, first the nominal file name to use,
2814 and second, t if reading the auto-save file.
2816 The function you specify is responsible for updating (or preserving) point.")
2818 (defvar before-revert-hook nil
2819 "Normal hook for `revert-buffer' to run before reverting.
2820 If `revert-buffer-function' is used to override the normal revert
2821 mechanism, this hook is not used.")
2823 (defvar after-revert-hook nil
2824 "Normal hook for `revert-buffer' to run after reverting.
2825 Note that the hook value that it runs is the value that was in effect
2826 before reverting; that makes a difference if you have buffer-local
2829 If `revert-buffer-function' is used to override the normal revert
2830 mechanism, this hook is not used.")
2832 (defvar revert-buffer-internal-hook)
2834 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2835 "Replace current buffer text with the text of the visited file on disk.
2836 This undoes all changes since the file was visited or saved.
2837 With a prefix argument, offer to revert from latest auto-save file, if
2838 that is more recent than the visited file.
2840 This command also works for special buffers that contain text which
2841 doesn't come from a file, but reflects some other data base instead:
2842 for example, Dired buffers and buffer-list buffers. In these cases,
2843 it reconstructs the buffer contents from the appropriate data base.
2845 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2846 to revert from the auto-save file when this is nil. Note that the
2847 sense of this argument is the reverse of the prefix argument, for the
2848 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2851 Optional second argument NOCONFIRM means don't ask for confirmation at
2852 all. (The local variable `revert-without-query', if non-nil, prevents
2855 Optional third argument PRESERVE-MODES non-nil means don't alter
2856 the files modes. Normally we reinitialize them using `normal-mode'.
2858 If the value of `revert-buffer-function' is non-nil, it is called to
2859 do all the work for this command. Otherwise, the hooks
2860 `before-revert-hook' and `after-revert-hook' are run at the beginning
2861 and the end, and if `revert-buffer-insert-file-contents-function' is
2862 non-nil, it is called instead of rereading visited file contents."
2864 ;; I admit it's odd to reverse the sense of the prefix argument, but
2865 ;; there is a lot of code out there which assumes that the first
2866 ;; argument should be t to avoid consulting the auto-save file, and
2867 ;; there's no straightforward way to encourage authors to notice a
2868 ;; reversal of the argument sense. So I'm just changing the user
2869 ;; interface, but leaving the programmatic interface the same.
2870 (interactive (list (not current-prefix-arg)))
2871 (if revert-buffer-function
2872 (funcall revert-buffer-function ignore-auto noconfirm)
2873 (let* ((auto-save-p (and (not ignore-auto)
2874 (recent-auto-save-p)
2875 buffer-auto-save-file-name
2876 (file-readable-p buffer-auto-save-file-name)
2878 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2879 (file-name (if auto-save-p
2880 buffer-auto-save-file-name
2882 (cond ((null file-name)
2883 (error "Buffer does not seem to be associated with any file"))
2885 (and (not (buffer-modified-p))
2886 (let ((tail revert-without-query)
2889 (if (string-match (car tail) file-name)
2891 (setq tail (cdr tail)))
2893 (yes-or-no-p (format "Revert buffer from file %s? "
2895 (run-hooks 'before-revert-hook)
2896 ;; If file was backed up but has changed since,
2897 ;; we shd make another backup.
2898 (and (not auto-save-p)
2899 (not (verify-visited-file-modtime (current-buffer)))
2900 (setq buffer-backed-up nil))
2901 ;; Get rid of all undo records for this buffer.
2902 (or (eq buffer-undo-list t)
2903 (setq buffer-undo-list nil))
2904 ;; Effectively copy the after-revert-hook status,
2905 ;; since after-find-file will clobber it.
2906 (let ((global-hook (default-value 'after-revert-hook))
2907 (local-hook-p (local-variable-p 'after-revert-hook))
2908 (local-hook (and (local-variable-p 'after-revert-hook)
2909 after-revert-hook)))
2910 (let (buffer-read-only
2911 ;; Don't make undo records for the reversion.
2912 (buffer-undo-list t))
2913 (if revert-buffer-insert-file-contents-function
2914 (funcall revert-buffer-insert-file-contents-function
2915 file-name auto-save-p)
2916 (if (not (file-exists-p file-name))
2917 (error "File %s no longer exists!" file-name))
2918 ;; Bind buffer-file-name to nil
2919 ;; so that we don't try to lock the file.
2920 (let ((buffer-file-name nil))
2924 (let ((coding-system-for-read
2925 ;; Auto-saved file shoule be read without
2926 ;; any code conversion.
2927 (if auto-save-p 'no-conversion
2928 coding-system-for-read)))
2929 ;; Note that this preserves point in an intelligent way.
2930 (insert-file-contents file-name (not auto-save-p)
2932 ;; Recompute the truename in case changes in symlinks
2933 ;; have changed the truename.
2934 (setq buffer-file-truename
2935 (abbreviate-file-name (file-truename buffer-file-name)))
2936 (after-find-file nil nil t t preserve-modes)
2937 ;; Run after-revert-hook as it was before we reverted.
2938 (setq-default revert-buffer-internal-hook global-hook)
2941 (make-local-variable 'revert-buffer-internal-hook)
2942 (setq revert-buffer-internal-hook local-hook))
2943 (kill-local-variable 'revert-buffer-internal-hook))
2944 (run-hooks 'revert-buffer-internal-hook))
2947 (defun recover-file (file)
2948 "Visit file FILE, but get contents from its last auto-save file."
2949 ;; Actually putting the file name in the minibuffer should be used
2951 ;; Not just because users often use the default.
2952 (interactive "FRecover file: ")
2953 (setq file (expand-file-name file))
2954 (if (auto-save-file-name-p (file-name-nondirectory file))
2955 (error "%s is an auto-save file" file))
2956 (let ((file-name (let ((buffer-file-name file))
2957 (make-auto-save-file-name))))
2958 (cond ((if (file-exists-p file)
2959 (not (file-newer-than-file-p file-name file))
2960 (not (file-exists-p file-name)))
2961 (error "Auto-save file %s not current" file-name))
2962 ((save-window-excursion
2963 (if (not (memq system-type '(vax-vms windows-nt)))
2964 (with-output-to-temp-buffer "*Directory*"
2965 (buffer-disable-undo standard-output)
2966 (call-process "ls" nil standard-output nil
2967 (if (file-symlink-p file) "-lL" "-l")
2969 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2970 (switch-to-buffer (find-file-noselect file t))
2971 (let ((buffer-read-only nil)
2972 ;; Keep the current buffer-file-coding-system.
2973 (coding-system buffer-file-coding-system)
2974 ;; Auto-saved file shoule be read without any code conversion.
2975 (coding-system-for-read 'no-conversion))
2977 (insert-file-contents file-name nil)
2978 (set-buffer-file-coding-system coding-system))
2979 (after-find-file nil nil t))
2980 (t (error "Recover-file cancelled")))))
2982 (defun recover-session ()
2983 "Recover auto save files from a previous Emacs session.
2984 This command first displays a Dired buffer showing you the
2985 previous sessions that you could recover from.
2986 To choose one, move point to the proper line and then type C-c C-c.
2987 Then you'll be asked about a number of files to recover."
2989 (if (null auto-save-list-file-prefix)
2990 (error "You set `auto-save-list-file-prefix' to disable making session files"))
2991 (let ((ls-lisp-support-shell-wildcards t))
2992 (dired (concat auto-save-list-file-prefix "*")
2993 (concat dired-listing-switches "t")))
2995 (goto-char (point-min))
2996 (or (looking-at " Move to the session you want to recover,")
2997 (let ((inhibit-read-only t))
2998 ;; Each line starts with a space
2999 ;; so that Font Lock mode won't highlight the first character.
3000 (insert " Move to the session you want to recover,\n"
3001 " then type C-c C-c to select it.\n\n"
3002 " You can also delete some of these files;\n"
3003 " type d on a line to mark that file for deletion.\n\n"))))
3004 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
3005 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
3007 (defun recover-session-finish ()
3008 "Choose one saved session to recover auto-save files from.
3009 This command is used in the special Dired buffer created by
3010 \\[recover-session]."
3012 ;; Get the name of the session file to recover from.
3013 (let ((file (dired-get-filename))
3015 (buffer (get-buffer-create " *recover*")))
3017 (dired-do-flagged-delete t)
3020 ;; Read in the auto-save-list file.
3023 (insert-file-contents file)
3024 ;; Loop thru the text of that file
3025 ;; and get out the names of the files to recover.
3027 (let (thisfile autofile)
3029 ;; This is a pair of lines for a non-file-visiting buffer.
3030 ;; Get the auto-save file name and manufacture
3031 ;; a "visited file name" from that.
3035 (buffer-substring-no-properties
3043 (file-name-nondirectory autofile)
3045 (file-name-directory autofile)))
3047 ;; This pair of lines is a file-visiting
3048 ;; buffer. Use the visited file name.
3051 (buffer-substring-no-properties
3052 (point) (progn (end-of-line) (point))))
3055 (buffer-substring-no-properties
3056 (point) (progn (end-of-line) (point))))
3058 ;; Ignore a file if its auto-save file does not exist now.
3059 (if (file-exists-p autofile)
3060 (setq files (cons thisfile files)))))
3061 (setq files (nreverse files))
3062 ;; The file contains a pair of line for each auto-saved buffer.
3063 ;; The first line of the pair contains the visited file name
3064 ;; or is empty if the buffer was not visiting a file.
3065 ;; The second line is the auto-save file name.
3067 (map-y-or-n-p "Recover %s? "
3070 (save-excursion (recover-file file))
3072 "Failed to recover `%s'" file)))
3074 '("file" "files" "recover"))
3075 (message "No files can be recovered from this session now")))
3076 (kill-buffer buffer))))
3078 (defun kill-some-buffers (&optional list)
3079 "For each buffer in LIST, ask whether to kill it.
3080 LIST defaults to all existing live buffers."
3083 (setq list (buffer-list)))
3085 (let* ((buffer (car list))
3086 (name (buffer-name buffer)))
3087 (and (not (string-equal name ""))
3088 (/= (aref name 0) ? )
3090 (format "Buffer %s %s. Kill? "
3092 (if (buffer-modified-p buffer)
3093 "HAS BEEN EDITED" "is unmodified")))
3094 (kill-buffer buffer)))
3095 (setq list (cdr list))))
3097 (defun auto-save-mode (arg)
3098 "Toggle auto-saving of contents of current buffer.
3099 With prefix argument ARG, turn auto-saving on if positive, else off."
3101 (setq buffer-auto-save-file-name
3103 (or (not buffer-auto-save-file-name)
3104 ;; If auto-save is off because buffer has shrunk,
3105 ;; then toggling should turn it on.
3106 (< buffer-saved-size 0))
3107 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
3108 (if (and buffer-file-name auto-save-visited-file-name
3109 (not buffer-read-only))
3111 (make-auto-save-file-name))))
3112 ;; If -1 was stored here, to temporarily turn off saving,
3114 (and (< buffer-saved-size 0)
3115 (setq buffer-saved-size 0))
3117 (message "Auto-save %s (in this buffer)"
3118 (if buffer-auto-save-file-name "on" "off")))
3119 buffer-auto-save-file-name)
3121 (defun rename-auto-save-file ()
3122 "Adjust current buffer's auto save file name for current conditions.
3123 Also rename any existing auto save file, if it was made in this session."
3124 (let ((osave buffer-auto-save-file-name))
3125 (setq buffer-auto-save-file-name
3126 (make-auto-save-file-name))
3127 (if (and osave buffer-auto-save-file-name
3128 (not (string= buffer-auto-save-file-name buffer-file-name))
3129 (not (string= buffer-auto-save-file-name osave))
3130 (file-exists-p osave)
3131 (recent-auto-save-p))
3132 (rename-file osave buffer-auto-save-file-name t))))
3134 (defun make-auto-save-file-name ()
3135 "Return file name to use for auto-saves of current buffer.
3136 Does not consider `auto-save-visited-file-name' as that variable is checked
3137 before calling this function. You can redefine this for customization.
3138 See also `auto-save-file-name-p'."
3139 (if buffer-file-name
3140 (if (and (eq system-type 'ms-dos)
3141 (not (msdos-long-file-names)))
3142 (let ((fn (file-name-nondirectory buffer-file-name)))
3143 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
3144 (concat (file-name-directory buffer-file-name)
3145 "#" (match-string 1 fn)
3146 "." (match-string 3 fn) "#"))
3147 (concat (file-name-directory buffer-file-name)
3149 (file-name-nondirectory buffer-file-name)
3152 ;; Deal with buffers that don't have any associated files. (Mail
3153 ;; mode tends to create a good number of these.)
3155 (let ((buffer-name (buffer-name))
3157 ;; Eliminate all slashes and backslashes by
3158 ;; replacing them with sequences that start with %.
3159 ;; Quote % also, to keep distinct names distinct.
3160 (while (string-match "[/\\%]" buffer-name limit)
3161 (let* ((character (aref buffer-name (match-beginning 0)))
3163 (cond ((eq character ?%) "%%")
3164 ((eq character ?/) "%+")
3165 ((eq character ?\\) "%-"))))
3166 (setq buffer-name (replace-match replacement t t buffer-name))
3167 (setq limit (1+ (match-end 0)))))
3168 ;; Generate the file name.
3170 (format "#%s#%s#" buffer-name (make-temp-name ""))
3171 ;; Try a few alternative directories, to get one we can write it.
3173 ((file-writable-p default-directory) default-directory)
3174 ((file-writable-p "/var/tmp/") "/var/tmp/")
3177 (defun auto-save-file-name-p (filename)
3178 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
3179 FILENAME should lack slashes. You can redefine this for customization."
3180 (string-match "^#.*#$" filename))
3182 (defun wildcard-to-regexp (wildcard)
3183 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
3184 The generated regexp will match a filename iff the filename
3185 matches that wildcard according to shell rules. Only wildcards known
3186 by `sh' are supported."
3187 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
3188 ;; Copy the initial run of non-special characters.
3189 (result (substring wildcard 0 i))
3190 (len (length wildcard)))
3191 ;; If no special characters, we're almost done.
3194 (let ((ch (aref wildcard i))
3202 (eq (aref wildcard (1+ i)) ?\]))
3204 ((eq ch ?\[) ; [...] maps to regexp char class
3209 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
3212 (if (eq (aref wildcard i) ?\])
3217 ((eq (aref wildcard i) ?^)
3218 ;; Found "[^". Insert a `\0' character
3219 ;; (which cannot happen in a filename)
3220 ;; into the character class, so that `^'
3221 ;; is not the first character after `[',
3222 ;; and thus non-special in a regexp.
3226 ((eq (aref wildcard i) ?\])
3227 ;; I don't think `]' can appear in a
3228 ;; character class in a wildcard, but
3229 ;; let's be general here.
3234 (prog1 ; copy everything upto next `]'.
3237 (setq j (string-match
3239 (setq i (if j (1- j) (1- len)))))))
3241 ((eq ch ?*) "[^\000]*")
3245 ((eq ch ?\\) "\\\\") ; probably cannot happen...
3246 ((eq ch ??) "[^\000]")
3247 (t (char-to-string ch)))))
3249 ;; Shell wildcards should match the entire filename,
3250 ;; not its part. Make the regexp say so.
3251 (concat "\\`" result "\\'")))
3253 (defcustom list-directory-brief-switches
3254 (if (eq system-type 'vax-vms) "" "-CF")
3255 "*Switches for `list-directory' to pass to `ls' for brief listing."
3259 (defcustom list-directory-verbose-switches
3260 (if (eq system-type 'vax-vms)
3261 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
3263 "*Switches for `list-directory' to pass to `ls' for verbose listing."
3267 (defun file-expand-wildcards (pattern &optional full)
3268 "Expand wildcard pattern PATTERN.
3269 This returns a list of file names which match the pattern.
3271 If PATTERN is written as an absolute relative file name,
3272 the values are absolute also.
3274 If PATTERN is written as a relative file name, it is interpreted
3275 relative to the current default directory, `default-directory'.
3276 The file names returned are normally also relative to the current
3277 default directory. However, if FULL is non-nil, they are absolute."
3278 (let* ((nondir (file-name-nondirectory pattern))
3279 (dirpart (file-name-directory pattern))
3280 ;; A list of all dirs that DIRPART specifies.
3281 ;; This can be more than one dir
3282 ;; if DIRPART contains wildcards.
3283 (dirs (if (and dirpart (string-match "[[*?]" dirpart))
3284 (mapcar 'file-name-as-directory
3285 (file-expand-wildcards (directory-file-name dirpart)))
3289 (when (or (null (car dirs)) ; Possible if DIRPART is not wild.
3290 (file-directory-p (directory-file-name (car dirs))))
3291 (let ((this-dir-contents
3292 ;; Filter out "." and ".."
3294 (mapcar #'(lambda (name)
3295 (unless (string-match "\\`\\.\\.?\\'"
3296 (file-name-nondirectory name))
3298 (directory-files (or (car dirs) ".") full
3299 (wildcard-to-regexp nondir))))))
3302 (if (and (car dirs) (not full))
3303 (mapcar (function (lambda (name) (concat (car dirs) name)))
3307 (setq dirs (cdr dirs)))
3310 (defun list-directory (dirname &optional verbose)
3311 "Display a list of files in or matching DIRNAME, a la `ls'.
3312 DIRNAME is globbed by the shell if necessary.
3313 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
3314 Actions controlled by variables `list-directory-brief-switches'
3315 and `list-directory-verbose-switches'."
3316 (interactive (let ((pfx current-prefix-arg))
3317 (list (read-file-name (if pfx "List directory (verbose): "
3318 "List directory (brief): ")
3319 nil default-directory nil)
3321 (let ((switches (if verbose list-directory-verbose-switches
3322 list-directory-brief-switches)))
3323 (or dirname (setq dirname default-directory))
3324 (setq dirname (expand-file-name dirname))
3325 (with-output-to-temp-buffer "*Directory*"
3326 (buffer-disable-undo standard-output)
3327 (princ "Directory ")
3331 (set-buffer "*Directory*")
3332 (setq default-directory
3333 (if (file-directory-p dirname)
3334 (file-name-as-directory dirname)
3335 (file-name-directory dirname)))
3336 (let ((wildcard (not (file-directory-p dirname))))
3337 (insert-directory dirname switches wildcard (not wildcard)))))))
3339 (defvar insert-directory-program "ls"
3340 "Absolute or relative name of the `ls' program used by `insert-directory'.")
3343 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
3344 ;; FULL-DIRECTORY-P is nil.
3345 ;; The single line of output must display FILE's name as it was
3346 ;; given, namely, an absolute path name.
3347 ;; - must insert exactly one line for each file if WILDCARD or
3348 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
3349 ;; before the file lines, plus optional text after the file lines.
3350 ;; Lines are delimited by "\n", so filenames containing "\n" are not
3352 ;; File lines should display the basename.
3353 ;; - must be consistent with
3354 ;; - functions dired-move-to-filename, (these two define what a file line is)
3355 ;; dired-move-to-end-of-filename,
3356 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
3357 ;; dired-insert-headerline
3358 ;; dired-after-subdir-garbage (defines what a "total" line is)
3359 ;; - variable dired-subdir-regexp
3360 (defun insert-directory (file switches &optional wildcard full-directory-p)
3361 "Insert directory listing for FILE, formatted according to SWITCHES.
3362 Leaves point after the inserted text.
3363 SWITCHES may be a string of options, or a list of strings.
3364 Optional third arg WILDCARD means treat FILE as shell wildcard.
3365 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
3366 switches do not contain `d', so that a full listing is expected.
3368 This works by running a directory listing program
3369 whose name is in the variable `insert-directory-program'.
3370 If WILDCARD, it also runs the shell specified by `shell-file-name'."
3371 ;; We need the directory in order to find the right handler.
3372 (let ((handler (find-file-name-handler (expand-file-name file)
3373 'insert-directory)))
3375 (funcall handler 'insert-directory file switches
3376 wildcard full-directory-p)
3377 (if (eq system-type 'vax-vms)
3378 (vms-read-directory file switches (current-buffer))
3379 (let* ((coding-system-for-read
3380 (and enable-multibyte-characters
3381 (or file-name-coding-system
3382 default-file-name-coding-system)))
3383 ;; This is to control encoding the arguments in call-process.
3384 (coding-system-for-write coding-system-for-read)
3387 ;; Run ls in the directory of the file pattern we asked for.
3388 (let ((default-directory
3389 (if (file-name-absolute-p file)
3390 (file-name-directory file)
3391 (file-name-directory (expand-file-name file))))
3392 (pattern (file-name-nondirectory file))
3394 ;; Quote some characters that have special meanings in shells;
3395 ;; but don't quote the wildcards--we want them to be special.
3396 ;; We also currently don't quote the quoting characters
3397 ;; in case people want to use them explicitly to quote
3398 ;; wildcard characters.
3399 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
3401 (concat (substring pattern 0 (match-beginning 0))
3403 (substring pattern (match-beginning 0)))
3404 beg (1+ (match-end 0))))
3405 (call-process shell-file-name nil t nil
3406 "-c" (concat "\\";; Disregard shell aliases!
3407 insert-directory-program
3409 (if (stringp switches)
3411 (mapconcat 'identity switches " "))
3414 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
3415 ;; directory if FILE is a symbolic link.
3416 (apply 'call-process
3417 insert-directory-program nil t nil
3419 (if (listp switches)
3420 (setq list switches)
3421 (if (not (equal switches ""))
3423 ;; Split the switches at any spaces
3424 ;; so we can pass separate options as separate args.
3425 (while (string-match " " switches)
3426 (setq list (cons (substring switches 0 (match-beginning 0))
3428 switches (substring switches (match-end 0))))
3429 (setq list (nreverse (cons switches list))))))
3431 ;; Avoid lossage if FILE starts with `-'.
3434 (if (string-match "\\`~" file)
3435 (setq file (expand-file-name file)))
3437 (if full-directory-p
3438 (concat (file-name-as-directory file) ".")
3441 ;; We get here if ls failed.
3442 ;; Access the file to get a suitable error.
3443 (access-file file "Reading directory")
3444 ;; Replace "total" with "used", to avoid confusion.
3445 ;; Add in the amount of free space.
3447 (goto-char (point-min))
3448 (when (re-search-forward "^total" nil t)
3449 (replace-match "used")
3453 (call-process "df" nil t nil ".")
3454 (goto-char (point-min))
3456 (skip-chars-forward "^ \t")
3458 (let ((end (point)))
3460 (setq available (buffer-substring (point) end))))
3461 (insert " available " available))))))))))
3463 (defvar kill-emacs-query-functions nil
3464 "Functions to call with no arguments to query about killing Emacs.
3465 If any of these functions returns nil, killing Emacs is cancelled.
3466 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
3467 but `kill-emacs', the low level primitive, does not.
3468 See also `kill-emacs-hook'.")
3470 (defun save-buffers-kill-emacs (&optional arg)
3471 "Offer to save each buffer, then kill this Emacs process.
3472 With prefix arg, silently save all file-visiting buffers, then kill."
3474 (save-some-buffers arg t)
3475 (and (or (not (memq t (mapcar (function
3476 (lambda (buf) (and (buffer-file-name buf)
3477 (buffer-modified-p buf))))
3479 (yes-or-no-p "Modified buffers exist; exit anyway? "))
3480 (or (not (fboundp 'process-list))
3481 ;; process-list is not defined on VMS.
3482 (let ((processes (process-list))
3485 (and (memq (process-status (car processes)) '(run stop open))
3486 (let ((val (process-kill-without-query (car processes))))
3487 (process-kill-without-query (car processes) val)
3490 (setq processes (cdr processes)))
3493 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
3494 ;; Query the user for other things, perhaps.
3495 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
3498 ;; We use /: as a prefix to "quote" a file name
3499 ;; so that magic file name handlers will not apply to it.
3501 (setq file-name-handler-alist
3502 (cons '("\\`/:" . file-name-non-special)
3503 file-name-handler-alist))
3505 ;; We depend on being the last handler on the list,
3506 ;; so that anything else which does need handling
3507 ;; has been handled already.
3508 ;; So it is safe for us to inhibit *all* magic file name handlers.
3510 (defun file-name-non-special (operation &rest arguments)
3511 (let ((file-name-handler-alist nil)
3513 (if (eq operation 'insert-directory)
3514 (directory-file-name
3516 (unhandled-file-name-directory default-directory)))
3518 ;; Get a list of the indices of the args which are file names.
3520 (cdr (or (assq operation
3521 ;; The first four are special because they
3522 ;; return a file name. We want to include the /:
3523 ;; in the return value.
3524 ;; So just avoid stripping it in the first place.
3525 '((expand-file-name . nil)
3526 ;; `identity' means just return the first arg
3527 ;; as stripped of its quoting.
3528 (substitute-in-file-name . identity)
3529 (file-name-directory . nil)
3530 (file-name-as-directory . nil)
3531 (directory-file-name . nil)
3532 (file-name-completion 0 1)
3533 (file-name-all-completions 0 1)
3536 (make-symbolic-link 0 1)
3537 (add-name-to-file 0 1)))
3538 ;; For all other operations, treat the first argument only
3539 ;; as the file name.
3541 ;; Copy ARGUMENTS so we can replace elements in it.
3542 (arguments (copy-sequence arguments)))
3543 ;; Strip off the /: from the file names that have this handler.
3545 (while (consp file-arg-indices)
3546 (let ((pair (nthcdr (car file-arg-indices) arguments)))
3548 (string-match "\\`/:" (car pair))
3550 (if (= (length (car pair)) 2)
3552 (substring (car pair) 2)))))
3553 (setq file-arg-indices (cdr file-arg-indices))))
3554 (if (eq file-arg-indices 'identity)
3556 (apply operation arguments))))
3558 (define-key ctl-x-map "\C-f" 'find-file)
3559 (define-key ctl-x-map "\C-r" 'find-file-read-only)
3560 (define-key ctl-x-map "\C-v" 'find-alternate-file)
3561 (define-key ctl-x-map "\C-s" 'save-buffer)
3562 (define-key ctl-x-map "s" 'save-some-buffers)
3563 (define-key ctl-x-map "\C-w" 'write-file)
3564 (define-key ctl-x-map "i" 'insert-file)
3565 (define-key esc-map "~" 'not-modified)
3566 (define-key ctl-x-map "\C-d" 'list-directory)
3567 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
3569 (define-key ctl-x-4-map "f" 'find-file-other-window)
3570 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
3571 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
3572 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
3573 (define-key ctl-x-4-map "\C-o" 'display-buffer)
3575 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
3576 (define-key ctl-x-5-map "f" 'find-file-other-frame)
3577 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
3578 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
3580 ;;; files.el ends here