1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985, 86, 87, 92, 93, 94, 1995 Free Software Foundation, Inc.
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to
21 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25 ;; Defines most of Emacs's file- and directory-handling functions,
26 ;; including basic file visiting, backup generation, link handling,
27 ;; ITS-id version control, load- and write-hook handling, and the like.
31 (defconst delete-auto-save-files t
32 "*Non-nil means delete auto-save file when a buffer is saved or killed.")
34 (defconst directory-abbrev-alist
36 "*Alist of abbreviations for file directories.
37 A list of elements of the form (FROM . TO), each meaning to replace
38 FROM with TO when it appears in a directory name. This replacement is
39 done when setting up the default directory of a newly visited file.
40 *Every* FROM string should start with `^'.
42 Do not use `~' in the TO strings.
43 They should be ordinary absolute directory names.
45 Use this feature when you have directories which you normally refer to
46 via absolute symbolic links. Make TO the name of the link, and FROM
47 the name it is linked to.")
49 ;;; Turn off backup files on VMS since it has version numbers.
50 (defconst make-backup-files (not (eq system-type 'vax-vms))
51 "*Non-nil means make a backup of a file the first time it is saved.
52 This can be done by renaming the file or by copying.
54 Renaming means that Emacs renames the existing file so that it is a
55 backup file, then writes the buffer into a new file. Any other names
56 that the old file had will now refer to the backup file. The new file
57 is owned by you and its group is defaulted.
59 Copying means that Emacs copies the existing file into the backup
60 file, then writes the buffer on top of the existing file. Any other
61 names that the old file had will now refer to the new (edited) file.
62 The file's owner and group are unchanged.
64 The choice of renaming or copying is controlled by the variables
65 `backup-by-copying', `backup-by-copying-when-linked' and
66 `backup-by-copying-when-mismatch'. See also `backup-inhibited'.")
68 ;; Do this so that local variables based on the file name
69 ;; are not overridden by the major mode.
70 (defvar backup-inhibited nil
71 "Non-nil means don't make a backup, regardless of the other parameters.
72 This variable is intended for use by making it local to a buffer.
73 But it is local only if you make it local.")
74 (put 'backup-inhibited 'permanent-local t)
76 (defconst backup-by-copying nil
77 "*Non-nil means always use copying to create backup files.
78 See documentation of variable `make-backup-files'.")
80 (defconst backup-by-copying-when-linked nil
81 "*Non-nil means use copying to create backups for files with multiple names.
82 This causes the alternate names to refer to the latest version as edited.
83 This variable is relevant only if `backup-by-copying' is nil.")
85 (defconst backup-by-copying-when-mismatch nil
86 "*Non-nil means create backups by copying if this preserves owner or group.
87 Renaming may still be used (subject to control of other variables)
88 when it would not result in changing the owner or group of the file;
89 that is, for files which are owned by you and whose group matches
90 the default for a new file created there by you.
91 This variable is relevant only if `backup-by-copying' is nil.")
93 (defvar backup-enable-predicate
95 (or (< (length name) 5)
96 (not (string-equal "/tmp/" (substring name 0 5)))))
97 "Predicate that looks at a file name and decides whether to make backups.
98 Called with an absolute file name as argument, it returns t to enable backup.")
100 (defconst buffer-offer-save nil
101 "*Non-nil in a buffer means offer to save the buffer on exit
102 even if the buffer is not visiting a file.
103 Automatically local in all buffers.")
104 (make-variable-buffer-local 'buffer-offer-save)
106 (defconst find-file-existing-other-name nil
107 "*Non-nil means find a file under alternative names, in existing buffers.
108 This means if any existing buffer is visiting the file you want
109 under another name, you get the existing buffer instead of a new buffer.")
111 (defconst find-file-visit-truename nil
112 "*Non-nil means visit a file under its truename.
113 The truename of a file is found by chasing all links
114 both at the file level and at the levels of the containing directories.")
116 (defvar buffer-file-truename nil
117 "The abbreviated truename of the file visited in the current buffer.
118 That is, (abbreviate-file-name (file-truename buffer-file-name)).
119 This variable is automatically local in all buffers, when non-nil.")
120 (make-variable-buffer-local 'buffer-file-truename)
121 (put 'buffer-file-truename 'permanent-local t)
123 (defvar buffer-file-number nil
124 "The device number and file number of the file visited in the current buffer.
125 The value is a list of the form (FILENUM DEVNUM).
126 This pair of numbers uniquely identifies the file.
127 If the buffer is visiting a new file, the value is nil.")
128 (make-variable-buffer-local 'buffer-file-number)
129 (put 'buffer-file-number 'permanent-local t)
131 (defconst file-precious-flag nil
132 "*Non-nil means protect against I/O errors while saving files.
133 Some modes set this non-nil in particular buffers.
135 This feature works by writing the new contents into a temporary file
136 and then renaming the temporary file to replace the original.
137 In this way, any I/O error in writing leaves the original untouched,
138 and there is never any instant where the file is nonexistent.
140 Note that this feature forces backups to be made by copying.
141 Yet, at the same time, saving a precious file
142 breaks any hard links between it and other files.")
144 (defvar version-control nil
145 "*Control use of version numbers for backup files.
146 t means make numeric backup versions unconditionally.
147 nil means make them for files that have some already.
148 `never' means do not make them.")
150 (defvar dired-kept-versions 2
151 "*When cleaning directory, number of versions to keep.")
153 (defvar delete-old-versions nil
154 "*If t, delete excess backup versions silently.
155 If nil, ask confirmation. Any other value prevents any trimming.")
157 (defvar kept-old-versions 2
158 "*Number of oldest versions to keep when a new numbered backup is made.")
160 (defvar kept-new-versions 2
161 "*Number of newest versions to keep when a new numbered backup is made.
162 Includes the new backup. Must be > 0")
164 (defconst require-final-newline nil
165 "*Value of t says silently ensure a file ends in a newline when it is saved.
166 Non-nil but not t says ask user whether to add a newline when there isn't one.
167 nil means don't add newlines.")
169 (defconst auto-save-default t
170 "*Non-nil says by default do auto-saving of every file-visiting buffer.")
172 (defconst auto-save-visited-file-name nil
173 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
174 Normally auto-save files are written under other names.")
176 (defconst save-abbrevs nil
177 "*Non-nil means save word abbrevs too when files are saved.
178 Loading an abbrev file sets this to t.")
180 (defconst find-file-run-dired t
181 "*Non-nil says run dired if `find-file' is given the name of a directory.")
183 ;;;It is not useful to make this a local variable.
184 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
185 (defvar find-file-not-found-hooks nil
186 "List of functions to be called for `find-file' on nonexistent file.
187 These functions are called as soon as the error is detected.
188 `buffer-file-name' is already set up.
189 The functions are called in the order given until one of them returns non-nil.")
191 ;;;It is not useful to make this a local variable.
192 ;;;(put 'find-file-hooks 'permanent-local t)
193 (defvar find-file-hooks nil
194 "List of functions to be called after a buffer is loaded from a file.
195 The buffer's local variables (if any) will have been processed before the
196 functions are called.")
198 (defvar write-file-hooks nil
199 "List of functions to be called before writing out a buffer to a file.
200 If one of them returns non-nil, the file is considered already written
201 and the rest are not called.
202 These hooks are considered to pertain to the visited file.
203 So this list is cleared if you change the visited file name.
204 See also `write-contents-hooks'.
205 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.")
206 ;;; However, in case someone does make it local...
207 (put 'write-file-hooks 'permanent-local t)
209 (defvar local-write-file-hooks nil
210 "Just like `write-file-hooks', except intended for per-buffer use.
211 The functions in this list are called before the ones in
212 `write-file-hooks'.")
213 (make-variable-buffer-local 'local-write-file-hooks)
214 (put 'local-write-file-hooks 'permanent-local t)
216 (defvar write-contents-hooks nil
217 "List of functions to be called before writing out a buffer to a file.
218 If one of them returns non-nil, the file is considered already written
219 and the rest are not called.
220 These hooks are considered to pertain to the buffer's contents,
221 not to the particular visited file; thus, `set-visited-file-name' does
222 not clear this variable, but changing the major mode does clear it.
223 See also `write-file-hooks'.")
225 (defconst enable-local-variables t
226 "*Control use of local-variables lists in files you visit.
227 The value can be t, nil or something else.
228 A value of t means local-variables lists are obeyed;
229 nil means they are ignored; anything else means query.
231 The command \\[normal-mode] always obeys local-variables lists
232 and ignores this variable.")
234 (defconst enable-local-eval 'maybe
235 "*Control processing of the \"variable\" `eval' in a file's local variables.
236 The value can be t, nil or something else.
237 A value of t means obey `eval' variables;
238 nil means ignore them; anything else means query.
240 The command \\[normal-mode] always obeys local-variables lists
241 and ignores this variable.")
243 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
244 (or (fboundp 'lock-buffer)
245 (defalias 'lock-buffer 'ignore))
246 (or (fboundp 'unlock-buffer)
247 (defalias 'unlock-buffer 'ignore))
249 ;; This hook function provides support for ange-ftp host name
250 ;; completion. It runs the usual ange-ftp hook, but only for
251 ;; completion operations. Having this here avoids the need
252 ;; to load ange-ftp when it's not really in use.
253 (defun ange-ftp-completion-hook-function (op &rest args)
254 (if (memq op '(file-name-completion file-name-all-completions))
255 (apply 'ange-ftp-hook-function op args)
256 (let ((inhibit-file-name-handlers
257 (cons 'ange-ftp-completion-hook-function
258 (and (eq inhibit-file-name-operation op)
259 inhibit-file-name-handlers)))
260 (inhibit-file-name-operation op))
264 "Show the current default directory."
266 (message "Directory %s" default-directory))
269 "Value of the CDPATH environment variable, as a list.
270 Not actually set up until the first time you you use it.")
272 (defvar path-separator ":"
273 "Character used to separate concatenated paths.")
275 (defun parse-colon-path (cd-path)
276 "Explode a colon-separated list of paths into a string list."
278 (let (cd-prefix cd-list (cd-start 0) cd-colon)
279 (setq cd-path (concat cd-path path-separator))
280 (while (setq cd-colon (string-match path-separator cd-path cd-start))
283 (list (if (= cd-start cd-colon)
285 (substitute-in-file-name
286 (file-name-as-directory
287 (substring cd-path cd-start cd-colon)))))))
288 (setq cd-start (+ cd-colon 1)))
291 (defun cd-absolute (dir)
292 "Change current directory to given absolute file name DIR."
293 ;; Put the name into directory syntax now,
294 ;; because otherwise expand-file-name may give some bad results.
295 (if (not (eq system-type 'vax-vms))
296 (setq dir (file-name-as-directory dir)))
297 (setq dir (abbreviate-file-name (expand-file-name dir)))
298 (if (not (file-directory-p dir))
299 (error "%s is not a directory" dir)
300 (if (file-executable-p dir)
301 (setq default-directory dir)
302 (error "Cannot cd to %s: Permission denied" dir))))
305 "Make DIR become the current buffer's default directory.
306 If your environment includes a `CDPATH' variable, try each one of that
307 colon-separated list of directories when resolving a relative directory name."
308 (interactive "FChange default directory: ")
309 (if (file-name-absolute-p dir)
310 (cd-absolute (expand-file-name dir))
312 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
313 (setq cd-path (or trypath (list "./")))))
314 (if (not (catch 'found
316 (function (lambda (x)
317 (let ((f (expand-file-name (concat x dir))))
318 (if (file-directory-p f)
321 (throw 'found t))))))
324 (error "No such directory found via CDPATH environment variable"))))
326 (defun load-file (file)
327 "Load the Lisp file named FILE."
328 (interactive "fLoad file: ")
329 (load (expand-file-name file) nil nil t))
331 (defun load-library (library)
332 "Load the library named LIBRARY.
333 This is an interface to the function `load'."
334 (interactive "sLoad library: ")
337 (defun file-local-copy (file &optional buffer)
338 "Copy the file FILE into a temporary file on this machine.
339 Returns the name of the local copy, or nil, if FILE is directly
341 (let ((handler (find-file-name-handler file 'file-local-copy)))
343 (funcall handler 'file-local-copy file)
346 (defun file-truename (filename &optional counter prev-dirs)
347 "Return the truename of FILENAME, which should be absolute.
348 The truename of a file name is found by chasing symbolic links
349 both at the level of the file and at the level of the directories
350 containing it, until no links are left at any level.
352 The arguments COUNTER and PREV-DIRS are used only in recursive calls.
353 Do not specify them in other calls."
354 ;; COUNTER can be a cons cell whose car is the count of how many more links
355 ;; to chase before getting an error.
356 ;; PREV-DIRS can be a cons cell whose car is an alist
357 ;; of truenames we've just recently computed.
359 ;; I don't understand the reason for these tests. To avoid string-match?
360 ;; Something like (string-match "\\`\\'\\|~" filename) would do the same.
361 ;; The last test looks dubious, maybe `+' is meant here? --simon.
362 (if (or (string= filename "") (string= filename "~")
363 (and (string= (substring filename 0 1) "~")
364 (string-match "~[^/]*" filename)))
366 (setq filename (expand-file-name filename))
367 (if (string= filename "")
368 (setq filename "/"))))
369 (or counter (setq counter (list 100)))
371 ;; For speed, remove the ange-ftp completion handler from the list.
372 ;; We know it's not needed here.
373 ;; For even more speed, do this only on the outermost call.
374 (file-name-handler-alist
375 (if prev-dirs file-name-handler-alist
376 (let ((tem (copy-sequence file-name-handler-alist)))
377 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
378 (or prev-dirs (setq prev-dirs (list nil)))
379 ;; If this file directly leads to a link, process that iteratively
380 ;; so that we don't use lots of stack.
382 (setcar counter (1- (car counter)))
383 (if (< (car counter) 0)
384 (error "Apparent cycle of symbolic links for %s" filename))
385 (let ((handler (find-file-name-handler filename 'file-truename)))
386 ;; For file name that has a special handler, call handler.
387 ;; This is so that ange-ftp can save time by doing a no-op.
389 (setq filename (funcall handler 'file-truename filename)
391 (let ((dir (or (file-name-directory filename) default-directory))
393 ;; Get the truename of the directory.
394 (setq dirfile (directory-file-name dir))
395 ;; If these are equal, we have the (or a) root directory.
396 (or (string= dir dirfile)
397 ;; If this is the same dir we last got the truename for,
398 ;; save time--don't recalculate.
399 (if (assoc dir (car prev-dirs))
400 (setq dir (cdr (assoc dir (car prev-dirs))))
402 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
403 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
405 (if (equal ".." (file-name-nondirectory filename))
407 (directory-file-name (file-name-directory (directory-file-name dir)))
409 (if (equal "." (file-name-nondirectory filename))
410 (setq filename (directory-file-name dir)
412 ;; Put it back on the file name.
413 (setq filename (concat dir (file-name-nondirectory filename)))
414 ;; Is the file name the name of a link?
415 (setq target (file-symlink-p filename))
417 ;; Yes => chase that link, then start all over
418 ;; since the link may point to a directory name that uses links.
419 ;; We can't safely use expand-file-name here
420 ;; since target might look like foo/../bar where foo
421 ;; is itself a link. Instead, we handle . and .. above.
423 (if (file-name-absolute-p target)
431 (defun file-chase-links (filename)
432 "Chase links in FILENAME until a name that is not a link.
433 Does not examine containing directories for links,
434 unlike `file-truename'."
435 (let (tem (count 100) (newname filename))
436 (while (setq tem (file-symlink-p newname))
438 (error "Apparent cycle of symbolic links for %s" filename))
439 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
440 (while (string-match "//+" tem)
441 (setq tem (concat (substring tem 0 (1+ (match-beginning 0)))
442 (substring tem (match-end 0)))))
443 ;; Handle `..' by hand, since it needs to work in the
444 ;; target of any directory symlink.
445 ;; This code is not quite complete; it does not handle
446 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
447 (while (string-match "\\`\\.\\./" tem)
448 (setq tem (substring tem 3))
449 (setq newname (file-name-as-directory
450 ;; Do the .. by hand.
453 ;; Chase links in the default dir of the symlink.
456 (file-name-directory newname))))))))
457 (setq newname (expand-file-name tem (file-name-directory newname)))
458 (setq count (1- count)))
461 (defun switch-to-buffer-other-window (buffer)
462 "Select buffer BUFFER in another window."
463 (interactive "BSwitch to buffer in other window: ")
464 (let ((pop-up-windows t))
465 (pop-to-buffer buffer t)))
467 (defun switch-to-buffer-other-frame (buffer)
468 "Switch to buffer BUFFER in another frame."
469 (interactive "BSwitch to buffer in other frame: ")
470 (let ((pop-up-frames t))
471 (pop-to-buffer buffer t)
472 (raise-frame (window-frame (selected-window)))))
474 (defun find-file (filename)
476 Switch to a buffer visiting file FILENAME,
477 creating one if none already exists."
478 (interactive "FFind file: ")
479 (switch-to-buffer (find-file-noselect filename)))
481 (defun find-file-other-window (filename)
482 "Edit file FILENAME, in another window.
483 May create a new window, or reuse an existing one.
484 See the function `display-buffer'."
485 (interactive "FFind file in other window: ")
486 (switch-to-buffer-other-window (find-file-noselect filename)))
488 (defun find-file-other-frame (filename)
489 "Edit file FILENAME, in another frame.
490 May create a new frame, or reuse an existing one.
491 See the function `display-buffer'."
492 (interactive "FFind file in other frame: ")
493 (switch-to-buffer-other-frame (find-file-noselect filename)))
495 (defun find-file-read-only (filename)
496 "Edit file FILENAME but don't allow changes.
497 Like \\[find-file] but marks buffer as read-only.
498 Use \\[toggle-read-only] to permit editing."
499 (interactive "fFind file read-only: ")
501 (setq buffer-read-only t)
504 (defun find-file-read-only-other-window (filename)
505 "Edit file FILENAME in another window but don't allow changes.
506 Like \\[find-file-other-window] but marks buffer as read-only.
507 Use \\[toggle-read-only] to permit editing."
508 (interactive "fFind file read-only other window: ")
509 (find-file-other-window filename)
510 (setq buffer-read-only t)
513 (defun find-file-read-only-other-frame (filename)
514 "Edit file FILENAME in another frame but don't allow changes.
515 Like \\[find-file-other-frame] but marks buffer as read-only.
516 Use \\[toggle-read-only] to permit editing."
517 (interactive "fFind file read-only other frame: ")
518 (find-file-other-frame filename)
519 (setq buffer-read-only t)
522 (defun find-alternate-file (filename)
523 "Find file FILENAME, select its buffer, kill previous buffer.
524 If the current buffer now contains an empty file that you just visited
525 \(presumably by mistake), use this command to visit the file you really want."
527 (let ((file buffer-file-name)
531 (setq file-name (file-name-nondirectory file)
532 file-dir (file-name-directory file)))
533 (list (read-file-name
534 "Find alternate file: " file-dir nil nil file-name))))
535 (and (buffer-modified-p) (buffer-file-name)
536 ;; (not buffer-read-only)
537 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
540 (let ((obuf (current-buffer))
541 (ofile buffer-file-name)
542 (onum buffer-file-number)
543 (otrue buffer-file-truename)
544 (oname (buffer-name)))
545 (rename-buffer " **lose**")
546 (setq buffer-file-name nil)
547 (setq buffer-file-number nil)
548 (setq buffer-file-truename nil)
552 (find-file filename))
553 (cond ((eq obuf (current-buffer))
554 (setq buffer-file-name ofile)
555 (setq buffer-file-number onum)
556 (setq buffer-file-truename otrue)
558 (rename-buffer oname))))
559 (or (eq (current-buffer) obuf)
560 (kill-buffer obuf))))
562 (defun create-file-buffer (filename)
563 "Create a suitably named buffer for visiting FILENAME, and return it.
564 FILENAME (sans directory) is used unchanged if that name is free;
565 otherwise a string <2> or <3> or ... is appended to get an unused name."
566 (let ((lastname (file-name-nondirectory filename)))
567 (if (string= lastname "")
568 (setq lastname filename))
569 (generate-new-buffer lastname)))
571 (defun generate-new-buffer (name)
572 "Create and return a buffer with a name based on NAME.
573 Choose the buffer's name using `generate-new-buffer-name'."
574 (get-buffer-create (generate-new-buffer-name name)))
576 (defconst automount-dir-prefix "^/tmp_mnt/"
577 "Regexp to match the automounter prefix in a directory name.")
579 (defvar abbreviated-home-dir nil
580 "The user's homedir abbreviated according to `directory-abbrev-list'.")
582 (defun abbreviate-file-name (filename)
583 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
584 This also substitutes \"~\" for the user's home directory.
585 Type \\[describe-variable] directory-abbrev-alist RET for more information."
586 ;; Get rid of the prefixes added by the automounter.
587 (if (and (string-match automount-dir-prefix filename)
588 (file-exists-p (file-name-directory
589 (substring filename (1- (match-end 0))))))
590 (setq filename (substring filename (1- (match-end 0)))))
591 (let ((tail directory-abbrev-alist))
592 ;; If any elt of directory-abbrev-alist matches this name,
593 ;; abbreviate accordingly.
595 (if (string-match (car (car tail)) filename)
597 (concat (cdr (car tail)) (substring filename (match-end 0)))))
598 (setq tail (cdr tail)))
599 ;; Compute and save the abbreviated homedir name.
600 ;; We defer computing this until the first time it's needed, to
601 ;; give time for directory-abbrev-alist to be set properly.
602 ;; We include a slash at the end, to avoid spurious matches
603 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
604 (or abbreviated-home-dir
605 (setq abbreviated-home-dir
606 (let ((abbreviated-home-dir "$foo"))
607 (concat "^" (abbreviate-file-name (expand-file-name "~"))
610 ;; If FILENAME starts with the abbreviated homedir,
611 ;; make it start with `~' instead.
612 (if (and (string-match abbreviated-home-dir filename)
613 ;; If the home dir is just /, don't change it.
614 (not (and (= (match-end 0) 1)
615 (= (aref filename 0) ?/)))
616 (not (and (or (eq system-type 'ms-dos)
617 (eq system-type 'windows-nt))
619 (string-match "^[a-zA-Z]:/$" filename)))))
622 (substring filename (match-beginning 1) (match-end 1))
623 (substring filename (match-end 0)))))
626 (defvar find-file-not-true-dirname-list nil
627 "*List of logical names for which visiting shouldn't save the true dirname.
628 On VMS, when you visit a file using a logical name that searches a path,
629 you may or may not want the visited file name to record the specific
630 directory where the file was found. If you *do not* want that, add the logical
631 name to this list as a string.")
633 (defun find-buffer-visiting (filename)
634 "Return the buffer visiting file FILENAME (a string).
635 This is like `get-file-buffer', except that it checks for any buffer
636 visiting the same file, possibly under a different name.
637 If there is no such live buffer, return nil."
638 (let ((buf (get-file-buffer filename))
639 (truename (abbreviate-file-name (file-truename filename))))
641 (let ((list (buffer-list)) found)
642 (while (and (not found) list)
644 (set-buffer (car list))
645 (if (and buffer-file-name
646 (string= buffer-file-truename truename))
647 (setq found (car list))))
648 (setq list (cdr list)))
650 (let ((number (nthcdr 10 (file-attributes truename)))
651 (list (buffer-list)) found)
653 (while (and (not found) list)
655 (set-buffer (car list))
656 (if (and buffer-file-name
657 (equal buffer-file-number number)
658 ;; Verify this buffer's file number
659 ;; still belongs to its file.
660 (file-exists-p buffer-file-name)
661 (equal (nthcdr 10 (file-attributes buffer-file-name))
663 (setq found (car list))))
664 (setq list (cdr list))))
667 (defun find-file-noselect (filename &optional nowarn)
668 "Read file FILENAME into a buffer and return the buffer.
669 If a buffer exists visiting FILENAME, return that one, but
670 verify that the file has not changed since visited or saved.
671 The buffer is not selected, just returned to the caller."
673 (abbreviate-file-name
674 (expand-file-name filename)))
675 (if (file-directory-p filename)
676 (if find-file-run-dired
677 (dired-noselect filename)
678 (error "%s is a directory." filename))
679 (let* ((buf (get-file-buffer filename))
680 (truename (abbreviate-file-name (file-truename filename)))
681 (number (nthcdr 10 (file-attributes truename)))
682 ;; Find any buffer for a file which has same truename.
683 (other (and (not buf) (find-buffer-visiting filename)))
685 ;; Let user know if there is a buffer with the same truename.
689 (string-equal filename (buffer-file-name other))
690 (message "%s and %s are the same file"
691 filename (buffer-file-name other)))
692 ;; Optionally also find that buffer.
693 (if (or find-file-existing-other-name find-file-visit-truename)
697 (verify-visited-file-modtime buf)
698 (cond ((not (file-exists-p filename))
699 (error "File %s no longer exists!" filename))
701 (if (string= (file-name-nondirectory filename)
704 (if (buffer-modified-p buf)
705 "File %s changed on disk. Discard your edits? "
706 "File %s changed on disk. Reread from disk? ")
707 (file-name-nondirectory filename))
709 (if (buffer-modified-p buf)
710 "File %s changed on disk. Discard your edits in %s? "
711 "File %s changed on disk. Reread from disk into %s? ")
712 (file-name-nondirectory filename)
716 (revert-buffer t t)))))
718 ;;; The truename stuff makes this obsolete.
719 ;;; (let* ((link-name (car (file-attributes filename)))
720 ;;; (linked-buf (and (stringp link-name)
721 ;;; (get-file-buffer link-name))))
722 ;;; (if (bufferp linked-buf)
723 ;;; (message "Symbolic link to file in buffer %s"
724 ;;; (buffer-name linked-buf))))
725 (setq buf (create-file-buffer filename))
726 (set-buffer-major-mode buf)
730 (insert-file-contents filename t)
732 ;; Run find-file-not-found-hooks until one returns non-nil.
733 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
734 ;; If they fail too, set error.
736 ;; Find the file's truename, and maybe use that as visited name.
737 (setq buffer-file-truename truename)
738 (setq buffer-file-number number)
739 ;; On VMS, we may want to remember which directory in a search list
740 ;; the file was found in.
741 (and (eq system-type 'vax-vms)
743 (if (string-match ":" (file-name-directory filename))
744 (setq logical (substring (file-name-directory filename)
745 0 (match-beginning 0))))
746 (not (member logical find-file-not-true-dirname-list)))
747 (setq buffer-file-name buffer-file-truename))
748 (if find-file-visit-truename
749 (setq buffer-file-name
751 (expand-file-name buffer-file-truename))))
752 ;; Set buffer's default directory to that of the file.
753 (setq default-directory (file-name-directory filename))
754 ;; Turn off backup files for certain file names. Since
755 ;; this is a permanent local, the major mode won't eliminate it.
756 (and (not (funcall backup-enable-predicate buffer-file-name))
758 (make-local-variable 'backup-inhibited)
759 (setq backup-inhibited t)))
760 (after-find-file error (not nowarn))))
763 (defvar after-find-file-from-revert-buffer nil)
765 (defun after-find-file (&optional error warn noauto
766 after-find-file-from-revert-buffer)
767 "Called after finding a file and by the default revert function.
768 Sets buffer mode, parses local variables.
769 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
770 error in reading the file. WARN non-nil means warn if there
771 exists an auto-save file more recent than the visited file.
772 NOAUTO means don't mess with auto-save mode.
773 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
774 means this call was from `revert-buffer'.
775 Finishes by calling the functions in `find-file-hooks'."
776 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
781 (cond ((and error (file-attributes buffer-file-name))
782 (setq buffer-read-only t)
783 "File exists, but cannot be read.")
784 ((not buffer-read-only)
786 (file-newer-than-file-p (make-auto-save-file-name)
788 "Auto save file is newer; consider M-x recover-file"
790 (if error "(New file)" nil)))
793 "Note: file is write protected")
794 ((file-attributes (directory-file-name default-directory))
795 "File not found and directory write-protected")
796 ((file-exists-p (file-name-directory buffer-file-name))
797 (setq buffer-read-only nil))
799 (setq buffer-read-only nil)
800 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
801 "Use M-x make-dir RET RET to create the directory"
802 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
806 (or not-serious (sit-for 1 nil t)))))
807 (if (and auto-save-default (not noauto))
810 (run-hooks 'find-file-hooks))
812 (defun normal-mode (&optional find-file)
813 "Choose the major mode for this buffer automatically.
814 Also sets up any specified local variables of the file.
815 Uses the visited file name, the -*- line, and the local variables spec.
817 This function is called automatically from `find-file'. In that case,
818 we may set up specified local variables depending on the value of
819 `enable-local-variables': if it is t, we do; if it is nil, we don't;
820 otherwise, we query. `enable-local-variables' is ignored if you
821 run `normal-mode' explicitly."
823 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
826 (error (message "File mode specification error: %s"
827 (prin1-to-string err))))
829 (let ((enable-local-variables (or (not find-file)
830 enable-local-variables)))
831 (hack-local-variables))
832 (error (message "File local-variables error: %s"
833 (prin1-to-string err)))))
835 (defvar auto-mode-alist (mapcar 'purecopy
836 '(("\\.text\\'" . text-mode)
839 ("\\.tex\\'" . tex-mode)
840 ("\\.ltx\\'" . latex-mode)
841 ("\\.el\\'" . emacs-lisp-mode)
842 ("\\.mm\\'" . nroff-mode)
843 ("\\.me\\'" . nroff-mode)
844 ("\\.ms\\'" . nroff-mode)
845 ("\\.man\\'" . nroff-mode)
846 ("\\.scm\\'" . scheme-mode)
847 ("\\.l\\'" . lisp-mode)
848 ("\\.lisp\\'" . lisp-mode)
849 ("\\.f\\'" . fortran-mode)
850 ("\\.for\\'" . fortran-mode)
851 ("\\.p\\'" . pascal-mode)
852 ("\\.pas\\'" . pascal-mode)
853 ("\\.mss\\'" . scribe-mode)
854 ("\\.ada\\'" . ada-mode)
855 ("\\.icn\\'" . icon-mode)
856 ("\\.pl\\'" . prolog-mode)
857 ("\\.cc\\'" . c++-mode)
858 ("\\.hh\\'" . c++-mode)
859 ("\\.C\\'" . c++-mode)
860 ("\\.H\\'" . c++-mode)
861 ("\\.cpp\\'" . c++-mode)
862 ("\\.cxx\\'" . c++-mode)
863 ("\\.hxx\\'" . c++-mode)
864 ("\\.c\\+\\+\\'" . c++-mode)
865 ("\\.h\\+\\+\\'" . c++-mode)
866 ;;; ("\\.mk\\'" . makefile-mode)
867 ;;; ("[Mm]akefile" . makefile-mode)
868 ;;; Less common extensions come here
869 ;;; so more common ones above are found faster.
870 ("\\.texinfo\\'" . texinfo-mode)
871 ("\\.texi\\'" . texinfo-mode)
872 ("\\.s\\'" . asm-mode)
873 ("ChangeLog\\'" . change-log-mode)
874 ("change.log\\'" . change-log-mode)
875 ("changelo\\'" . change-log-mode)
876 ("ChangeLog.[0-9]+\\'" . change-log-mode)
877 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
878 ;; The following should come after the ChangeLog pattern
879 ;; for the sake of ChangeLog.1, etc.
880 ("\\.[12345678]\\'" . nroff-mode)
881 ("\\.TeX\\'" . tex-mode)
882 ("\\.sty\\'" . latex-mode)
883 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
884 ("\\.bbl\\'" . latex-mode)
885 ("\\.bib\\'" . bibtex-mode)
886 ("\\.article\\'" . text-mode)
887 ("\\.letter\\'" . text-mode)
888 ("\\.tcl\\'" . tcl-mode)
889 ("\\.lsp\\'" . lisp-mode)
890 ("\\.awk\\'" . awk-mode)
891 ("\\.prolog\\'" . prolog-mode)
892 ("\\.tar\\'" . tar-mode)
893 ;; Mailer puts message to be edited in
894 ;; /tmp/Re.... or Message
895 ("^/tmp/Re" . text-mode)
896 ("/Message[0-9]*\\'" . text-mode)
897 ("/drafts/[0-9]+\\'" . mh-letter-mode)
898 ;; some news reader is reported to use this
899 ("^/tmp/fol/" . text-mode)
901 ("\\.lex\\'" . c-mode)
902 ("\\.oak\\'" . scheme-mode)
903 ("\\.scm.[0-9]*\\'" . scheme-mode)
904 ("\\.sgm\\'" . sgml-mode)
905 ("\\.sgml\\'" . sgml-mode)
906 ("\\.dtd\\'" . sgml-mode)
907 ;; .emacs following a directory delimiter
908 ;; in either Unix or VMS syntax.
909 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
910 ;; _emacs following a directory delimiter
912 ("[:/]_emacs\\'" . emacs-lisp-mode)
913 ("\\.ml\\'" . lisp-mode)))
915 Alist of filename patterns vs corresponding major mode functions.
916 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
917 \(NON-NIL stands for anything that is not nil; the value does not matter.)
918 Visiting a file whose name matches REGEXP specifies FUNCTION as the
919 mode function to use. FUNCTION will be called, unless it is nil.
921 If the element has the form (REGEXP FUNCTION NON-NIL), then after
922 calling FUNCTION (if it's not nil), we delete the suffix that matched
923 REGEXP and search the list again for another match.")
925 (defconst interpreter-mode-alist
926 '(("perl" . perl-mode)
933 ("scm" . scheme-mode))
934 "Alist mapping interpreter names to major modes.
935 This alist applies to files whose first line starts with `#!'.
936 Each element looks like (INTERPRETER . MODE).
937 The car of each element is compared with
938 the name of the interpreter specified in the first line.
939 If it matches, mode MODE is selected.")
941 (defconst inhibit-first-line-modes-regexps '("\\.tar\\'")
942 "List of regexps; if one matches a file name, don't look for `-*-'.")
944 (defconst inhibit-first-line-modes-suffixes nil
945 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
946 When checking `inhibit-first-line-modes-regexps', we first discard
947 from the end of the file name anything that matches one of these regexps.")
949 (defvar user-init-file
950 "" ; set by command-line
951 "File name including directory of user's initialization file.")
953 (defun set-auto-mode ()
954 "Select major mode appropriate for current buffer.
955 This checks for a -*- mode tag in the buffer's text,
956 compares the filename against the entries in `auto-mode-alist',
957 or checks the interpreter that runs this file against
958 `interpreter-mode-alist'.
960 It does not check for the `mode:' local variable in the
961 Local Variables section of the file; for that, use `hack-local-variables'.
963 If `enable-local-variables' is nil, this function does not check for a
965 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
968 (goto-char (point-min))
969 (skip-chars-forward " \t\n")
970 (and enable-local-variables
971 ;; Don't look for -*- if this file name matches any
972 ;; of the regexps in inhibit-first-line-modes-regexps.
973 (let ((temp inhibit-first-line-modes-regexps)
974 (name (if buffer-file-name
975 (file-name-sans-versions buffer-file-name)
977 (while (let ((sufs inhibit-first-line-modes-suffixes))
978 (while (and sufs (not (string-match (car sufs) name)))
979 (setq sufs (cdr sufs)))
981 (setq name (substring name 0 (match-beginning 0))))
983 (not (string-match (car temp) name)))
984 (setq temp (cdr temp)))
986 (search-forward "-*-" (save-excursion
987 ;; If the file begins with "#!"
988 ;; (exec interpreter magic), look
989 ;; for mode frobs in the first two
990 ;; lines. You cannot necessarily
991 ;; put them in the first line of
992 ;; such a file without screwing up
993 ;; the interpreter invocation.
994 (end-of-line (and (looking-at "^#!") 2))
997 (skip-chars-forward " \t")
999 (search-forward "-*-"
1000 (save-excursion (end-of-line) (point))
1004 (skip-chars-backward " \t")
1007 (if (save-excursion (search-forward ":" end t))
1008 ;; Find all specifications for the `mode:' variable
1009 ;; and execute them left to right.
1010 (while (let ((case-fold-search t))
1011 (or (and (looking-at "mode:")
1012 (goto-char (match-end 0)))
1013 (re-search-forward "[ \t;]mode:" end t)))
1014 (skip-chars-forward " \t")
1016 (if (search-forward ";" end t)
1019 (skip-chars-backward " \t")
1020 (funcall (intern (concat (downcase (buffer-substring beg (point))) "-mode")))
1022 ;; Simple -*-MODE-*- case.
1023 (funcall (intern (concat (downcase (buffer-substring beg end)) "-mode")))
1025 ;; If we didn't find a mode from a -*- line, try using the file name.
1026 (if (and (not done) buffer-file-name)
1027 (let ((name buffer-file-name)
1029 ;; Remove backup-suffixes from file name.
1030 (setq name (file-name-sans-versions name))
1032 (setq keep-going nil)
1033 (let ((alist auto-mode-alist)
1035 ;; Find first matching alist entry.
1036 (let ((case-fold-search
1037 (memq system-type '(vax-vms windows-nt))))
1038 (while (and (not mode) alist)
1039 (if (string-match (car (car alist)) name)
1040 (if (and (consp (cdr (car alist)))
1041 (nth 2 (car alist)))
1043 (setq mode (car (cdr (car alist)))
1044 name (substring name 0 (match-beginning 0))
1046 (setq mode (cdr (car alist))
1048 (setq alist (cdr alist))))
1051 ;; If we can't deduce a mode from the file name,
1052 ;; look for an interpreter specified in the first line.
1055 (goto-char (point-min))
1056 (if (looking-at "#! *\\([^ \t\n]+\\)")
1057 (buffer-substring (match-beginning 1)
1061 ;; Map interpreter name to a mode.
1062 (setq elt (assoc (file-name-nondirectory interpreter)
1063 interpreter-mode-alist))
1065 (funcall (cdr elt))))))))))))
1067 (defun hack-local-variables-prop-line ()
1068 ;; Set local variables specified in the -*- line.
1069 ;; Ignore any specification for `mode:';
1070 ;; set-auto-mode should already have handled that.
1072 (goto-char (point-min))
1074 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
1075 ;; Parse the -*- line into the `result' alist.
1076 (cond ((not (search-forward "-*-" end t))
1077 ;; doesn't have one.
1079 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1080 ;; Simple form: "-*- MODENAME -*-". Already handled.
1083 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1084 ;; (last ";" is optional).
1086 (if (search-forward "-*-" end t)
1087 (setq end (- (point) 3))
1088 (error "-*- not terminated before end of line")))
1089 (while (< (point) end)
1090 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1091 (error "malformed -*- line"))
1092 (goto-char (match-end 0))
1093 ;; There used to be a downcase here,
1094 ;; but the manual didn't say so,
1095 ;; and people want to set var names that aren't all lc.
1096 (let ((key (intern (buffer-substring
1099 (val (save-restriction
1100 (narrow-to-region (point) end)
1101 (read (current-buffer)))))
1103 (setq result (cons (cons key val) result)))
1104 (skip-chars-forward " \t;")))
1105 (setq result (nreverse result))))
1108 (or (eq enable-local-variables t)
1109 (and enable-local-variables
1110 (save-window-excursion
1112 (switch-to-buffer (current-buffer))
1114 ;; If we fail to switch in the selected window,
1115 ;; it is probably a minibuffer.
1116 ;; So try another window.
1118 (switch-to-buffer-other-window (current-buffer))
1120 (switch-to-buffer-other-frame (current-buffer))))))
1121 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1122 (file-name-nondirectory buffer-file-name)))))))
1124 (hack-one-local-variable (car (car result)) (cdr (car result)))
1125 (setq result (cdr result)))))))
1127 (defvar hack-local-variables-hook nil
1128 "Normal hook run after processing a file's local variables specs.
1129 Major modes can use this to examine user-specified local variables
1130 in order to initialize other data structure based on them.")
1132 (defun hack-local-variables ()
1133 "Parse and put into effect this buffer's local variables spec."
1134 (hack-local-variables-prop-line)
1135 ;; Look for "Local variables:" line in last page.
1137 (goto-char (point-max))
1138 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1139 (if (let ((case-fold-search t))
1140 (and (search-forward "Local Variables:" nil t)
1141 (or (eq enable-local-variables t)
1142 (and enable-local-variables
1143 (save-window-excursion
1144 (switch-to-buffer (current-buffer))
1147 (set-window-start (selected-window) (point)))
1148 (y-or-n-p (format "Set local variables as specified at end of %s? "
1149 (if buffer-file-name
1150 (file-name-nondirectory
1153 (buffer-name))))))))))
1155 prefix prefixlen suffix beg
1156 (enable-local-eval enable-local-eval))
1157 ;; The prefix is what comes before "local variables:" in its line.
1158 ;; The suffix is what comes after "local variables:" in its line.
1159 (skip-chars-forward " \t")
1161 (setq suffix (buffer-substring (point)
1162 (progn (end-of-line) (point)))))
1163 (goto-char (match-beginning 0))
1166 (buffer-substring (point)
1167 (progn (beginning-of-line) (point)))))
1169 (if prefix (setq prefixlen (length prefix)
1170 prefix (regexp-quote prefix)))
1171 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1173 ;; Look at next local variable spec.
1174 (if selective-display (re-search-forward "[\n\C-m]")
1176 ;; Skip the prefix, if any.
1178 (if (looking-at prefix)
1179 (forward-char prefixlen)
1180 (error "Local variables entry is missing the prefix")))
1181 ;; Find the variable name; strip whitespace.
1182 (skip-chars-forward " \t")
1184 (skip-chars-forward "^:\n")
1185 (if (eolp) (error "Missing colon in local variables entry"))
1186 (skip-chars-backward " \t")
1187 (let* ((str (buffer-substring beg (point)))
1190 ;; Setting variable named "end" means end of list.
1191 (if (string-equal (downcase str) "end")
1193 ;; Otherwise read the variable value.
1194 (skip-chars-forward "^:")
1196 (setq val (read (current-buffer)))
1197 (skip-chars-backward "\n")
1198 (skip-chars-forward " \t")
1199 (or (if suffix (looking-at suffix) (eolp))
1200 (error "Local variables entry is terminated incorrectly"))
1201 ;; Set the variable. "Variables" mode and eval are funny.
1202 (hack-one-local-variable var val)))))))
1203 (run-hooks 'hack-local-variables-hook))
1205 (defconst ignored-local-variables
1206 '(enable-local-eval)
1207 "Variables to be ignored in a file's local variable spec.")
1209 ;; Get confirmation before setting these variables as locals in a file.
1210 (put 'debugger 'risky-local-variable t)
1211 (put 'enable-local-eval 'risky-local-variable t)
1212 (put 'ignored-local-variables 'risky-local-variable t)
1213 (put 'eval 'risky-local-variable t)
1214 (put 'file-name-handler-alist 'risky-local-variable t)
1215 (put 'minor-mode-map-alist 'risky-local-variable t)
1216 (put 'after-load-alist 'risky-local-variable t)
1217 (put 'buffer-file-name 'risky-local-variable t)
1218 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1219 (put 'buffer-file-truename 'risky-local-variable t)
1220 (put 'exec-path 'risky-local-variable t)
1221 (put 'load-path 'risky-local-variable t)
1222 (put 'exec-directory 'risky-local-variable t)
1223 (put 'process-environment 'risky-local-variable t)
1224 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1225 (put 'outline-level 'risky-local-variable t)
1226 (put 'rmail-output-file-alist 'risky-local-variable t)
1228 ;; This one is safe because the user gets to check it before it is used.
1229 (put 'compile-command 'safe-local-variable t)
1231 (defun hack-one-local-variable-quotep (exp)
1232 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1234 ;; "Set" one variable in a local variables spec.
1235 ;; A few variable names are treated specially.
1236 (defun hack-one-local-variable (var val)
1237 (cond ((eq var 'mode)
1238 (funcall (intern (concat (downcase (symbol-name val))
1240 ((memq var ignored-local-variables)
1242 ;; "Setting" eval means either eval it or do nothing.
1243 ;; Likewise for setting hook variables.
1244 ((or (get var 'risky-local-variable)
1246 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
1248 (not (get var 'safe-local-variable))))
1249 ;; Permit evaling a put of a harmless property
1250 ;; if the args do nothing tricky.
1251 (if (or (and (eq var 'eval)
1254 (hack-one-local-variable-quotep (nth 1 val))
1255 (hack-one-local-variable-quotep (nth 2 val))
1256 ;; Only allow safe values of lisp-indent-hook;
1258 (or (numberp (nth 3 val))
1259 (equal (nth 3 val) ''defun))
1260 (memq (nth 1 (nth 2 val))
1261 '(lisp-indent-hook)))
1262 ;; Permit eval if not root and user says ok.
1263 (and (not (zerop (user-uid)))
1264 (or (eq enable-local-eval t)
1265 (and enable-local-eval
1266 (save-window-excursion
1267 (switch-to-buffer (current-buffer))
1270 (set-window-start (selected-window) (point)))
1271 (setq enable-local-eval
1272 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1273 (file-name-nondirectory buffer-file-name)))))))))
1275 (save-excursion (eval val))
1276 (make-local-variable var)
1278 (message "Ignoring `eval:' in file's local variables")))
1279 ;; Ordinary variable, really set it.
1280 (t (make-local-variable var)
1284 (defun set-visited-file-name (filename)
1285 "Change name of file visited in current buffer to FILENAME.
1286 The next time the buffer is saved it will go in the newly specified file.
1287 nil or empty string as argument means make buffer not be visiting any file.
1288 Remember to delete the initial contents of the minibuffer
1289 if you wish to pass an empty string as the argument."
1290 (interactive "FSet visited file name: ")
1291 (if (buffer-base-buffer)
1292 (error "An indirect buffer cannot visit a file"))
1296 (if (string-equal filename "")
1298 (expand-file-name filename))))
1301 (setq truename (file-truename filename))
1302 (if find-file-visit-truename
1303 ;; Do not use the abbreviated filename, because
1304 ;; write-region will reset it to the expanded filename
1305 (setq filename truename))))
1306 (or (equal filename buffer-file-name)
1308 (and filename (lock-buffer filename))
1310 (setq buffer-file-name filename)
1311 (if filename ; make buffer name reflect filename.
1312 (let ((new-name (file-name-nondirectory buffer-file-name)))
1313 (if (string= new-name "")
1314 (error "Empty file name"))
1315 (if (eq system-type 'vax-vms)
1316 (setq new-name (downcase new-name)))
1317 (setq default-directory (file-name-directory buffer-file-name))
1318 (or (string= new-name (buffer-name))
1319 (rename-buffer new-name t))))
1320 (setq buffer-backed-up nil)
1321 (clear-visited-file-modtime)
1323 (setq buffer-file-truename (abbreviate-file-name truename)))
1324 (setq buffer-file-number
1326 (nth 10 (file-attributes buffer-file-name))
1328 ;; write-file-hooks is normally used for things like ftp-find-file
1329 ;; that visit things that are not local files as if they were files.
1330 ;; Changing to visit an ordinary local file instead should flush the hook.
1331 (kill-local-variable 'write-file-hooks)
1332 (kill-local-variable 'local-write-file-hooks)
1333 (kill-local-variable 'revert-buffer-function)
1334 (kill-local-variable 'backup-inhibited)
1335 ;; If buffer was read-only because of version control,
1336 ;; that reason is gone now, so make it writable.
1338 (setq buffer-read-only nil))
1339 (kill-local-variable 'vc-mode)
1340 ;; Turn off backup files for certain file names.
1341 ;; Since this is a permanent local, the major mode won't eliminate it.
1342 (and (not (funcall backup-enable-predicate buffer-file-name))
1344 (make-local-variable 'backup-inhibited)
1345 (setq backup-inhibited t)))
1346 (let ((oauto buffer-auto-save-file-name))
1347 ;; If auto-save was not already on, turn it on if appropriate.
1348 (if (not buffer-auto-save-file-name)
1349 (and buffer-file-name auto-save-default
1351 ;; If auto save is on, start using a new name.
1352 ;; We deliberately don't rename or delete the old auto save
1353 ;; for the old visited file name. This is because perhaps
1354 ;; the user wants to save the new state and then compare with the
1355 ;; previous state from the auto save file.
1356 (setq buffer-auto-save-file-name
1357 (make-auto-save-file-name)))
1358 ;; Rename the old auto save file if any.
1359 (and oauto buffer-auto-save-file-name
1360 (file-exists-p oauto)
1361 (rename-file oauto buffer-auto-save-file-name t)))
1362 (if buffer-file-name
1363 (set-buffer-modified-p t)))
1365 (defun write-file (filename &optional confirm)
1366 "Write current buffer into file FILENAME.
1367 Makes buffer visit that file, and marks it not modified.
1368 If the buffer is already visiting a file, you can specify
1369 a directory name as FILENAME, to write a file of the same
1370 old name in that directory.
1371 If optional second arg CONFIRM is non-nil,
1372 ask for confirmation for overwriting an existing file."
1373 ;; (interactive "FWrite file: ")
1375 (list (if buffer-file-name
1376 (read-file-name "Write file: "
1378 (read-file-name "Write file: "
1379 (cdr (assq 'default-directory
1380 (buffer-local-variables)))
1381 nil nil (buffer-name)))
1383 (or (null filename) (string-equal filename "")
1385 ;; If arg is just a directory,
1386 ;; use same file name, but in that directory.
1387 (if (and (file-directory-p filename) buffer-file-name)
1388 (setq filename (concat (file-name-as-directory filename)
1389 (file-name-nondirectory buffer-file-name))))
1391 (file-exists-p filename)
1392 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1393 (error "Canceled")))
1394 (set-visited-file-name filename)))
1395 (set-buffer-modified-p t)
1398 (defun backup-buffer ()
1399 "Make a backup of the disk file visited by the current buffer, if appropriate.
1400 This is normally done before saving the buffer the first time.
1401 If the value is non-nil, it is the result of `file-modes' on the original
1402 file; this means that the caller, after saving the buffer, should change
1403 the modes of the new file to agree with the old modes."
1404 (if (and make-backup-files (not backup-inhibited)
1405 (not buffer-backed-up)
1406 (file-exists-p buffer-file-name)
1407 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1409 (let ((real-file-name buffer-file-name)
1410 backup-info backupname targets setmodes)
1411 ;; If specified name is a symbolic link, chase it to the target.
1412 ;; Thus we make the backups in the directory where the real file is.
1413 (setq real-file-name (file-chase-links real-file-name))
1414 (setq backup-info (find-backup-file-name real-file-name)
1415 backupname (car backup-info)
1416 targets (cdr backup-info))
1417 ;;; (if (file-directory-p buffer-file-name)
1418 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1421 (let ((delete-old-versions
1422 ;; If have old versions to maybe delete,
1423 ;; ask the user to confirm now, before doing anything.
1424 ;; But don't actually delete til later.
1426 (or (eq delete-old-versions t) (eq delete-old-versions nil))
1427 (or delete-old-versions
1428 (y-or-n-p (format "Delete excess backup versions of %s? "
1429 real-file-name))))))
1430 ;; Actually write the back up file.
1432 (if (or file-precious-flag
1433 ; (file-symlink-p buffer-file-name)
1435 (and backup-by-copying-when-linked
1436 (> (file-nlinks real-file-name) 1))
1437 (and backup-by-copying-when-mismatch
1438 (let ((attr (file-attributes real-file-name)))
1440 (not (file-ownership-preserved-p real-file-name))))))
1442 (copy-file real-file-name backupname t t)
1444 ;; If copying fails because file BACKUPNAME
1445 ;; is not writable, delete that file and try again.
1446 (if (and (file-exists-p backupname)
1447 (not (file-writable-p backupname)))
1448 (delete-file backupname))
1449 (copy-file real-file-name backupname t t)))
1450 ;; rename-file should delete old backup.
1451 (rename-file real-file-name backupname t)
1452 (setq setmodes (file-modes backupname)))
1454 ;; If trouble writing the backup, write it in ~.
1455 (setq backupname (expand-file-name "~/%backup%~"))
1456 (message "Cannot write backup file; backing up in ~/%%backup%%~")
1459 (copy-file real-file-name backupname t t)
1461 ;; If copying fails because file BACKUPNAME
1462 ;; is not writable, delete that file and try again.
1463 (if (and (file-exists-p backupname)
1464 (not (file-writable-p backupname)))
1465 (delete-file backupname))
1466 (copy-file real-file-name backupname t t)))))
1467 (setq buffer-backed-up t)
1468 ;; Now delete the old versions, if desired.
1469 (if delete-old-versions
1472 (delete-file (car targets))
1474 (setq targets (cdr targets))))
1476 (file-error nil))))))
1478 (defun file-name-sans-versions (name &optional keep-backup-version)
1479 "Return FILENAME sans backup versions or strings.
1480 This is a separate procedure so your site-init or startup file can
1482 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1483 we do not remove backup version numbers, only true file version numbers."
1484 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1486 (funcall handler 'file-name-sans-versions name keep-backup-version)
1488 (if (eq system-type 'vax-vms)
1489 ;; VMS version number is (a) semicolon, optional
1490 ;; sign, zero or more digits or (b) period, option
1491 ;; sign, zero or more digits, provided this is the
1492 ;; second period encountered outside of the
1493 ;; device/directory part of the file name.
1494 (or (string-match ";[-+]?[0-9]*\\'" name)
1495 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1497 (match-beginning 1))
1499 (if keep-backup-version
1501 (or (string-match "\\.~[0-9]+~\\'" name)
1502 (string-match "~\\'" name)
1503 (length name))))))))
1505 (defun file-ownership-preserved-p (file)
1506 "Returns t if deleting FILE and rewriting it would preserve the owner."
1507 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1509 (funcall handler 'file-ownership-preserved-p file)
1510 (let ((attributes (file-attributes file)))
1511 ;; Return t if the file doesn't exist, since it's true that no
1512 ;; information would be lost by an (attempted) delete and create.
1513 (or (null attributes)
1514 (= (nth 2 attributes) (user-uid)))))))
1516 (defun file-name-sans-extension (filename)
1517 "Return FILENAME sans final \"extension\".
1518 The extension, in a file name, is the part that follows the last `.'."
1520 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1522 (if (string-match "\\.[^.]*\\'" file)
1523 (if (setq directory (file-name-directory filename))
1524 (expand-file-name (substring file 0 (match-beginning 0))
1526 (substring file 0 (match-beginning 0)))
1529 (defun make-backup-file-name (file)
1530 "Create the non-numeric backup file name for FILE.
1531 This is a separate function so you can redefine it for customization."
1532 (if (eq system-type 'ms-dos)
1533 (let ((fn (file-name-nondirectory file)))
1534 (concat (file-name-directory file)
1535 (if (string-match "\\([^.]*\\)\\(\\..*\\)?" fn)
1536 (substring fn 0 (match-end 1)))
1540 (defun backup-file-name-p (file)
1541 "Return non-nil if FILE is a backup file name (numeric or not).
1542 This is a separate function so you can redefine it for customization.
1543 You may need to redefine `file-name-sans-versions' as well."
1544 (if (eq system-type 'ms-dos)
1545 (string-match "\\.bak$" file)
1546 (string-match "~$" file)))
1548 ;; This is used in various files.
1549 ;; The usage of bv-length is not very clean,
1550 ;; but I can't see a good alternative,
1551 ;; so as of now I am leaving it alone.
1552 (defun backup-extract-version (fn)
1553 "Given the name of a numeric backup file, return the backup number.
1554 Uses the free variable `bv-length', whose value should be
1555 the index in the name where the version number begins."
1556 (if (and (string-match "[0-9]+~$" fn bv-length)
1557 (= (match-beginning 0) bv-length))
1558 (string-to-int (substring fn bv-length -1))
1561 ;; I believe there is no need to alter this behavior for VMS;
1562 ;; since backup files are not made on VMS, it should not get called.
1563 (defun find-backup-file-name (fn)
1564 "Find a file name for a backup file, and suggestions for deletions.
1565 Value is a list whose car is the name for the backup file
1566 and whose cdr is a list of old versions to consider deleting now.
1567 If the value is nil, don't make a backup."
1568 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
1569 ;; Run a handler for this function so that ange-ftp can refuse to do it.
1571 (funcall handler 'find-backup-file-name fn)
1572 (if (eq version-control 'never)
1573 (list (make-backup-file-name fn))
1574 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1575 (bv-length (length base-versions))
1579 (deserve-versions-p nil)
1580 (number-to-delete 0))
1582 (setq possibilities (file-name-all-completions
1584 (file-name-directory fn))
1585 versions (sort (mapcar
1586 (function backup-extract-version)
1589 high-water-mark (apply 'max 0 versions)
1590 deserve-versions-p (or version-control
1591 (> high-water-mark 0))
1592 number-to-delete (- (length versions)
1593 kept-old-versions kept-new-versions -1))
1595 (setq possibilities nil)))
1596 (if (not deserve-versions-p)
1597 (list (make-backup-file-name fn))
1598 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
1599 (if (and (> number-to-delete 0)
1600 ;; Delete nothing if there is overflow
1601 ;; in the number of versions to keep.
1602 (>= (+ kept-new-versions kept-old-versions -1) 0))
1603 (mapcar (function (lambda (n)
1604 (concat fn ".~" (int-to-string n) "~")))
1605 (let ((v (nthcdr kept-old-versions versions)))
1606 (rplacd (nthcdr (1- number-to-delete) v) ())
1609 (defun file-nlinks (filename)
1610 "Return number of names file FILENAME has."
1611 (car (cdr (file-attributes filename))))
1613 (defun file-relative-name (filename &optional directory)
1614 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1615 (setq filename (expand-file-name filename)
1616 directory (file-name-as-directory (expand-file-name
1617 (or directory default-directory))))
1618 (let ((ancestor ""))
1619 (while (not (string-match (concat "^" (regexp-quote directory)) filename))
1620 (setq directory (file-name-directory (substring directory 0 -1))
1621 ancestor (concat "../" ancestor)))
1622 (concat ancestor (substring filename (match-end 0)))))
1624 (defun save-buffer (&optional args)
1625 "Save current buffer in visited file if modified. Versions described below.
1626 By default, makes the previous version into a backup file
1627 if previously requested or if this is the first save.
1628 With 1 or 3 \\[universal-argument]'s, marks this version
1629 to become a backup when the next save is done.
1630 With 2 or 3 \\[universal-argument]'s,
1631 unconditionally makes the previous version into a backup file.
1632 With argument of 0, never makes the previous version into a backup file.
1634 If a file's name is FOO, the names of its numbered backup versions are
1635 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1636 Numeric backups (rather than FOO~) will be made if value of
1637 `version-control' is not the atom `never' and either there are already
1638 numeric versions of the file being backed up, or `version-control' is
1640 We don't want excessive versions piling up, so there are variables
1641 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1642 and `kept-new-versions', which tells how many newest versions to keep.
1643 Defaults are 2 old versions and 2 new.
1644 `dired-kept-versions' controls dired's clean-directory (.) command.
1645 If `delete-old-versions' is nil, system will query user
1646 before trimming versions. Otherwise it does it silently."
1648 (let ((modp (buffer-modified-p))
1649 (large (> (buffer-size) 50000))
1650 (make-backup-files (or (and make-backup-files (not (eq args 0)))
1651 (memq args '(16 64)))))
1652 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
1653 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
1655 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
1657 (defun delete-auto-save-file-if-necessary (&optional force)
1658 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1659 Normally delete only if the file was written by this Emacs since
1660 the last real save, but optional arg FORCE non-nil means delete anyway."
1661 (and buffer-auto-save-file-name delete-auto-save-files
1662 (not (string= buffer-file-name buffer-auto-save-file-name))
1663 (or force (recent-auto-save-p))
1666 (delete-file buffer-auto-save-file-name)
1668 (set-buffer-auto-saved))))
1670 (defun basic-save-buffer ()
1671 "Save the current buffer in its visited file, if it has been modified."
1674 ;; In an indirect buffer, save its base buffer instead.
1675 (if (buffer-base-buffer)
1676 (set-buffer (buffer-base-buffer)))
1677 (if (buffer-modified-p)
1678 (let ((recent-save (recent-auto-save-p))
1679 setmodes tempsetmodes)
1680 ;; On VMS, rename file and buffer to get rid of version number.
1681 (if (and (eq system-type 'vax-vms)
1682 (not (string= buffer-file-name
1683 (file-name-sans-versions buffer-file-name))))
1684 (let (buffer-new-name)
1685 ;; Strip VMS version number before save.
1686 (setq buffer-file-name
1687 (file-name-sans-versions buffer-file-name))
1688 ;; Construct a (unique) buffer name to correspond.
1689 (let ((buf (create-file-buffer (downcase buffer-file-name))))
1690 (setq buffer-new-name (buffer-name buf))
1692 (rename-buffer buffer-new-name)))
1693 ;; If buffer has no file name, ask user for one.
1694 (or buffer-file-name
1695 (set-visited-file-name
1696 (expand-file-name (read-file-name "File to save in: ") nil)))
1697 (or (verify-visited-file-modtime (current-buffer))
1698 (not (file-exists-p buffer-file-name))
1700 (format "%s has changed since visited or saved. Save anyway? "
1701 (file-name-nondirectory buffer-file-name)))
1702 (error "Save not confirmed"))
1705 (and (> (point-max) 1)
1706 (/= (char-after (1- (point-max))) ?\n)
1707 (not (and (eq selective-display t)
1708 (= (char-after (1- (point-max))) ?\r)))
1709 (or (eq require-final-newline t)
1710 (and require-final-newline
1712 (format "Buffer %s does not end in newline. Add one? "
1715 (goto-char (point-max))
1717 (or (run-hook-with-args-until-success 'write-contents-hooks)
1718 (run-hook-with-args-until-success 'local-write-file-hooks)
1719 (run-hook-with-args-until-success 'write-file-hooks)
1720 ;; If a hook returned t, file is already "written".
1721 ;; Otherwise, write it the usual way now.
1722 (setq setmodes (basic-save-buffer-1)))
1723 (setq buffer-file-number (nth 10 (file-attributes buffer-file-name)))
1726 (set-file-modes buffer-file-name setmodes)
1728 ;; If the auto-save file was recent before this command,
1730 (delete-auto-save-file-if-necessary recent-save)
1731 (run-hooks 'after-save-hook))
1732 (message "(No changes need to be saved)"))))
1734 ;; This does the "real job" of writing a buffer into its visited file
1735 ;; and making a backup file. This is what is normally done
1736 ;; but inhibited if one of write-file-hooks returns non-nil.
1737 ;; It returns a value to store in setmodes.
1738 (defun basic-save-buffer-1 ()
1739 (let (tempsetmodes setmodes)
1740 (if (not (file-writable-p buffer-file-name))
1741 (let ((dir (file-name-directory buffer-file-name)))
1742 (if (not (file-directory-p dir))
1743 (error "%s is not a directory" dir)
1744 (if (not (file-exists-p buffer-file-name))
1745 (error "Directory %s write-protected" dir)
1747 (format "File %s is write-protected; try to save anyway? "
1748 (file-name-nondirectory
1750 (setq tempsetmodes t)
1751 (error "Attempt to save to a file which you aren't allowed to write"))))))
1752 (or buffer-backed-up
1753 (setq setmodes (backup-buffer)))
1754 (let ((dir (file-name-directory buffer-file-name)))
1755 (if (and file-precious-flag
1756 (file-writable-p dir))
1757 ;; If file is precious, write temp name, then rename it.
1758 ;; This requires write access to the containing dir,
1759 ;; which is why we don't try it if we don't have that access.
1760 (let ((realname buffer-file-name)
1761 tempname temp nogood i succeed
1762 (old-modtime (visited-file-modtime)))
1765 ;; Find the temporary name to write under.
1767 (setq tempname (format "%s#tmp#%d" dir i))
1768 (setq nogood (file-exists-p tempname))
1771 (progn (clear-visited-file-modtime)
1772 (write-region (point-min) (point-max)
1773 tempname nil realname)
1775 ;; If writing the temp file fails,
1776 ;; delete the temp file.
1779 (delete-file tempname)
1780 (set-visited-file-modtime old-modtime))))
1781 ;; Since we have created an entirely new file
1782 ;; and renamed it, make sure it gets the
1783 ;; right permission bits set.
1784 (setq setmodes (file-modes buffer-file-name))
1785 ;; We succeeded in writing the temp file,
1787 (rename-file tempname buffer-file-name t))
1788 ;; If file not writable, see if we can make it writable
1789 ;; temporarily while we write it.
1790 ;; But no need to do so if we have just backed it up
1791 ;; (setmodes is set) because that says we're superseding.
1792 (cond ((and tempsetmodes (not setmodes))
1793 ;; Change the mode back, after writing.
1794 (setq setmodes (file-modes buffer-file-name))
1795 (set-file-modes buffer-file-name 511)))
1796 (write-region (point-min) (point-max)
1797 buffer-file-name nil t)))
1800 (defun save-some-buffers (&optional arg exiting)
1801 "Save some modified file-visiting buffers. Asks user about each one.
1802 Optional argument (the prefix) non-nil means save all with no questions.
1803 Optional second argument EXITING means ask about certain non-file buffers
1804 as well as about file buffers."
1806 (save-window-excursion
1811 (and (buffer-modified-p buffer)
1812 (not (buffer-base-buffer buffer))
1814 (buffer-file-name buffer)
1818 (and buffer-offer-save (> (buffer-size) 0)))))
1821 (if (buffer-file-name buffer)
1822 (format "Save file %s? "
1823 (buffer-file-name buffer))
1824 (format "Save buffer %s? "
1825 (buffer-name buffer)))))))
1831 '("buffer" "buffers" "save")
1832 (list (list ?\C-r (lambda (buf)
1834 (setq view-exit-action
1836 (exit-recursive-edit)))
1838 ;; Return nil to ask about BUF again.
1840 "display the current buffer"))))
1842 (and save-abbrevs abbrevs-changed
1845 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
1846 (write-abbrev-file nil))
1847 ;; Don't keep bothering user if he says no.
1848 (setq abbrevs-changed nil)
1850 (or (> files-done 0) abbrevs-done
1851 (message "(No files need saving)")))))
1853 (defun not-modified (&optional arg)
1854 "Mark current buffer as unmodified, not needing to be saved.
1855 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
1857 It is not a good idea to use this function in Lisp programs, because it
1858 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
1860 (message (if arg "Modification-flag set"
1861 "Modification-flag cleared"))
1862 (set-buffer-modified-p arg))
1864 (defun toggle-read-only (&optional arg)
1865 "Change whether this buffer is visiting its file read-only.
1866 With arg, set read-only iff arg is positive."
1868 (setq buffer-read-only
1870 (not buffer-read-only)
1871 (> (prefix-numeric-value arg) 0)))
1872 (force-mode-line-update))
1874 (defun insert-file (filename)
1875 "Insert contents of file FILENAME into buffer after point.
1876 Set mark after the inserted text.
1878 This function is meant for the user to run interactively.
1879 Don't call it from programs! Use `insert-file-contents' instead.
1880 \(Its calling sequence is different; see its documentation)."
1881 (interactive "*fInsert file: ")
1882 (if (file-directory-p filename)
1883 (signal 'file-error (list "Opening input file" "file is a directory"
1885 (let ((tem (insert-file-contents filename)))
1886 (push-mark (+ (point) (car (cdr tem))))))
1888 (defun append-to-file (start end filename)
1889 "Append the contents of the region to the end of file FILENAME.
1890 When called from a function, expects three arguments,
1891 START, END and FILENAME. START and END are buffer positions
1892 saying what text to write."
1893 (interactive "r\nFAppend to file: ")
1894 (write-region start end filename t))
1896 (defun file-newest-backup (filename)
1897 "Return most recent backup file for FILENAME or nil if no backups exist."
1898 (let* ((filename (expand-file-name filename))
1899 (file (file-name-nondirectory filename))
1900 (dir (file-name-directory filename))
1901 (comp (file-name-all-completions file dir))
1904 (setq file (concat dir (car comp))
1906 (if (and (backup-file-name-p file)
1907 (or (null newest) (file-newer-than-file-p file newest)))
1908 (setq newest file)))
1911 (defun rename-uniquely ()
1912 "Rename current buffer to a similar name not already taken.
1913 This function is useful for creating multiple shell process buffers
1914 or multiple mail buffers, etc."
1917 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
1918 (not (and buffer-file-name
1919 (string= (buffer-name)
1920 (file-name-nondirectory
1921 buffer-file-name)))))
1922 ;; If the existing buffer name has a <NNN>,
1923 ;; which isn't part of the file name (if any),
1924 ;; then get rid of that.
1925 (substring (buffer-name) 0 (match-beginning 0))
1927 (new-buf (generate-new-buffer base-name))
1928 (name (buffer-name new-buf)))
1929 (kill-buffer new-buf)
1930 (rename-buffer name)
1931 (force-mode-line-update))))
1933 (defun make-directory (dir &optional parents)
1934 "Create the directory DIR and any nonexistent parent dirs.
1935 Interactively, the default choice of directory to create
1936 is the current default directory for file names.
1937 That is useful when you have visited a file in a nonexistint directory.
1939 Noninteractively, the second (optional) argument PARENTS says whether
1940 to create parent directories if they don't exist."
1942 (list (read-file-name "Make directory: " default-directory default-directory
1945 (let ((handler (find-file-name-handler dir 'make-directory)))
1947 (funcall handler 'make-directory dir parents)
1949 (make-directory-internal dir)
1950 (let ((dir (directory-file-name (expand-file-name dir)))
1952 (while (not (file-exists-p dir))
1953 (setq create-list (cons dir create-list)
1954 dir (directory-file-name (file-name-directory dir))))
1956 (make-directory-internal (car create-list))
1957 (setq create-list (cdr create-list))))))))
1959 (put 'revert-buffer-function 'permanent-local t)
1960 (defvar revert-buffer-function nil
1961 "Function to use to revert this buffer, or nil to do the default.
1962 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
1963 which are the arguments that `revert-buffer' received.")
1965 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
1966 (defvar revert-buffer-insert-file-contents-function nil
1967 "Function to use to insert contents when reverting this buffer.
1968 Gets two args, first the nominal file name to use,
1969 and second, t if reading the auto-save file.")
1971 (defvar before-revert-hook nil
1972 "Normal hook for `revert-buffer' to run before reverting.
1973 If `revert-buffer-function' is used to override the normal revert
1974 mechanism, this hook is not used.")
1976 (defvar after-revert-hook nil
1977 "Normal hook for `revert-buffer' to run after reverting.
1978 Note that the hook value that it runs is the value that was in effect
1979 before reverting; that makes a difference if you have buffer-local
1982 If `revert-buffer-function' is used to override the normal revert
1983 mechanism, this hook is not used.")
1985 (defun revert-buffer (&optional ignore-auto noconfirm)
1986 "Replace the buffer text with the text of the visited file on disk.
1987 This undoes all changes since the file was visited or saved.
1988 With a prefix argument, offer to revert from latest auto-save file, if
1989 that is more recent than the visited file.
1991 When called from Lisp, the first argument is IGNORE-AUTO; only offer
1992 to revert from the auto-save file when this is nil. Note that the
1993 sense of this argument is the reverse of the prefix argument, for the
1994 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
1997 Optional second argument NOCONFIRM means don't ask for confirmation at
2000 If the value of `revert-buffer-function' is non-nil, it is called to
2003 The default revert function runs the hook `before-revert-hook' at the
2004 beginning and `after-revert-hook' at the end."
2005 ;; I admit it's odd to reverse the sense of the prefix argument, but
2006 ;; there is a lot of code out there which assumes that the first
2007 ;; argument should be t to avoid consulting the auto-save file, and
2008 ;; there's no straightforward way to encourage authors to notice a
2009 ;; reversal of the argument sense. So I'm just changing the user
2010 ;; interface, but leaving the programmatic interface the same.
2011 (interactive (list (not current-prefix-arg)))
2012 (if revert-buffer-function
2013 (funcall revert-buffer-function ignore-auto noconfirm)
2014 (let* ((opoint (point))
2015 (auto-save-p (and (not ignore-auto)
2016 (recent-auto-save-p)
2017 buffer-auto-save-file-name
2018 (file-readable-p buffer-auto-save-file-name)
2020 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2021 (file-name (if auto-save-p
2022 buffer-auto-save-file-name
2024 (cond ((null file-name)
2025 (error "Buffer does not seem to be associated with any file"))
2027 (yes-or-no-p (format "Revert buffer from file %s? "
2029 (run-hooks 'before-revert-hook)
2030 ;; If file was backed up but has changed since,
2031 ;; we shd make another backup.
2032 (and (not auto-save-p)
2033 (not (verify-visited-file-modtime (current-buffer)))
2034 (setq buffer-backed-up nil))
2035 ;; Get rid of all undo records for this buffer.
2036 (or (eq buffer-undo-list t)
2037 (setq buffer-undo-list nil))
2038 ;; Effectively copy the after-revert-hook status,
2039 ;; since after-find-file will clobber it.
2040 (let ((global-hook (default-value 'after-revert-hook))
2041 (local-hook-p (local-variable-p 'after-revert-hook))
2042 (local-hook (and (local-variable-p 'after-revert-hook)
2043 after-revert-hook)))
2044 (let (buffer-read-only
2045 ;; Don't make undo records for the reversion.
2046 (buffer-undo-list t))
2047 (if revert-buffer-insert-file-contents-function
2048 (funcall revert-buffer-insert-file-contents-function
2049 file-name auto-save-p)
2050 (if (not (file-exists-p file-name))
2051 (error "File %s no longer exists!" file-name))
2052 ;; Bind buffer-file-name to nil
2053 ;; so that we don't try to lock the file.
2054 (let ((buffer-file-name nil))
2058 (insert-file-contents file-name (not auto-save-p)
2060 (goto-char (min opoint (point-max)))
2061 ;; Recompute the truename in case changes in symlinks
2062 ;; have changed the truename.
2063 (setq buffer-file-truename
2064 (abbreviate-file-name (file-truename buffer-file-name)))
2065 (after-find-file nil nil t t)
2066 ;; Run after-revert-hook as it was before we reverted.
2067 (setq-default revert-buffer-internal-hook global-hook)
2070 (make-local-variable 'revert-buffer-internal-hook)
2071 (setq revert-buffer-internal-hook local-hook))
2072 (kill-local-variable 'revert-buffer-internal-hook))
2073 (run-hooks 'revert-buffer-internal-hook))
2076 (defun recover-file (file)
2077 "Visit file FILE, but get contents from its last auto-save file."
2078 ;; Actually putting the file name in the minibuffer should be used
2080 ;; Not just because users often use the default.
2081 (interactive "fRecover file: ")
2082 (setq file (expand-file-name file))
2083 (if (auto-save-file-name-p (file-name-nondirectory file))
2084 (error "%s is an auto-save file" file))
2085 (let ((file-name (let ((buffer-file-name file))
2086 (make-auto-save-file-name))))
2087 (cond ((not (file-newer-than-file-p file-name file))
2088 (error "Auto-save file %s not current" file-name))
2089 ((save-window-excursion
2090 (if (not (eq system-type 'vax-vms))
2091 (with-output-to-temp-buffer "*Directory*"
2092 (buffer-disable-undo standard-output)
2093 (call-process "ls" nil standard-output nil
2094 (if (file-symlink-p file) "-lL" "-l")
2096 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2097 (switch-to-buffer (find-file-noselect file t))
2098 (let ((buffer-read-only nil))
2100 (insert-file-contents file-name nil))
2101 (after-find-file nil nil t))
2102 (t (error "Recover-file cancelled.")))))
2104 (defun recover-session ()
2105 "Recover auto save files from a previous Emacs session.
2106 This command first displays a Dired buffer showing you the
2107 previous sessions that you could recover from.
2108 To choose one, move point to the proper line and then type C-c C-c.
2109 Then you'll be asked about a number of files to recover."
2112 (goto-char (point-min))
2113 (or (looking-at "Move to the session you want to recover,")
2114 (let ((inhibit-read-only t))
2115 (insert "Move to the session you want to recover,\n")
2116 (insert "then type C-c C-c to select it.\n\n")))
2117 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2118 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
2120 (defun recover-session-finish ()
2121 "Choose one saved session to recover auto-save files from.
2122 This command is used in the special Dired buffer created by
2123 \\[recover-session]."
2125 ;; Get the name of the session file to recover from.
2126 (let ((file (dired-get-filename))
2127 (buffer (get-buffer-create " *recover*")))
2130 ;; Read in the auto-save-list file.
2133 (insert-file-contents file)
2134 (map-y-or-n-p "Recover %s? "
2135 (lambda (file) (save-excursion (recover-file file)))
2140 (buffer-substring-no-properties
2141 (point) (progn (end-of-line) (point)))
2142 (while (and (eolp) (not (eobp)))
2143 (forward-line 2)))))
2144 '("file" "files" "recover")))
2145 (kill-buffer buffer))))
2147 (defun kill-some-buffers ()
2148 "For each buffer, ask whether to kill it."
2150 (let ((list (buffer-list)))
2152 (let* ((buffer (car list))
2153 (name (buffer-name buffer)))
2154 (and (not (string-equal name ""))
2155 (/= (aref name 0) ? )
2157 (format "Buffer %s %s. Kill? "
2159 (if (buffer-modified-p buffer)
2160 "HAS BEEN EDITED" "is unmodified")))
2161 (kill-buffer buffer)))
2162 (setq list (cdr list)))))
2164 (defun auto-save-mode (arg)
2165 "Toggle auto-saving of contents of current buffer.
2166 With prefix argument ARG, turn auto-saving on if positive, else off."
2168 (setq buffer-auto-save-file-name
2170 (or (not buffer-auto-save-file-name)
2171 ;; If autosave is off because buffer has shrunk,
2172 ;; then toggling should turn it on.
2173 (< buffer-saved-size 0))
2174 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2175 (if (and buffer-file-name auto-save-visited-file-name
2176 (not buffer-read-only))
2178 (make-auto-save-file-name))))
2179 ;; If -1 was stored here, to temporarily turn off saving,
2181 (and (< buffer-saved-size 0)
2182 (setq buffer-saved-size 0))
2184 (message "Auto-save %s (in this buffer)"
2185 (if buffer-auto-save-file-name "on" "off")))
2186 buffer-auto-save-file-name)
2188 (defun rename-auto-save-file ()
2189 "Adjust current buffer's auto save file name for current conditions.
2190 Also rename any existing auto save file, if it was made in this session."
2191 (let ((osave buffer-auto-save-file-name))
2192 (setq buffer-auto-save-file-name
2193 (make-auto-save-file-name))
2194 (if (and osave buffer-auto-save-file-name
2195 (not (string= buffer-auto-save-file-name buffer-file-name))
2196 (not (string= buffer-auto-save-file-name osave))
2197 (file-exists-p osave)
2198 (recent-auto-save-p))
2199 (rename-file osave buffer-auto-save-file-name t))))
2201 (defun make-auto-save-file-name ()
2202 "Return file name to use for auto-saves of current buffer.
2203 Does not consider `auto-save-visited-file-name' as that variable is checked
2204 before calling this function. You can redefine this for customization.
2205 See also `auto-save-file-name-p'."
2206 (if buffer-file-name
2207 (concat (file-name-directory buffer-file-name)
2209 (file-name-nondirectory buffer-file-name)
2212 ;; Deal with buffers that don't have any associated files. (Mail
2213 ;; mode tends to create a good number of these.)
2215 (let ((buffer-name (buffer-name))
2217 ;; Use technique from Sebastian Kremer's auto-save
2218 ;; package to turn slashes into \\!. This ensures that
2219 ;; the auto-save buffer name is unique.
2221 (while (string-match "[/\\]" buffer-name limit)
2222 (setq buffer-name (concat (substring buffer-name 0 (match-beginning 0))
2223 (if (string= (substring buffer-name
2229 (substring buffer-name (match-end 0))))
2230 (setq limit (1+ (match-end 0))))
2232 (expand-file-name (format "#%s#%s#" buffer-name (make-temp-name ""))))))
2234 (defun auto-save-file-name-p (filename)
2235 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2236 FILENAME should lack slashes. You can redefine this for customization."
2237 (string-match "^#.*#$" filename))
2239 (defconst list-directory-brief-switches
2240 (if (eq system-type 'vax-vms) "" "-CF")
2241 "*Switches for list-directory to pass to `ls' for brief listing,")
2243 (defconst list-directory-verbose-switches
2244 (if (eq system-type 'vax-vms)
2245 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2247 "*Switches for list-directory to pass to `ls' for verbose listing,")
2249 (defun list-directory (dirname &optional verbose)
2250 "Display a list of files in or matching DIRNAME, a la `ls'.
2251 DIRNAME is globbed by the shell if necessary.
2252 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2253 Actions controlled by variables `list-directory-brief-switches'
2254 and `list-directory-verbose-switches'."
2255 (interactive (let ((pfx current-prefix-arg))
2256 (list (read-file-name (if pfx "List directory (verbose): "
2257 "List directory (brief): ")
2258 nil default-directory nil)
2260 (let ((switches (if verbose list-directory-verbose-switches
2261 list-directory-brief-switches)))
2262 (or dirname (setq dirname default-directory))
2263 (setq dirname (expand-file-name dirname))
2264 (with-output-to-temp-buffer "*Directory*"
2265 (buffer-disable-undo standard-output)
2266 (princ "Directory ")
2270 (set-buffer "*Directory*")
2271 (let ((wildcard (not (file-directory-p dirname))))
2272 (insert-directory dirname switches wildcard (not wildcard)))))))
2274 (defvar insert-directory-program "ls"
2275 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2278 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2279 ;; FULL-DIRECTORY-P is nil.
2280 ;; The single line of output must display FILE's name as it was
2281 ;; given, namely, an absolute path name.
2282 ;; - must insert exactly one line for each file if WILDCARD or
2283 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
2284 ;; before the file lines, plus optional text after the file lines.
2285 ;; Lines are delimited by "\n", so filenames containing "\n" are not
2287 ;; File lines should display the basename.
2288 ;; - must be consistent with
2289 ;; - functions dired-move-to-filename, (these two define what a file line is)
2290 ;; dired-move-to-end-of-filename,
2291 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2292 ;; dired-insert-headerline
2293 ;; dired-after-subdir-garbage (defines what a "total" line is)
2294 ;; - variable dired-subdir-regexp
2295 (defun insert-directory (file switches &optional wildcard full-directory-p)
2296 "Insert directory listing for FILE, formatted according to SWITCHES.
2297 Leaves point after the inserted text.
2298 SWITCHES may be a string of options, or a list of strings.
2299 Optional third arg WILDCARD means treat FILE as shell wildcard.
2300 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2301 switches do not contain `d', so that a full listing is expected.
2303 This works by running a directory listing program
2304 whose name is in the variable `insert-directory-program'.
2305 If WILDCARD, it also runs the shell specified by `shell-file-name'."
2306 ;; We need the directory in order to find the right handler.
2307 (let ((handler (find-file-name-handler (expand-file-name file)
2308 'insert-directory)))
2310 (funcall handler 'insert-directory file switches
2311 wildcard full-directory-p)
2312 (if (eq system-type 'vax-vms)
2313 (vms-read-directory file switches (current-buffer))
2315 ;; Run ls in the directory of the file pattern we asked for.
2316 (let ((default-directory
2317 (if (file-name-absolute-p file)
2318 (file-name-directory file)
2319 (file-name-directory (expand-file-name file))))
2320 (pattern (file-name-nondirectory file))
2322 ;; Quote some characters that have special meanings in shells;
2323 ;; but don't quote the wildcards--we want them to be special.
2324 ;; We also currently don't quote the quoting characters
2325 ;; in case people want to use them explicitly to quote
2326 ;; wildcard characters.
2327 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
2329 (concat (substring pattern 0 (match-beginning 0))
2331 (substring pattern (match-beginning 0)))
2332 beg (1+ (match-end 0))))
2333 (call-process shell-file-name nil t nil
2334 "-c" (concat "\\" ;; Disregard shell aliases!
2335 insert-directory-program
2337 (if (stringp switches)
2339 (mapconcat 'identity switches " "))
2342 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2343 ;; directory if FILE is a symbolic link.
2344 (apply 'call-process
2345 insert-directory-program nil t nil
2347 (if (listp switches)
2348 (setq list switches)
2349 (if (not (equal switches ""))
2351 ;; Split the switches at any spaces
2352 ;; so we can pass separate options as separate args.
2353 (while (string-match " " switches)
2354 (setq list (cons (substring switches 0 (match-beginning 0))
2356 switches (substring switches (match-end 0))))
2357 (setq list (cons switches list)))))
2360 (if full-directory-p
2361 (concat (file-name-as-directory file) ".")
2364 (defvar kill-emacs-query-functions nil
2365 "Functions to call with no arguments to query about killing Emacs.
2366 If any of these functions returns nil, killing Emacs is cancelled.
2367 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
2368 but `kill-emacs', the low level primitive, does not.
2369 See also `kill-emacs-hook'.")
2371 (defun save-buffers-kill-emacs (&optional arg)
2372 "Offer to save each buffer, then kill this Emacs process.
2373 With prefix arg, silently save all file-visiting buffers, then kill."
2375 (save-some-buffers arg t)
2376 (and (or (not (memq t (mapcar (function
2377 (lambda (buf) (and (buffer-file-name buf)
2378 (buffer-modified-p buf))))
2380 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2381 (or (not (fboundp 'process-list))
2382 ;; process-list is not defined on VMS.
2383 (let ((processes (process-list))
2386 (and (memq (process-status (car processes)) '(run stop open))
2387 (let ((val (process-kill-without-query (car processes))))
2388 (process-kill-without-query (car processes) val)
2391 (setq processes (cdr processes)))
2393 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
2394 ;; Query the user for other things, perhaps.
2395 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
2398 (define-key ctl-x-map "\C-f" 'find-file)
2399 (define-key ctl-x-map "\C-q" 'toggle-read-only)
2400 (define-key ctl-x-map "\C-r" 'find-file-read-only)
2401 (define-key ctl-x-map "\C-v" 'find-alternate-file)
2402 (define-key ctl-x-map "\C-s" 'save-buffer)
2403 (define-key ctl-x-map "s" 'save-some-buffers)
2404 (define-key ctl-x-map "\C-w" 'write-file)
2405 (define-key ctl-x-map "i" 'insert-file)
2406 (define-key esc-map "~" 'not-modified)
2407 (define-key ctl-x-map "\C-d" 'list-directory)
2408 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
2410 (define-key ctl-x-4-map "f" 'find-file-other-window)
2411 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
2412 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
2413 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
2414 (define-key ctl-x-4-map "\C-o" 'display-buffer)
2416 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
2417 (define-key ctl-x-5-map "f" 'find-file-other-frame)
2418 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
2419 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
2421 ;;; files.el ends here