Delete misplaced comment.
[emacs.git] / lisp / files.el
blob1bba1ef7daeee72bc93d2a6fe7bbc12b1744daed
1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985, 86, 87, 92, 93, 94 Free Software Foundation, Inc.
5 ;; Maintainer: FSF
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)
12 ;; any later version.
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.
23 ;;; Commentary:
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.
29 ;;; Code:
31 (defconst delete-auto-save-files t
32 "*Non-nil means delete a buffer's auto-save file when the buffer is saved.")
34 (defconst directory-abbrev-alist
35 nil
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
94 '(lambda (name)
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, (abbreviated-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 (defvar version-control nil
136 "*Control use of version numbers for backup files.
137 t means make numeric backup versions unconditionally.
138 nil means make them for files that have some already.
139 `never' means do not make them.")
141 (defvar dired-kept-versions 2
142 "*When cleaning directory, number of versions to keep.")
144 (defvar trim-versions-without-asking nil
145 "*If t, deletes excess backup versions silently.
146 If nil, asks confirmation. Any other value prevents any trimming.")
148 (defvar kept-old-versions 2
149 "*Number of oldest versions to keep when a new numbered backup is made.")
151 (defvar kept-new-versions 2
152 "*Number of newest versions to keep when a new numbered backup is made.
153 Includes the new backup. Must be > 0")
155 (defconst require-final-newline nil
156 "*Value of t says silently ensure a file ends in a newline when it is saved.
157 Non-nil but not t says ask user whether to add a newline when there isn't one.
158 nil means don't add newlines.")
160 (defconst auto-save-default t
161 "*Non-nil says by default do auto-saving of every file-visiting buffer.")
163 (defconst auto-save-visited-file-name nil
164 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
165 Normally auto-save files are written under other names.")
167 (defconst save-abbrevs nil
168 "*Non-nil means save word abbrevs too when files are saved.
169 Loading an abbrev file sets this to t.")
171 (defconst find-file-run-dired t
172 "*Non-nil says run dired if `find-file' is given the name of a directory.")
174 ;;;It is not useful to make this a local variable.
175 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
176 (defvar find-file-not-found-hooks nil
177 "List of functions to be called for `find-file' on nonexistent file.
178 These functions are called as soon as the error is detected.
179 `buffer-file-name' is already set up.
180 The functions are called in the order given until one of them returns non-nil.")
182 ;;;It is not useful to make this a local variable.
183 ;;;(put 'find-file-hooks 'permanent-local t)
184 (defvar find-file-hooks nil
185 "List of functions to be called after a buffer is loaded from a file.
186 The buffer's local variables (if any) will have been processed before the
187 functions are called.")
189 (defvar write-file-hooks nil
190 "List of functions to be called before writing out a buffer to a file.
191 If one of them returns non-nil, the file is considered already written
192 and the rest are not called.
193 These hooks are considered to pertain to the visited file.
194 So this list is cleared if you change the visited file name.
195 See also `write-contents-hooks'.
196 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.")
197 ;;; However, in case someone does make it local...
198 (put 'write-file-hooks 'permanent-local t)
200 (defvar local-write-file-hooks nil
201 "Just like `write-file-hooks', except intended for per-buffer use.
202 The functions in this list are called before the ones in
203 `write-file-hooks'.")
204 (make-variable-buffer-local 'local-write-file-hooks)
205 (put 'local-write-file-hooks 'permanent-local t)
207 (defvar write-contents-hooks nil
208 "List of functions to be called before writing out a buffer to a file.
209 If one of them returns non-nil, the file is considered already written
210 and the rest are not called.
211 These hooks are considered to pertain to the buffer's contents,
212 not to the particular visited file; thus, `set-visited-file-name' does
213 not clear this variable, but changing the major mode does clear it.
214 See also `write-file-hooks'.")
216 (defconst enable-local-variables t
217 "*Control use of local-variables lists in files you visit.
218 The value can be t, nil or something else.
219 A value of t means local-variables lists are obeyed;
220 nil means they are ignored; anything else means query.
222 The command \\[normal-mode] always obeys local-variables lists
223 and ignores this variable.")
225 (defconst enable-local-eval 'maybe
226 "*Control processing of the \"variable\" `eval' in a file's local variables.
227 The value can be t, nil or something else.
228 A value of t means obey `eval' variables;
229 nil means ignore them; anything else means query.
231 The command \\[normal-mode] always obeys local-variables lists
232 and ignores this variable.")
234 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
235 (or (fboundp 'lock-buffer)
236 (defalias 'lock-buffer 'ignore))
237 (or (fboundp 'unlock-buffer)
238 (defalias 'unlock-buffer 'ignore))
240 ;; This hook function provides support for ange-ftp host name
241 ;; completion. It runs the usual ange-ftp hook, but only for
242 ;; completion operations. Having this here avoids the need
243 ;; to load ange-ftp when it's not really in use.
244 (defun ange-ftp-completion-hook-function (op &rest args)
245 (if (memq op '(file-name-completion file-name-all-completions))
246 (apply 'ange-ftp-hook-function op args)
247 (let (file-name-handler-alist)
248 (apply op args))))
250 (defun pwd ()
251 "Show the current default directory."
252 (interactive nil)
253 (message "Directory %s" default-directory))
255 (defvar cd-path nil
256 "Value of the CDPATH environment variable, as a list.
257 Not actually set up until the first time you you use it.")
259 (defun parse-colon-path (cd-path)
260 "Explode a colon-separated list of paths into a string list."
261 (and cd-path
262 (let (cd-prefix cd-list (cd-start 0) cd-colon)
263 (setq cd-path (concat cd-path ":"))
264 (while (setq cd-colon (string-match ":" cd-path cd-start))
265 (setq cd-list
266 (nconc cd-list
267 (list (if (= cd-start cd-colon)
269 (substitute-in-file-name
270 (file-name-as-directory
271 (substring cd-path cd-start cd-colon)))))))
272 (setq cd-start (+ cd-colon 1)))
273 cd-list)))
275 (defun cd-absolute (dir)
276 "Change current directory to given absolute file name DIR."
277 (setq dir (abbreviate-file-name (expand-file-name dir)))
278 (if (not (eq system-type 'vax-vms))
279 (setq dir (file-name-as-directory dir)))
280 (if (not (file-directory-p dir))
281 (error "%s is not a directory" dir)
282 (if (file-executable-p dir)
283 (setq default-directory dir)
284 (error "Cannot cd to %s: Permission denied" dir))))
286 (defun cd (dir)
287 "Make DIR become the current buffer's default directory.
288 If your environment includes a `CDPATH' variable, try each one of that
289 colon-separated list of directories when resolving a relative directory name."
290 (interactive "FChange default directory: ")
291 (if (file-name-absolute-p dir)
292 (cd-absolute (expand-file-name dir))
293 (if (null cd-path)
294 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
295 (setq cd-path (or trypath (list "./")))))
296 (if (not (catch 'found
297 (mapcar
298 (function (lambda (x)
299 (let ((f (expand-file-name (concat x dir))))
300 (if (file-directory-p f)
301 (progn
302 (cd-absolute f)
303 (throw 'found t))))))
304 cd-path)
305 nil))
306 (error "No such directory found via CDPATH environment variable"))))
308 (defun load-file (file)
309 "Load the Lisp file named FILE."
310 (interactive "fLoad file: ")
311 (load (expand-file-name file) nil nil t))
313 (defun load-library (library)
314 "Load the library named LIBRARY.
315 This is an interface to the function `load'."
316 (interactive "sLoad library: ")
317 (load library))
319 (defun file-local-copy (file &optional buffer)
320 "Copy the file FILE into a temporary file on this machine.
321 Returns the name of the local copy, or nil, if FILE is directly
322 accessible."
323 (let ((handler (find-file-name-handler file 'file-local-copy)))
324 (if handler
325 (funcall handler 'file-local-copy file)
326 nil)))
328 (defun file-truename (filename)
329 "Return the truename of FILENAME, which should be absolute.
330 The truename of a file name is found by chasing symbolic links
331 both at the level of the file and at the level of the directories
332 containing it, until no links are left at any level."
333 (if (or (string= filename "~")
334 (and (string= (substring filename 0 1) "~")
335 (string-match "~[^/]*" filename)))
336 (progn
337 (setq filename (expand-file-name filename))
338 (if (string= filename "")
339 (setq filename "/"))))
340 (let ((handler (find-file-name-handler filename 'file-truename)))
341 ;; For file name that has a special handler, call handler.
342 ;; This is so that ange-ftp can save time by doing a no-op.
343 (if handler
344 (funcall handler 'file-truename filename)
345 (let ((dir (file-name-directory filename))
346 target dirfile)
347 ;; Get the truename of the directory.
348 (setq dirfile (directory-file-name dir))
349 ;; If these are equal, we have the (or a) root directory.
350 (or (string= dir dirfile)
351 (setq dir (file-name-as-directory (file-truename dirfile))))
352 (if (equal ".." (file-name-nondirectory filename))
353 (directory-file-name (file-name-directory (directory-file-name dir)))
354 (if (equal "." (file-name-nondirectory filename))
355 (directory-file-name dir)
356 ;; Put it back on the file name.
357 (setq filename (concat dir (file-name-nondirectory filename)))
358 ;; Is the file name the name of a link?
359 (setq target (file-symlink-p filename))
360 (if target
361 ;; Yes => chase that link, then start all over
362 ;; since the link may point to a directory name that uses links.
363 ;; We can't safely use expand-file-name here
364 ;; since target might look like foo/../bar where foo
365 ;; is itself a link. Instead, we handle . and .. above.
366 (if (file-name-absolute-p target)
367 (file-truename target)
368 (file-truename (concat dir target)))
369 ;; No, we are done!
370 filename)))))))
372 (defun file-chase-links (filename)
373 "Chase links in FILENAME until a name that is not a link.
374 Does not examine containing directories for links,
375 unlike `file-truename'."
376 (let (tem (count 100) (newname filename))
377 (while (setq tem (file-symlink-p newname))
378 (if (= count 0)
379 (error "Apparent cycle of symbolic links for %s" filename))
380 ;; Handle `..' by hand, since it needs to work in the
381 ;; target of any directory symlink.
382 ;; This code is not quite complete; it does not handle
383 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
384 (while (string-match "\\.\\./" tem)
385 (setq tem (substring tem 3))
386 (setq newname (file-name-as-directory
387 ;; Do the .. by hand.
388 (directory-file-name
389 (file-name-directory
390 ;; Chase links in the default dir of the symlink.
391 (file-chase-links
392 (directory-file-name
393 (file-name-directory newname))))))))
394 (setq newname (expand-file-name tem (file-name-directory newname)))
395 (setq count (1- count)))
396 newname))
398 (defun switch-to-buffer-other-window (buffer)
399 "Select buffer BUFFER in another window."
400 (interactive "BSwitch to buffer in other window: ")
401 (let ((pop-up-windows t))
402 (pop-to-buffer buffer t)))
404 (defun switch-to-buffer-other-frame (buffer)
405 "Switch to buffer BUFFER in another frame."
406 (interactive "BSwitch to buffer in other frame: ")
407 (let ((pop-up-frames t))
408 (pop-to-buffer buffer t)))
410 (defun find-file (filename)
411 "Edit file FILENAME.
412 Switch to a buffer visiting file FILENAME,
413 creating one if none already exists."
414 (interactive "FFind file: ")
415 (switch-to-buffer (find-file-noselect filename)))
417 (defun find-file-other-window (filename)
418 "Edit file FILENAME, in another window.
419 May create a new window, or reuse an existing one.
420 See the function `display-buffer'."
421 (interactive "FFind file in other window: ")
422 (switch-to-buffer-other-window (find-file-noselect filename)))
424 (defun find-file-other-frame (filename)
425 "Edit file FILENAME, in another frame.
426 May create a new frame, or reuse an existing one.
427 See the function `display-buffer'."
428 (interactive "FFind file in other frame: ")
429 (switch-to-buffer-other-frame (find-file-noselect filename)))
431 (defun find-file-read-only (filename)
432 "Edit file FILENAME but don't allow changes.
433 Like \\[find-file] but marks buffer as read-only.
434 Use \\[toggle-read-only] to permit editing."
435 (interactive "fFind file read-only: ")
436 (find-file filename)
437 (setq buffer-read-only t)
438 (current-buffer))
440 (defun find-file-read-only-other-window (filename)
441 "Edit file FILENAME in another window but don't allow changes.
442 Like \\[find-file-other-window] but marks buffer as read-only.
443 Use \\[toggle-read-only] to permit editing."
444 (interactive "fFind file read-only other window: ")
445 (find-file-other-window filename)
446 (setq buffer-read-only t)
447 (current-buffer))
449 (defun find-file-read-only-other-frame (filename)
450 "Edit file FILENAME in another frame but don't allow changes.
451 Like \\[find-file-other-frame] but marks buffer as read-only.
452 Use \\[toggle-read-only] to permit editing."
453 (interactive "fFind file read-only other frame: ")
454 (find-file-other-frame filename)
455 (setq buffer-read-only t)
456 (current-buffer))
458 (defun find-alternate-file (filename)
459 "Find file FILENAME, select its buffer, kill previous buffer.
460 If the current buffer now contains an empty file that you just visited
461 \(presumably by mistake), use this command to visit the file you really want."
462 (interactive
463 (let ((file buffer-file-name)
464 (file-name nil)
465 (file-dir nil))
466 (and file
467 (setq file-name (file-name-nondirectory file)
468 file-dir (file-name-directory file)))
469 (list (read-file-name
470 "Find alternate file: " file-dir nil nil file-name))))
471 (and (buffer-modified-p)
472 ;; (not buffer-read-only)
473 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
474 (buffer-name))))
475 (error "Aborted"))
476 (let ((obuf (current-buffer))
477 (ofile buffer-file-name)
478 (onum buffer-file-number)
479 (otrue buffer-file-truename)
480 (oname (buffer-name)))
481 (rename-buffer " **lose**")
482 (setq buffer-file-name nil)
483 (setq buffer-file-number nil)
484 (setq buffer-file-truename nil)
485 (unwind-protect
486 (progn
487 (unlock-buffer)
488 (find-file filename))
489 (cond ((eq obuf (current-buffer))
490 (setq buffer-file-name ofile)
491 (setq buffer-file-number onum)
492 (setq buffer-file-truename otrue)
493 (lock-buffer)
494 (rename-buffer oname))))
495 (or (eq (current-buffer) obuf)
496 (kill-buffer obuf))))
498 (defun create-file-buffer (filename)
499 "Create a suitably named buffer for visiting FILENAME, and return it.
500 FILENAME (sans directory) is used unchanged if that name is free;
501 otherwise a string <2> or <3> or ... is appended to get an unused name."
502 (let ((lastname (file-name-nondirectory filename)))
503 (if (string= lastname "")
504 (setq lastname filename))
505 (generate-new-buffer lastname)))
507 (defun generate-new-buffer (name)
508 "Create and return a buffer with a name based on NAME.
509 Choose the buffer's name using `generate-new-buffer-name'."
510 (get-buffer-create (generate-new-buffer-name name)))
512 (defconst automount-dir-prefix "^/tmp_mnt/"
513 "Regexp to match the automounter prefix in a directory name.")
515 (defvar abbreviated-home-dir nil
516 "The user's homedir abbreviated according to `directory-abbrev-list'.")
518 (defun abbreviate-file-name (filename)
519 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
520 This also substitutes \"~\" for the user's home directory.
521 Type \\[describe-variable] directory-abbrev-alist RET for more information."
522 ;; Get rid of the prefixes added by the automounter.
523 (if (and (string-match automount-dir-prefix filename)
524 (file-exists-p (file-name-directory
525 (substring filename (1- (match-end 0))))))
526 (setq filename (substring filename (1- (match-end 0)))))
527 (let ((tail directory-abbrev-alist))
528 ;; If any elt of directory-abbrev-alist matches this name,
529 ;; abbreviate accordingly.
530 (while tail
531 (if (string-match (car (car tail)) filename)
532 (setq filename
533 (concat (cdr (car tail)) (substring filename (match-end 0)))))
534 (setq tail (cdr tail)))
535 ;; Compute and save the abbreviated homedir name.
536 ;; We defer computing this until the first time it's needed, to
537 ;; give time for directory-abbrev-alist to be set properly.
538 ;; We include a slash at the end, to avoid spurious matches
539 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
540 (or abbreviated-home-dir
541 (setq abbreviated-home-dir
542 (let ((abbreviated-home-dir "$foo"))
543 (concat "^" (abbreviate-file-name (expand-file-name "~"))
544 "\\(/\\|$\\)"))))
546 ;; If FILENAME starts with the abbreviated homedir,
547 ;; make it start with `~' instead.
548 (if (and (string-match abbreviated-home-dir filename)
549 ;; If the home dir is just /, don't change it.
550 (not (and (= (match-end 0) 1)
551 (= (aref filename 0) ?/))))
552 (setq filename
553 (concat "~"
554 ;; If abbreviated-home-dir ends with a slash,
555 ;; don't remove the corresponding slash from
556 ;; filename. On MS-DOS and OS/2, you can have
557 ;; home directories like "g:/", in which it is
558 ;; important not to remove the slash. And what
559 ;; about poor root on Unix systems?
560 (if (eq ?/ (aref abbreviated-home-dir
561 (1- (length abbreviated-home-dir))))
564 (substring filename (match-beginning 1) (match-end 1))
565 (substring filename (match-end 0)))))
566 filename))
568 (defvar find-file-not-true-dirname-list nil
569 "*List of logical names for which visiting shouldn't save the true dirname.
570 On VMS, when you visit a file using a logical name that searches a path,
571 you may or may not want the visited file name to record the specific
572 directory where the file was found. If you *do not* want that, add the logical
573 name to this list as a string.")
575 (defun find-buffer-visiting (filename)
576 "Return the buffer visiting file FILENAME (a string).
577 This is like `get-file-buffer', except that it checks for any buffer
578 visiting the same file, possibly under a different name.
579 If there is no such live buffer, return nil."
580 (let ((buf (get-file-buffer filename))
581 (truename (abbreviate-file-name (file-truename filename))))
582 (or buf
583 (let ((list (buffer-list)) found)
584 (while (and (not found) list)
585 (save-excursion
586 (set-buffer (car list))
587 (if (and buffer-file-name
588 (string= buffer-file-truename truename))
589 (setq found (car list))))
590 (setq list (cdr list)))
591 found)
592 (let ((number (nthcdr 10 (file-attributes truename)))
593 (list (buffer-list)) found)
594 (and number
595 (while (and (not found) list)
596 (save-excursion
597 (set-buffer (car list))
598 (if (and buffer-file-name
599 (equal buffer-file-number number)
600 ;; Verify this buffer's file number
601 ;; still belongs to its file.
602 (file-exists-p buffer-file-name)
603 (equal (nthcdr 10 (file-attributes buffer-file-name))
604 number))
605 (setq found (car list))))
606 (setq list (cdr list))))
607 found))))
609 (defun find-file-noselect (filename &optional nowarn)
610 "Read file FILENAME into a buffer and return the buffer.
611 If a buffer exists visiting FILENAME, return that one, but
612 verify that the file has not changed since visited or saved.
613 The buffer is not selected, just returned to the caller."
614 (setq filename
615 (abbreviate-file-name
616 (expand-file-name filename)))
617 (if (file-directory-p filename)
618 (if find-file-run-dired
619 (dired-noselect filename)
620 (error "%s is a directory." filename))
621 (let* ((buf (get-file-buffer filename))
622 (truename (abbreviate-file-name (file-truename filename)))
623 (number (nthcdr 10 (file-attributes truename)))
624 ;; Find any buffer for a file which has same truename.
625 (other (and (not buf) (find-buffer-visiting filename)))
626 error)
627 ;; Let user know if there is a buffer with the same truename.
628 (if other
629 (progn
630 (or nowarn (message "%s and %s are the same file"
631 filename (buffer-file-name other)))
632 ;; Optionally also find that buffer.
633 (if (or find-file-existing-other-name find-file-visit-truename)
634 (setq buf other))))
635 (if buf
636 (or nowarn
637 (verify-visited-file-modtime buf)
638 (cond ((not (file-exists-p filename))
639 (error "File %s no longer exists!" filename))
640 ((yes-or-no-p
641 (format
642 (if (buffer-modified-p buf)
643 "File %s changed on disk. Discard your edits? "
644 "File %s changed on disk. Read the new version? ")
645 (file-name-nondirectory filename)))
646 (save-excursion
647 (set-buffer buf)
648 (revert-buffer t t)))))
649 (save-excursion
650 ;;; The truename stuff makes this obsolete.
651 ;;; (let* ((link-name (car (file-attributes filename)))
652 ;;; (linked-buf (and (stringp link-name)
653 ;;; (get-file-buffer link-name))))
654 ;;; (if (bufferp linked-buf)
655 ;;; (message "Symbolic link to file in buffer %s"
656 ;;; (buffer-name linked-buf))))
657 (setq buf (create-file-buffer filename))
658 (set-buffer buf)
659 (erase-buffer)
660 (condition-case ()
661 (insert-file-contents filename t)
662 (file-error
663 (setq error t)
664 ;; Run find-file-not-found-hooks until one returns non-nil.
665 (let ((hooks find-file-not-found-hooks))
666 (while (and hooks
667 (not (and (funcall (car hooks))
668 ;; If a hook succeeded, clear error.
669 (progn (setq error nil)
670 ;; Also exit the loop.
671 t))))
672 (setq hooks (cdr hooks))))))
673 ;; Find the file's truename, and maybe use that as visited name.
674 (setq buffer-file-truename truename)
675 (setq buffer-file-number number)
676 ;; On VMS, we may want to remember which directory in a search list
677 ;; the file was found in.
678 (and (eq system-type 'vax-vms)
679 (let (logical)
680 (if (string-match ":" (file-name-directory filename))
681 (setq logical (substring (file-name-directory filename)
682 0 (match-beginning 0))))
683 (not (member logical find-file-not-true-dirname-list)))
684 (setq buffer-file-name buffer-file-truename))
685 (if find-file-visit-truename
686 (setq buffer-file-name
687 (setq filename
688 (expand-file-name buffer-file-truename))))
689 ;; Set buffer's default directory to that of the file.
690 (setq default-directory (file-name-directory filename))
691 ;; Turn off backup files for certain file names. Since
692 ;; this is a permanent local, the major mode won't eliminate it.
693 (and (not (funcall backup-enable-predicate buffer-file-name))
694 (progn
695 (make-local-variable 'backup-inhibited)
696 (setq backup-inhibited t)))
697 (after-find-file error (not nowarn))))
698 buf)))
700 (defun after-find-file (&optional error warn noauto)
701 "Called after finding a file and by the default revert function.
702 Sets buffer mode, parses local variables.
703 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
704 error in reading the file. WARN non-nil means warn if there
705 exists an auto-save file more recent than the visited file.
706 NOAUTO means don't mess with auto-save mode.
707 Finishes by calling the functions in `find-file-hooks'."
708 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
709 (if noninteractive
711 (let* (not-serious
712 (msg
713 (cond ((and error (file-attributes buffer-file-name))
714 (setq buffer-read-only t)
715 "File exists, but cannot be read.")
716 ((not buffer-read-only)
717 (if (and warn
718 (file-newer-than-file-p (make-auto-save-file-name)
719 buffer-file-name))
720 "Auto save file is newer; consider M-x recover-file"
721 (setq not-serious t)
722 (if error "(New file)" nil)))
723 ((not error)
724 (setq not-serious t)
725 "Note: file is write protected")
726 ((file-attributes (directory-file-name default-directory))
727 "File not found and directory write-protected")
728 ((file-exists-p (file-name-directory buffer-file-name))
729 (setq buffer-read-only nil))
731 (setq buffer-read-only nil)
732 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
733 "Use M-x make-dir RET RET to create the directory"
734 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
735 (if msg
736 (progn
737 (message msg)
738 (or not-serious (sit-for 1 nil t)))))
739 (if (and auto-save-default (not noauto))
740 (auto-save-mode t)))
741 (normal-mode t)
742 (mapcar 'funcall find-file-hooks))
744 (defun normal-mode (&optional find-file)
745 "Choose the major mode for this buffer automatically.
746 Also sets up any specified local variables of the file.
747 Uses the visited file name, the -*- line, and the local variables spec.
749 This function is called automatically from `find-file'. In that case,
750 we may set up specified local variables depending on the value of
751 `enable-local-variables': if it is t, we do; if it is nil, we don't;
752 otherwise, we query. `enable-local-variables' is ignored if you
753 run `normal-mode' explicitly."
754 (interactive)
755 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
756 (condition-case err
757 (set-auto-mode)
758 (error (message "File mode specification error: %s"
759 (prin1-to-string err))))
760 (condition-case err
761 (let ((enable-local-variables (or (not find-file)
762 enable-local-variables)))
763 (hack-local-variables))
764 (error (message "File local-variables error: %s"
765 (prin1-to-string err)))))
767 (defvar auto-mode-alist (mapcar 'purecopy
768 '(("\\.text\\'" . text-mode)
769 ("\\.c\\'" . c-mode)
770 ("\\.h\\'" . c-mode)
771 ("\\.tex\\'" . TeX-mode)
772 ("\\.ltx\\'" . LaTeX-mode)
773 ("\\.el\\'" . emacs-lisp-mode)
774 ("\\.mm\\'" . nroff-mode)
775 ("\\.me\\'" . nroff-mode)
776 ("\\.ms\\'" . nroff-mode)
777 ("\\.man\\'" . nroff-mode)
778 ("\\.scm\\'" . scheme-mode)
779 ("\\.l\\'" . lisp-mode)
780 ("\\.lisp\\'" . lisp-mode)
781 ("\\.f\\'" . fortran-mode)
782 ("\\.for\\'" . fortran-mode)
783 ("\\.p\\'" . pascal-mode)
784 ("\\.pas\\'" . pascal-mode)
785 ("\\.mss\\'" . scribe-mode)
786 ("\\.pl\\'" . prolog-mode)
787 ("\\.cc\\'" . c++-mode)
788 ("\\.hh\\'" . c++-mode)
789 ("\\.C\\'" . c++-mode)
790 ("\\.H\\'" . c++-mode)
791 ;;; ("\\.mk\\'" . makefile-mode)
792 ;;; ("[Mm]akefile" . makefile-mode)
793 ;;; Less common extensions come here
794 ;;; so more common ones above are found faster.
795 ("\\.texinfo\\'" . texinfo-mode)
796 ("\\.texi\\'" . texinfo-mode)
797 ("\\.s\\'" . asm-mode)
798 ("ChangeLog\\'" . change-log-mode)
799 ("change.log\\'" . change-log-mode)
800 ("changelo\\'" . change-log-mode)
801 ("ChangeLog.[0-9]+\\'" . change-log-mode)
802 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
803 ;; The following should come after the ChangeLog pattern
804 ;; for the sake of ChangeLog.1, etc.
805 ("\\.[12345678]\\'" . nroff-mode)
806 ("\\.TeX\\'" . TeX-mode)
807 ("\\.sty\\'" . LaTeX-mode)
808 ("\\.bbl\\'" . LaTeX-mode)
809 ("\\.bib\\'" . bibtex-mode)
810 ("\\.article\\'" . text-mode)
811 ("\\.letter\\'" . text-mode)
812 ("\\.tcl\\'" . tcl-mode)
813 ("\\.lsp\\'" . lisp-mode)
814 ("\\.awk\\'" . awk-mode)
815 ("\\.prolog\\'" . prolog-mode)
816 ("\\.tar\\'" . tar-mode)
817 ;; Mailer puts message to be edited in
818 ;; /tmp/Re.... or Message
819 ("^/tmp/Re" . text-mode)
820 ("/Message[0-9]*\\'" . text-mode)
821 ;; some news reader is reported to use this
822 ("^/tmp/fol/" . text-mode)
823 ("\\.y\\'" . c-mode)
824 ("\\.lex\\'" . c-mode)
825 ("\\.oak\\'" . scheme-mode)
826 ("\\.scm.[0-9]*\\'" . scheme-mode)
827 ("\\.sgm\\'" . sgml-mode)
828 ("\\.sgml\\'" . sgml-mode)
829 ("\\.dtd\\'" . sgml-mode)
830 ;; .emacs following a directory delimiter
831 ;; in either Unix or VMS syntax.
832 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
833 ;; _emacs following a directory delimiter
834 ;; in MsDos syntax
835 ("[:/]_emacs\\'" . emacs-lisp-mode)
836 ("\\.ml\\'" . lisp-mode)))
838 Alist of filename patterns vs corresponding major mode functions.
839 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION).
840 Visiting a file whose name matches REGEXP causes FUNCTION to be called.
841 If the element has the form (REGEXP FUNCTION), then after calling
842 FUNCTION, we delete the suffix that matched REGEXP and search the list
843 again for another match.")
845 (defconst interpreter-mode-alist
846 '(("perl" . perl-mode)
847 ("scope" . tcl-mode)
848 ("wish" . tcl-mode)
849 ("shell" . tcl-mode)
850 ("form" . tcl-mode)
851 ("tcl" . tcl-mode)
852 ("awk" . awk-mode)
853 ("gawk" . awk-mode)
854 ("scm" . scheme-mode))
855 "Alist mapping interpreter names to major modes.
856 This alist applies to files whose first line starts with `#!'.
857 Each element looks like (INTERPRETER . MODE).
858 The car of each element is compared with
859 the name of the interpreter specified in the first line.
860 If it matches, mode MODE is selected.")
862 (defconst inhibit-first-line-modes-regexps '("\\.tar$")
863 "List of regexps; if one matches a file name, don't look for `-*-'.")
865 (defvar user-init-file
866 "" ; set by command-line
867 "File name including directory of user's initialization file.")
869 (defun set-auto-mode ()
870 "Select major mode appropriate for current buffer.
871 This checks for a -*- mode tag in the buffer's text, or
872 compares the filename against the entries in `auto-mode-alist'. It does
873 not check for the \"mode:\" local variable in the Local Variables
874 section of the file; for that, use `hack-local-variables'.
876 If `enable-local-variables' is nil, this function does not check for a
877 -*- mode tag."
878 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
879 (let (beg end done)
880 (save-excursion
881 (goto-char (point-min))
882 (skip-chars-forward " \t\n")
883 (and enable-local-variables
884 ;; Don't look for -*- if this file name matches any
885 ;; of the regexps in inhibit-first-line-modes-regexps.
886 (let ((temp inhibit-first-line-modes-regexps))
887 (while (and temp
888 (not (string-match (car temp)
889 buffer-file-name)))
890 (setq temp (cdr temp)))
891 (not temp))
892 (search-forward "-*-" (save-excursion
893 ;; If the file begins with "#!"
894 ;; (exec interpreter magic), look
895 ;; for mode frobs in the first two
896 ;; lines. You cannot necessarily
897 ;; put them in the first line of
898 ;; such a file without screwing up
899 ;; the interpreter invocation.
900 (end-of-line (and (looking-at "^#!") 2))
901 (point)) t)
902 (progn
903 (skip-chars-forward " \t")
904 (setq beg (point))
905 (search-forward "-*-"
906 (save-excursion (end-of-line) (point))
908 (progn
909 (forward-char -3)
910 (skip-chars-backward " \t")
911 (setq end (point))
912 (goto-char beg)
913 (if (save-excursion (search-forward ":" end t))
914 ;; Find all specifications for the `mode:' variable
915 ;; and execute them left to right.
916 (while (let ((case-fold-search t))
917 (search-forward "mode:" end t))
918 (skip-chars-forward " \t")
919 (setq beg (point))
920 (if (search-forward ";" end t)
921 (forward-char -1)
922 (goto-char end))
923 (skip-chars-backward " \t")
924 (funcall (intern (concat (downcase (buffer-substring beg (point))) "-mode"))))
925 ;; Simple -*-MODE-*- case.
926 (funcall (intern (concat (downcase (buffer-substring beg end)) "-mode"))))
927 (setq done t)))
928 ;; If we didn't find a mode from a -*- line, try using the file name.
929 (if (and (not done) buffer-file-name)
930 (let ((name buffer-file-name)
931 (case-fold-search (eq system-type 'vax-vms))
932 (keep-going t))
933 ;; Remove backup-suffixes from file name.
934 (setq name (file-name-sans-versions name))
935 (while keep-going
936 (setq keep-going nil)
937 (let ((alist auto-mode-alist)
938 (mode nil))
939 ;; Find first matching alist entry.
940 (while (and (not mode) alist)
941 (if (string-match (car (car alist)) name)
942 (if (and (consp (cdr (car alist)))
943 (nth 2 (car alist)))
944 (progn
945 (setq mode (car (cdr (car alist)))
946 name (substring name 0 (match-beginning 0))
947 keep-going t))
948 (setq mode (cdr (car alist))
949 keep-going nil)))
950 (setq alist (cdr alist)))
951 (if mode
952 (funcall mode)
953 ;; If we can't deduce a mode from the file name,
954 ;; look for an interpreter specified in the first line.
955 (let ((interpreter
956 (save-excursion
957 (goto-char (point-min))
958 (if (looking-at "#! *")
959 (progn
960 (goto-char (match-end 0))
961 (buffer-substring (point)
962 (progn (end-of-line) (point))))
963 "")))
964 elt)
965 ;; Map interpreter name to a mode.
966 (setq elt (assoc (file-name-nondirectory interpreter)
967 interpreter-mode-alist))
968 (if elt
969 (funcall (cdr elt))))))))))))
971 (defun hack-local-variables-prop-line ()
972 ;; Set local variables specified in the -*- line.
973 ;; Ignore any specification for `mode:';
974 ;; set-auto-mode should already have handled that.
975 (save-excursion
976 (goto-char (point-min))
977 (let ((result nil)
978 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
979 ;; Parse the -*- line into the `result' alist.
980 (cond ((not (search-forward "-*-" end t))
981 ;; doesn't have one.
982 nil)
983 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
984 ;; Simple form: "-*- MODENAME -*-". Already handled.
985 nil)
987 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
988 ;; (last ";" is optional).
989 (save-excursion
990 (if (search-forward "-*-" end t)
991 (setq end (- (point) 3))
992 (error "-*- not terminated before end of line")))
993 (while (< (point) end)
994 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
995 (error "malformed -*- line"))
996 (goto-char (match-end 0))
997 (let ((key (intern (downcase (buffer-substring
998 (match-beginning 1)
999 (match-end 1)))))
1000 (val (save-restriction
1001 (narrow-to-region (point) end)
1002 (read (current-buffer)))))
1003 (or (eq key 'mode)
1004 (setq result (cons (cons key val) result)))
1005 (skip-chars-forward " \t;")))
1006 (setq result (nreverse result))))
1008 (if (and result
1009 (or (eq enable-local-variables t)
1010 (and enable-local-variables
1011 (save-window-excursion
1012 (condition-case nil
1013 (switch-to-buffer (current-buffer))
1014 (error
1015 ;; If we fail to switch in the selected window,
1016 ;; it is probably a minibuffer.
1017 ;; So try another window.
1018 (condition-case nil
1019 (switch-to-buffer-other-window (current-buffer))
1020 (error
1021 (switch-to-buffer-other-frame (current-buffer))))))
1022 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1023 (file-name-nondirectory buffer-file-name)))))))
1024 (while result
1025 (hack-one-local-variable (car (car result)) (cdr (car result)))
1026 (setq result (cdr result)))))))
1028 (defun hack-local-variables ()
1029 "Parse and put into effect this buffer's local variables spec."
1030 (hack-local-variables-prop-line)
1031 ;; Look for "Local variables:" line in last page.
1032 (save-excursion
1033 (goto-char (point-max))
1034 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1035 (if (let ((case-fold-search t))
1036 (and (search-forward "Local Variables:" nil t)
1037 (or (eq enable-local-variables t)
1038 (and enable-local-variables
1039 (save-window-excursion
1040 (switch-to-buffer (current-buffer))
1041 (save-excursion
1042 (beginning-of-line)
1043 (set-window-start (selected-window) (point)))
1044 (y-or-n-p (format "Set local variables as specified at end of %s? "
1045 (if buffer-file-name
1046 (file-name-nondirectory
1047 buffer-file-name)
1048 (concat "buffer "
1049 (buffer-name))))))))))
1050 (let ((continue t)
1051 prefix prefixlen suffix beg
1052 (enable-local-eval enable-local-eval))
1053 ;; The prefix is what comes before "local variables:" in its line.
1054 ;; The suffix is what comes after "local variables:" in its line.
1055 (skip-chars-forward " \t")
1056 (or (eolp)
1057 (setq suffix (buffer-substring (point)
1058 (progn (end-of-line) (point)))))
1059 (goto-char (match-beginning 0))
1060 (or (bolp)
1061 (setq prefix
1062 (buffer-substring (point)
1063 (progn (beginning-of-line) (point)))))
1065 (if prefix (setq prefixlen (length prefix)
1066 prefix (regexp-quote prefix)))
1067 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1068 (while continue
1069 ;; Look at next local variable spec.
1070 (if selective-display (re-search-forward "[\n\C-m]")
1071 (forward-line 1))
1072 ;; Skip the prefix, if any.
1073 (if prefix
1074 (if (looking-at prefix)
1075 (forward-char prefixlen)
1076 (error "Local variables entry is missing the prefix")))
1077 ;; Find the variable name; strip whitespace.
1078 (skip-chars-forward " \t")
1079 (setq beg (point))
1080 (skip-chars-forward "^:\n")
1081 (if (eolp) (error "Missing colon in local variables entry"))
1082 (skip-chars-backward " \t")
1083 (let* ((str (buffer-substring beg (point)))
1084 (var (read str))
1085 val)
1086 ;; Setting variable named "end" means end of list.
1087 (if (string-equal (downcase str) "end")
1088 (setq continue nil)
1089 ;; Otherwise read the variable value.
1090 (skip-chars-forward "^:")
1091 (forward-char 1)
1092 (setq val (read (current-buffer)))
1093 (skip-chars-backward "\n")
1094 (skip-chars-forward " \t")
1095 (or (if suffix (looking-at suffix) (eolp))
1096 (error "Local variables entry is terminated incorrectly"))
1097 ;; Set the variable. "Variables" mode and eval are funny.
1098 (hack-one-local-variable var val))))))))
1100 (defconst ignored-local-variables
1101 '(enable-local-eval)
1102 "Variables to be ignored in a file's local variable spec.")
1104 ;; Get confirmation before setting these variables as locals in a file.
1105 (put 'eval 'risky-local-variable t)
1106 (put 'file-name-handler-alist 'risky-local-variable t)
1107 (put 'minor-mode-map-alist 'risky-local-variable t)
1108 (put 'after-load-alist 'risky-local-variable t)
1110 ;; "Set" one variable in a local variables spec.
1111 ;; A few variable names are treated specially.
1112 (defun hack-one-local-variable (var val)
1113 (cond ((eq var 'mode)
1114 (funcall (intern (concat (downcase (symbol-name val))
1115 "-mode"))))
1116 ((memq var ignored-local-variables)
1117 nil)
1118 ;; "Setting" eval means either eval it or do nothing.
1119 ;; Likewise for setting hook variables.
1120 ((or (get var 'risky-local-variable)
1121 (string-match "-hooks?$\\|-functions?$\\|-forms?$"
1122 (symbol-name var)))
1123 (if (and (not (string= (user-login-name) "root"))
1124 (or (eq enable-local-eval t)
1125 (and enable-local-eval
1126 (save-window-excursion
1127 (switch-to-buffer (current-buffer))
1128 (save-excursion
1129 (beginning-of-line)
1130 (set-window-start (selected-window) (point)))
1131 (setq enable-local-eval
1132 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1133 (file-name-nondirectory buffer-file-name))))))))
1134 (if (eq var 'eval)
1135 (save-excursion (eval val))
1136 (make-local-variable var)
1137 (set var val))
1138 (message "Ignoring `eval:' in file's local variables")))
1139 ;; Ordinary variable, really set it.
1140 (t (make-local-variable var)
1141 (set var val))))
1144 (defun set-visited-file-name (filename)
1145 "Change name of file visited in current buffer to FILENAME.
1146 The next time the buffer is saved it will go in the newly specified file.
1147 nil or empty string as argument means make buffer not be visiting any file.
1148 Remember to delete the initial contents of the minibuffer
1149 if you wish to pass an empty string as the argument."
1150 (interactive "FSet visited file name: ")
1151 (if filename
1152 (setq filename
1153 (if (string-equal filename "")
1155 (expand-file-name filename))))
1156 (or (equal filename buffer-file-name)
1157 (progn
1158 (and filename (lock-buffer filename))
1159 (unlock-buffer)))
1160 (setq buffer-file-name filename)
1161 (if filename ; make buffer name reflect filename.
1162 (let ((new-name (file-name-nondirectory buffer-file-name)))
1163 (if (string= new-name "")
1164 (error "Empty file name"))
1165 (if (eq system-type 'vax-vms)
1166 (setq new-name (downcase new-name)))
1167 (setq default-directory (file-name-directory buffer-file-name))
1168 (or (string= new-name (buffer-name))
1169 (rename-buffer new-name t))))
1170 (setq buffer-backed-up nil)
1171 (clear-visited-file-modtime)
1172 (if filename
1173 (progn
1174 (setq buffer-file-truename
1175 (abbreviate-file-name (file-truename buffer-file-name)))
1176 (if find-file-visit-truename
1177 (setq buffer-file-name buffer-file-truename))
1178 (setq buffer-file-number (nth 10 (file-attributes buffer-file-name))))
1179 (setq buffer-file-truename nil buffer-file-number nil))
1180 ;; write-file-hooks is normally used for things like ftp-find-file
1181 ;; that visit things that are not local files as if they were files.
1182 ;; Changing to visit an ordinary local file instead should flush the hook.
1183 (kill-local-variable 'write-file-hooks)
1184 (kill-local-variable 'local-write-file-hooks)
1185 (kill-local-variable 'revert-buffer-function)
1186 (kill-local-variable 'backup-inhibited)
1187 ;; If buffer was read-only because of version control,
1188 ;; that reason is gone now, so make it writable.
1189 (if vc-mode
1190 (setq buffer-read-only nil))
1191 (kill-local-variable 'vc-mode)
1192 ;; Turn off backup files for certain file names.
1193 ;; Since this is a permanent local, the major mode won't eliminate it.
1194 (and (not (funcall backup-enable-predicate buffer-file-name))
1195 (progn
1196 (make-local-variable 'backup-inhibited)
1197 (setq backup-inhibited t)))
1198 (let ((oauto buffer-auto-save-file-name))
1199 ;; If auto-save was not already on, turn it on if appropriate.
1200 (if (not buffer-auto-save-file-name)
1201 (and buffer-file-name auto-save-default
1202 (auto-save-mode t))
1203 ;; If auto save is on, start using a new name.
1204 ;; We deliberately don't rename or delete the old auto save
1205 ;; for the old visited file name. This is because perhaps
1206 ;; the user wants to save the new state and then compare with the
1207 ;; previous state from the auto save file.
1208 (setq buffer-auto-save-file-name
1209 (make-auto-save-file-name)))
1210 ;; Rename the old auto save file if any.
1211 (and oauto buffer-auto-save-file-name
1212 (file-exists-p oauto)
1213 (rename-file oauto buffer-auto-save-file-name t)))
1214 (if buffer-file-name
1215 (set-buffer-modified-p t)))
1217 (defun write-file (filename)
1218 "Write current buffer into file FILENAME.
1219 Makes buffer visit that file, and marks it not modified.
1220 If the buffer is already visiting a file, you can specify
1221 a directory name as FILENAME, to write a file of the same
1222 old name in that directory."
1223 ;; (interactive "FWrite file: ")
1224 (interactive
1225 (list (if buffer-file-name
1226 (read-file-name "Write file: "
1227 nil nil nil nil)
1228 (read-file-name "Write file: "
1229 (cdr (assq 'default-directory
1230 (buffer-local-variables)))
1231 nil nil (buffer-name)))))
1232 (or (null filename) (string-equal filename "")
1233 (progn
1234 ;; If arg is just a directory,
1235 ;; use same file name, but in that directory.
1236 (if (and (file-directory-p filename) buffer-file-name)
1237 (setq filename (concat (file-name-as-directory filename)
1238 (file-name-nondirectory buffer-file-name))))
1239 (set-visited-file-name filename)))
1240 (set-buffer-modified-p t)
1241 (save-buffer))
1243 (defun backup-buffer ()
1244 "Make a backup of the disk file visited by the current buffer, if appropriate.
1245 This is normally done before saving the buffer the first time.
1246 If the value is non-nil, it is the result of `file-modes' on the original
1247 file; this means that the caller, after saving the buffer, should change
1248 the modes of the new file to agree with the old modes."
1249 (if (and make-backup-files (not backup-inhibited)
1250 (not buffer-backed-up)
1251 (file-exists-p buffer-file-name)
1252 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1253 '(?- ?l)))
1254 (let ((real-file-name buffer-file-name)
1255 backup-info backupname targets setmodes)
1256 ;; If specified name is a symbolic link, chase it to the target.
1257 ;; Thus we make the backups in the directory where the real file is.
1258 (setq real-file-name (file-chase-links real-file-name))
1259 (setq backup-info (find-backup-file-name real-file-name)
1260 backupname (car backup-info)
1261 targets (cdr backup-info))
1262 ;;; (if (file-directory-p buffer-file-name)
1263 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1264 (condition-case ()
1265 (let ((delete-old-versions
1266 ;; If have old versions to maybe delete,
1267 ;; ask the user to confirm now, before doing anything.
1268 ;; But don't actually delete til later.
1269 (and targets
1270 (or (eq trim-versions-without-asking t) (eq trim-versions-without-asking nil))
1271 (or trim-versions-without-asking
1272 (y-or-n-p (format "Delete excess backup versions of %s? "
1273 real-file-name))))))
1274 ;; Actually write the back up file.
1275 (condition-case ()
1276 (if (or file-precious-flag
1277 ; (file-symlink-p buffer-file-name)
1278 backup-by-copying
1279 (and backup-by-copying-when-linked
1280 (> (file-nlinks real-file-name) 1))
1281 (and backup-by-copying-when-mismatch
1282 (let ((attr (file-attributes real-file-name)))
1283 (or (nth 9 attr)
1284 (/= (nth 2 attr) (user-uid))))))
1285 (condition-case ()
1286 (copy-file real-file-name backupname t t)
1287 (file-error
1288 ;; If copying fails because file BACKUPNAME
1289 ;; is not writable, delete that file and try again.
1290 (if (and (file-exists-p backupname)
1291 (not (file-writable-p backupname)))
1292 (delete-file backupname))
1293 (copy-file real-file-name backupname t t)))
1294 ;; rename-file should delete old backup.
1295 (rename-file real-file-name backupname t)
1296 (setq setmodes (file-modes backupname)))
1297 (file-error
1298 ;; If trouble writing the backup, write it in ~.
1299 (setq backupname (expand-file-name "~/%backup%~"))
1300 (message "Cannot write backup file; backing up in ~/%%backup%%~")
1301 (sleep-for 1)
1302 (condition-case ()
1303 (copy-file real-file-name backupname t t)
1304 (file-error
1305 ;; If copying fails because file BACKUPNAME
1306 ;; is not writable, delete that file and try again.
1307 (if (and (file-exists-p backupname)
1308 (not (file-writable-p backupname)))
1309 (delete-file backupname))
1310 (copy-file real-file-name backupname t t)))))
1311 (setq buffer-backed-up t)
1312 ;; Now delete the old versions, if desired.
1313 (if delete-old-versions
1314 (while targets
1315 (condition-case ()
1316 (delete-file (car targets))
1317 (file-error nil))
1318 (setq targets (cdr targets))))
1319 setmodes)
1320 (file-error nil)))))
1322 (defun file-name-sans-versions (name &optional keep-backup-version)
1323 "Return FILENAME sans backup versions or strings.
1324 This is a separate procedure so your site-init or startup file can
1325 redefine it.
1326 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1327 we do not remove backup version numbers, only true file version numbers."
1328 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1329 (if handler
1330 (funcall handler 'file-name-sans-versions name keep-backup-version)
1331 (substring name 0
1332 (if (eq system-type 'vax-vms)
1333 ;; VMS version number is (a) semicolon, optional
1334 ;; sign, zero or more digits or (b) period, option
1335 ;; sign, zero or more digits, provided this is the
1336 ;; second period encountered outside of the
1337 ;; device/directory part of the file name.
1338 (or (string-match ";[-+]?[0-9]*\\'" name)
1339 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1340 name)
1341 (match-beginning 1))
1342 (length name))
1343 (if keep-backup-version
1344 (length name)
1345 (or (string-match "\\.~[0-9]+~\\'" name)
1346 (string-match "~\\'" name)
1347 (length name))))))))
1349 (defun make-backup-file-name (file)
1350 "Create the non-numeric backup file name for FILE.
1351 This is a separate function so you can redefine it for customization."
1352 (if (eq system-type 'ms-dos)
1353 (let ((fn (file-name-nondirectory file)))
1354 (concat (file-name-directory file)
1355 (if (string-match "\\([^.]*\\)\\(\\..*\\)?" fn)
1356 (substring fn 0 (match-end 1)))
1357 ".bak"))
1358 (concat file "~")))
1360 (defun backup-file-name-p (file)
1361 "Return non-nil if FILE is a backup file name (numeric or not).
1362 This is a separate function so you can redefine it for customization.
1363 You may need to redefine `file-name-sans-versions' as well."
1364 (if (eq system-type 'ms-dos)
1365 (string-match "\\.bak$" file)
1366 (string-match "~$" file)))
1368 ;; This is used in various files.
1369 ;; The usage of bv-length is not very clean,
1370 ;; but I can't see a good alternative,
1371 ;; so as of now I am leaving it alone.
1372 (defun backup-extract-version (fn)
1373 "Given the name of a numeric backup file, return the backup number.
1374 Uses the free variable `bv-length', whose value should be
1375 the index in the name where the version number begins."
1376 (if (and (string-match "[0-9]+~$" fn bv-length)
1377 (= (match-beginning 0) bv-length))
1378 (string-to-int (substring fn bv-length -1))
1381 ;; I believe there is no need to alter this behavior for VMS;
1382 ;; since backup files are not made on VMS, it should not get called.
1383 (defun find-backup-file-name (fn)
1384 "Find a file name for a backup file, and suggestions for deletions.
1385 Value is a list whose car is the name for the backup file
1386 and whose cdr is a list of old versions to consider deleting now."
1387 (if (eq version-control 'never)
1388 (list (make-backup-file-name fn))
1389 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1390 (bv-length (length base-versions))
1391 possibilities
1392 (versions nil)
1393 (high-water-mark 0)
1394 (deserve-versions-p nil)
1395 (number-to-delete 0))
1396 (condition-case ()
1397 (setq possibilities (file-name-all-completions
1398 base-versions
1399 (file-name-directory fn))
1400 versions (sort (mapcar
1401 (function backup-extract-version)
1402 possibilities)
1404 high-water-mark (apply 'max 0 versions)
1405 deserve-versions-p (or version-control
1406 (> high-water-mark 0))
1407 number-to-delete (- (length versions)
1408 kept-old-versions kept-new-versions -1))
1409 (file-error
1410 (setq possibilities nil)))
1411 (if (not deserve-versions-p)
1412 (list (make-backup-file-name fn))
1413 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
1414 (if (and (> number-to-delete 0)
1415 ;; Delete nothing if there is overflow
1416 ;; in the number of versions to keep.
1417 (>= (+ kept-new-versions kept-old-versions -1) 0))
1418 (mapcar (function (lambda (n)
1419 (concat fn ".~" (int-to-string n) "~")))
1420 (let ((v (nthcdr kept-old-versions versions)))
1421 (rplacd (nthcdr (1- number-to-delete) v) ())
1422 v))))))))
1424 (defun file-nlinks (filename)
1425 "Return number of names file FILENAME has."
1426 (car (cdr (file-attributes filename))))
1428 (defun file-relative-name (filename &optional directory)
1429 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1430 (setq filename (expand-file-name filename)
1431 directory (file-name-as-directory (expand-file-name
1432 (or directory default-directory))))
1433 (let ((ancestor ""))
1434 (while (not (string-match (concat "^" (regexp-quote directory)) filename))
1435 (setq directory (file-name-directory (substring directory 0 -1))
1436 ancestor (concat "../" ancestor)))
1437 (concat ancestor (substring filename (match-end 0)))))
1439 (defun save-buffer (&optional args)
1440 "Save current buffer in visited file if modified. Versions described below.
1441 By default, makes the previous version into a backup file
1442 if previously requested or if this is the first save.
1443 With 1 or 3 \\[universal-argument]'s, marks this version
1444 to become a backup when the next save is done.
1445 With 2 or 3 \\[universal-argument]'s,
1446 unconditionally makes the previous version into a backup file.
1447 With argument of 0, never makes the previous version into a backup file.
1449 If a file's name is FOO, the names of its numbered backup versions are
1450 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1451 Numeric backups (rather than FOO~) will be made if value of
1452 `version-control' is not the atom `never' and either there are already
1453 numeric versions of the file being backed up, or `version-control' is
1454 non-nil.
1455 We don't want excessive versions piling up, so there are variables
1456 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1457 and `kept-new-versions', which tells how many newest versions to keep.
1458 Defaults are 2 old versions and 2 new.
1459 `dired-kept-versions' controls dired's clean-directory (.) command.
1460 If `trim-versions-without-asking' is nil, system will query user
1461 before trimming versions. Otherwise it does it silently."
1462 (interactive "p")
1463 (let ((modp (buffer-modified-p))
1464 (large (> (buffer-size) 50000))
1465 (make-backup-files (and make-backup-files (not (eq args 0)))))
1466 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
1467 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
1468 (basic-save-buffer)
1469 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
1471 (defun delete-auto-save-file-if-necessary (&optional force)
1472 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1473 Normally delete only if the file was written by this Emacs since
1474 the last real save, but optional arg FORCE non-nil means delete anyway."
1475 (and buffer-auto-save-file-name delete-auto-save-files
1476 (not (string= buffer-file-name buffer-auto-save-file-name))
1477 (or force (recent-auto-save-p))
1478 (progn
1479 (condition-case ()
1480 (delete-file buffer-auto-save-file-name)
1481 (file-error nil))
1482 (set-buffer-auto-saved))))
1484 (defun basic-save-buffer ()
1485 "Save the current buffer in its visited file, if it has been modified."
1486 (interactive)
1487 (if (buffer-modified-p)
1488 (let ((recent-save (recent-auto-save-p))
1489 setmodes tempsetmodes)
1490 ;; On VMS, rename file and buffer to get rid of version number.
1491 (if (and (eq system-type 'vax-vms)
1492 (not (string= buffer-file-name
1493 (file-name-sans-versions buffer-file-name))))
1494 (let (buffer-new-name)
1495 ;; Strip VMS version number before save.
1496 (setq buffer-file-name
1497 (file-name-sans-versions buffer-file-name))
1498 ;; Construct a (unique) buffer name to correspond.
1499 (let ((buf (create-file-buffer (downcase buffer-file-name))))
1500 (setq buffer-new-name (buffer-name buf))
1501 (kill-buffer buf))
1502 (rename-buffer buffer-new-name)))
1503 ;; If buffer has no file name, ask user for one.
1504 (or buffer-file-name
1505 (set-visited-file-name
1506 (expand-file-name (read-file-name "File to save in: ") nil)))
1507 (or (verify-visited-file-modtime (current-buffer))
1508 (not (file-exists-p buffer-file-name))
1509 (yes-or-no-p
1510 (format "%s has changed since visited or saved. Save anyway? "
1511 (file-name-nondirectory buffer-file-name)))
1512 (error "Save not confirmed"))
1513 (save-restriction
1514 (widen)
1515 (and (> (point-max) 1)
1516 (/= (char-after (1- (point-max))) ?\n)
1517 (not (and (eq selective-display t)
1518 (= (char-after (1- (point-max))) ?\r)))
1519 (or (eq require-final-newline t)
1520 (and require-final-newline
1521 (y-or-n-p
1522 (format "Buffer %s does not end in newline. Add one? "
1523 (buffer-name)))))
1524 (save-excursion
1525 (goto-char (point-max))
1526 (insert ?\n)))
1527 (let ((hooks (append write-contents-hooks local-write-file-hooks
1528 write-file-hooks))
1529 (done nil))
1530 (while (and hooks
1531 (not (setq done (funcall (car hooks)))))
1532 (setq hooks (cdr hooks)))
1533 ;; If a hook returned t, file is already "written".
1534 (cond ((not done)
1535 (setq setmodes (basic-save-buffer-1)))))
1536 (setq buffer-file-number (nth 10 (file-attributes buffer-file-name)))
1537 (if setmodes
1538 (condition-case ()
1539 (set-file-modes buffer-file-name setmodes)
1540 (error nil))))
1541 ;; If the auto-save file was recent before this command,
1542 ;; delete it now.
1543 (delete-auto-save-file-if-necessary recent-save)
1544 (run-hooks 'after-save-hook))
1545 (message "(No changes need to be saved)")))
1547 ;; This does the "real job" of writing a buffer into its visited file
1548 ;; and making a backup file. This is what is normally done
1549 ;; but inhibited if one of write-file-hooks returns non-nil.
1550 ;; It returns a value to store in setmodes.
1551 (defun basic-save-buffer-1 ()
1552 (let (tempsetmodes setmodes)
1553 (if (not (file-writable-p buffer-file-name))
1554 (let ((dir (file-name-directory buffer-file-name)))
1555 (if (not (file-directory-p dir))
1556 (error "%s is not a directory" dir)
1557 (if (not (file-exists-p buffer-file-name))
1558 (error "Directory %s write-protected" dir)
1559 (if (yes-or-no-p
1560 (format "File %s is write-protected; try to save anyway? "
1561 (file-name-nondirectory
1562 buffer-file-name)))
1563 (setq tempsetmodes t)
1564 (error "Attempt to save to a file which you aren't allowed to write"))))))
1565 (or buffer-backed-up
1566 (setq setmodes (backup-buffer)))
1567 (if file-precious-flag
1568 ;; If file is precious, write temp name, then rename it.
1569 (let ((dir (file-name-directory buffer-file-name))
1570 (realname buffer-file-name)
1571 tempname temp nogood i succeed)
1572 (setq i 0)
1573 (setq nogood t)
1574 ;; Find the temporary name to write under.
1575 (while nogood
1576 (setq tempname (format "%s#tmp#%d" dir i))
1577 (setq nogood (file-exists-p tempname))
1578 (setq i (1+ i)))
1579 (unwind-protect
1580 (progn (clear-visited-file-modtime)
1581 (write-region (point-min) (point-max)
1582 tempname nil realname)
1583 (setq succeed t))
1584 ;; If writing the temp file fails,
1585 ;; delete the temp file.
1586 (or succeed (delete-file tempname)))
1587 ;; Since we have created an entirely new file
1588 ;; and renamed it, make sure it gets the
1589 ;; right permission bits set.
1590 (setq setmodes (file-modes buffer-file-name))
1591 ;; We succeeded in writing the temp file,
1592 ;; so rename it.
1593 (rename-file tempname buffer-file-name t))
1594 ;; If file not writable, see if we can make it writable
1595 ;; temporarily while we write it.
1596 ;; But no need to do so if we have just backed it up
1597 ;; (setmodes is set) because that says we're superseding.
1598 (cond ((and tempsetmodes (not setmodes))
1599 ;; Change the mode back, after writing.
1600 (setq setmodes (file-modes buffer-file-name))
1601 (set-file-modes buffer-file-name 511)))
1602 (write-region (point-min) (point-max)
1603 buffer-file-name nil t))
1604 setmodes))
1606 (defun save-some-buffers (&optional arg exiting)
1607 "Save some modified file-visiting buffers. Asks user about each one.
1608 Optional argument (the prefix) non-nil means save all with no questions.
1609 Optional second argument EXITING means ask about certain non-file buffers
1610 as well as about file buffers."
1611 (interactive "P")
1612 (save-window-excursion
1613 (let ((files-done
1614 (map-y-or-n-p
1615 (function
1616 (lambda (buffer)
1617 (and (buffer-modified-p buffer)
1619 (buffer-file-name buffer)
1620 (and exiting
1621 (progn
1622 (set-buffer buffer)
1623 (and buffer-offer-save (> (buffer-size) 0)))))
1624 (if arg
1626 (if (buffer-file-name buffer)
1627 (format "Save file %s? "
1628 (buffer-file-name buffer))
1629 (format "Save buffer %s? "
1630 (buffer-name buffer)))))))
1631 (function
1632 (lambda (buffer)
1633 (set-buffer buffer)
1634 (save-buffer)))
1635 (buffer-list)
1636 '("buffer" "buffers" "save")
1637 (list (list ?\C-r (lambda (buf)
1638 (view-buffer buf)
1639 (setq view-exit-action
1640 '(lambda (ignore)
1641 (exit-recursive-edit)))
1642 (recursive-edit)
1643 ;; Return nil to ask about BUF again.
1644 nil)
1645 "display the current buffer"))))
1646 (abbrevs-done
1647 (and save-abbrevs abbrevs-changed
1648 (progn
1649 (if (or arg
1650 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
1651 (write-abbrev-file nil))
1652 ;; Don't keep bothering user if he says no.
1653 (setq abbrevs-changed nil)
1654 t))))
1655 (or (> files-done 0) abbrevs-done
1656 (message "(No files need saving)")))))
1658 (defun not-modified (&optional arg)
1659 "Mark current buffer as unmodified, not needing to be saved.
1660 With prefix arg, mark buffer as modified, so \\[save-buffer] will save."
1661 (interactive "P")
1662 (message (if arg "Modification-flag set"
1663 "Modification-flag cleared"))
1664 (set-buffer-modified-p arg))
1666 (defun toggle-read-only (&optional arg)
1667 "Change whether this buffer is visiting its file read-only.
1668 With arg, set read-only iff arg is positive."
1669 (interactive "P")
1670 (setq buffer-read-only
1671 (if (null arg)
1672 (not buffer-read-only)
1673 (> (prefix-numeric-value arg) 0)))
1674 ;; Force mode-line redisplay
1675 (set-buffer-modified-p (buffer-modified-p)))
1677 (defun insert-file (filename)
1678 "Insert contents of file FILENAME into buffer after point.
1679 Set mark after the inserted text.
1681 This function is meant for the user to run interactively.
1682 Don't call it from programs! Use `insert-file-contents' instead.
1683 \(Its calling sequence is different; see its documentation)."
1684 (interactive "*fInsert file: ")
1685 (if (file-directory-p filename)
1686 (signal 'file-error (list "Opening input file" "file is a directory"
1687 filename)))
1688 (let ((tem (insert-file-contents filename)))
1689 (push-mark (+ (point) (car (cdr tem))))))
1691 (defun append-to-file (start end filename)
1692 "Append the contents of the region to the end of file FILENAME.
1693 When called from a function, expects three arguments,
1694 START, END and FILENAME. START and END are buffer positions
1695 saying what text to write."
1696 (interactive "r\nFAppend to file: ")
1697 (write-region start end filename t))
1699 (defun file-newest-backup (filename)
1700 "Return most recent backup file for FILENAME or nil if no backups exist."
1701 (let* ((filename (expand-file-name filename))
1702 (file (file-name-nondirectory filename))
1703 (dir (file-name-directory filename))
1704 (comp (file-name-all-completions file dir))
1705 newest)
1706 (while comp
1707 (setq file (concat dir (car comp))
1708 comp (cdr comp))
1709 (if (and (backup-file-name-p file)
1710 (or (null newest) (file-newer-than-file-p file newest)))
1711 (setq newest file)))
1712 newest))
1714 (defun rename-uniquely ()
1715 "Rename current buffer to a similar name not already taken.
1716 This function is useful for creating multiple shell process buffers
1717 or multiple mail buffers, etc."
1718 (interactive)
1719 (let* ((new-buf (generate-new-buffer (buffer-name)))
1720 (name (buffer-name new-buf)))
1721 (kill-buffer new-buf)
1722 (rename-buffer name)
1723 (set-buffer-modified-p (buffer-modified-p)))) ; force mode line update
1725 (defun make-directory (dir &optional parents)
1726 "Create the directory DIR and any nonexistent parent dirs.
1727 Interactively, the default choice of directory to create
1728 is the current default directory for file names.
1729 That is useful when you have visited a file in a nonexistint directory.
1731 Noninteractively, the second (optional) argument PARENTS says whether
1732 to create parent directories if they don't exist."
1733 (interactive
1734 (list (read-file-name "Make directory: " default-directory default-directory
1735 nil nil)
1737 (let ((handler (find-file-name-handler dir 'make-directory)))
1738 (if handler
1739 (funcall handler 'make-directory dir parents)
1740 (if (not parents)
1741 (make-directory-internal dir)
1742 (let ((dir (directory-file-name (expand-file-name dir)))
1743 create-list)
1744 (while (not (file-exists-p dir))
1745 (setq create-list (cons dir create-list)
1746 dir (directory-file-name (file-name-directory dir))))
1747 (while create-list
1748 (make-directory-internal (car create-list))
1749 (setq create-list (cdr create-list))))))))
1751 (put 'revert-buffer-function 'permanent-local t)
1752 (defvar revert-buffer-function nil
1753 "Function to use to revert this buffer, or nil to do the default.")
1755 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
1756 (defvar revert-buffer-insert-file-contents-function nil
1757 "Function to use to insert contents when reverting this buffer.
1758 Gets two args, first the nominal file name to use,
1759 and second, t if reading the auto-save file.")
1761 (defun revert-buffer (&optional ignore-auto noconfirm)
1762 "Replace the buffer text with the text of the visited file on disk.
1763 This undoes all changes since the file was visited or saved.
1764 With a prefix argument, offer to revert from latest auto-save file, if
1765 that is more recent than the visited file.
1767 When called from lisp, The first argument is IGNORE-AUTO; only offer
1768 to revert from the auto-save file when this is nil. Note that the
1769 sense of this argument is the reverse of the prefix argument, for the
1770 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
1771 to nil.
1773 Optional second argument NOCONFIRM means don't ask for confirmation at
1774 all.
1776 If the value of `revert-buffer-function' is non-nil, it is called to
1777 do the work.
1779 The default revert function runs the hook `before-revert-hook' at the
1780 beginning and `after-revert-hook' at the end."
1781 ;; I admit it's odd to reverse the sense of the prefix argument, but
1782 ;; there is a lot of code out there which assumes that the first
1783 ;; argument should be t to avoid consulting the auto-save file, and
1784 ;; there's no straightforward way to encourage authors to notice a
1785 ;; reversal of the argument sense. So I'm just changing the user
1786 ;; interface, but leaving the programmatic interface the same.
1787 (interactive (list (not prefix-arg)))
1788 (if revert-buffer-function
1789 (funcall revert-buffer-function ignore-auto noconfirm)
1790 (let* ((opoint (point))
1791 (auto-save-p (and (not ignore-auto)
1792 (recent-auto-save-p)
1793 buffer-auto-save-file-name
1794 (file-readable-p buffer-auto-save-file-name)
1795 (y-or-n-p
1796 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
1797 (file-name (if auto-save-p
1798 buffer-auto-save-file-name
1799 buffer-file-name)))
1800 (cond ((null file-name)
1801 (error "Buffer does not seem to be associated with any file"))
1802 ((or noconfirm
1803 (yes-or-no-p (format "Revert buffer from file %s? "
1804 file-name)))
1805 (run-hooks 'before-revert-hook)
1806 ;; If file was backed up but has changed since,
1807 ;; we shd make another backup.
1808 (and (not auto-save-p)
1809 (not (verify-visited-file-modtime (current-buffer)))
1810 (setq buffer-backed-up nil))
1811 ;; Get rid of all undo records for this buffer.
1812 (or (eq buffer-undo-list t)
1813 (setq buffer-undo-list nil))
1814 (let ((buffer-read-only nil)
1815 ;; Don't make undo records for the reversion.
1816 (buffer-undo-list t))
1817 (if revert-buffer-insert-file-contents-function
1818 (funcall revert-buffer-insert-file-contents-function
1819 file-name auto-save-p)
1820 (if (not (file-exists-p file-name))
1821 (error "File %s no longer exists!" file-name))
1822 ;; Bind buffer-file-name to nil
1823 ;; so that we don't try to lock the file.
1824 (let ((buffer-file-name nil))
1825 (or auto-save-p
1826 (unlock-buffer)))
1827 (insert-file-contents file-name (not auto-save-p)
1828 nil nil t)))
1829 (goto-char (min opoint (point-max)))
1830 (after-find-file nil nil t)
1831 (run-hooks 'after-revert-hook)
1832 t)))))
1834 (defun recover-file (file)
1835 "Visit file FILE, but get contents from its last auto-save file."
1836 (interactive
1837 (let ((prompt-file buffer-file-name)
1838 (file-name nil)
1839 (file-dir nil))
1840 (and prompt-file
1841 (setq file-name (file-name-nondirectory prompt-file)
1842 file-dir (file-name-directory prompt-file)))
1843 (list (read-file-name "Recover file: "
1844 file-dir nil nil file-name))))
1845 (setq file (expand-file-name file))
1846 (if (auto-save-file-name-p (file-name-nondirectory file))
1847 (error "%s is an auto-save file" file))
1848 (let ((file-name (let ((buffer-file-name file))
1849 (make-auto-save-file-name))))
1850 (cond ((not (file-newer-than-file-p file-name file))
1851 (error "Auto-save file %s not current" file-name))
1852 ((save-window-excursion
1853 (if (not (eq system-type 'vax-vms))
1854 (with-output-to-temp-buffer "*Directory*"
1855 (buffer-disable-undo standard-output)
1856 (call-process "ls" nil standard-output nil
1857 (if (file-symlink-p file) "-lL" "-l")
1858 file file-name)))
1859 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
1860 (switch-to-buffer (find-file-noselect file t))
1861 (let ((buffer-read-only nil))
1862 (erase-buffer)
1863 (insert-file-contents file-name nil))
1864 (after-find-file nil nil t))
1865 (t (error "Recover-file cancelled.")))))
1867 (defun kill-some-buffers ()
1868 "For each buffer, ask whether to kill it."
1869 (interactive)
1870 (let ((list (buffer-list)))
1871 (while list
1872 (let* ((buffer (car list))
1873 (name (buffer-name buffer)))
1874 (and (not (string-equal name ""))
1875 (/= (aref name 0) ? )
1876 (yes-or-no-p
1877 (format "Buffer %s %s. Kill? "
1878 name
1879 (if (buffer-modified-p buffer)
1880 "HAS BEEN EDITED" "is unmodified")))
1881 (kill-buffer buffer)))
1882 (setq list (cdr list)))))
1884 (defun auto-save-mode (arg)
1885 "Toggle auto-saving of contents of current buffer.
1886 With prefix argument ARG, turn auto-saving on if positive, else off."
1887 (interactive "P")
1888 (setq buffer-auto-save-file-name
1889 (and (if (null arg)
1890 (not buffer-auto-save-file-name)
1891 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
1892 (if (and buffer-file-name auto-save-visited-file-name
1893 (not buffer-read-only))
1894 buffer-file-name
1895 (make-auto-save-file-name))))
1896 ;; If -1 was stored here, to temporarily turn off saving,
1897 ;; turn it back on.
1898 (and (< buffer-saved-size 0)
1899 (setq buffer-saved-size 0))
1900 (if (interactive-p)
1901 (message "Auto-save %s (in this buffer)"
1902 (if buffer-auto-save-file-name "on" "off")))
1903 buffer-auto-save-file-name)
1905 (defun rename-auto-save-file ()
1906 "Adjust current buffer's auto save file name for current conditions.
1907 Also rename any existing auto save file, if it was made in this session."
1908 (let ((osave buffer-auto-save-file-name))
1909 (setq buffer-auto-save-file-name
1910 (make-auto-save-file-name))
1911 (if (and osave buffer-auto-save-file-name
1912 (not (string= buffer-auto-save-file-name buffer-file-name))
1913 (not (string= buffer-auto-save-file-name osave))
1914 (file-exists-p osave)
1915 (recent-auto-save-p))
1916 (rename-file osave buffer-auto-save-file-name t))))
1918 (defun make-auto-save-file-name ()
1919 "Return file name to use for auto-saves of current buffer.
1920 Does not consider `auto-save-visited-file-name' as that variable is checked
1921 before calling this function. You can redefine this for customization.
1922 See also `auto-save-file-name-p'."
1923 (if buffer-file-name
1924 (concat (file-name-directory buffer-file-name)
1926 (file-name-nondirectory buffer-file-name)
1927 "#")
1928 ;; For non-file bfr, use bfr name and Emacs pid.
1929 (expand-file-name (format "#%s#%s#" (buffer-name) (make-temp-name "")))))
1931 (defun auto-save-file-name-p (filename)
1932 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
1933 FILENAME should lack slashes. You can redefine this for customization."
1934 (string-match "^#.*#$" filename))
1936 (defconst list-directory-brief-switches
1937 (if (eq system-type 'vax-vms) "" "-CF")
1938 "*Switches for list-directory to pass to `ls' for brief listing,")
1940 (defconst list-directory-verbose-switches
1941 (if (eq system-type 'vax-vms)
1942 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
1943 "-l")
1944 "*Switches for list-directory to pass to `ls' for verbose listing,")
1946 (defun list-directory (dirname &optional verbose)
1947 "Display a list of files in or matching DIRNAME, a la `ls'.
1948 DIRNAME is globbed by the shell if necessary.
1949 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
1950 Actions controlled by variables `list-directory-brief-switches'
1951 and `list-directory-verbose-switches'."
1952 (interactive (let ((pfx current-prefix-arg))
1953 (list (read-file-name (if pfx "List directory (verbose): "
1954 "List directory (brief): ")
1955 nil default-directory nil)
1956 pfx)))
1957 (let ((switches (if verbose list-directory-verbose-switches
1958 list-directory-brief-switches)))
1959 (or dirname (setq dirname default-directory))
1960 (setq dirname (expand-file-name dirname))
1961 (with-output-to-temp-buffer "*Directory*"
1962 (buffer-disable-undo standard-output)
1963 (princ "Directory ")
1964 (princ dirname)
1965 (terpri)
1966 (save-excursion
1967 (set-buffer "*Directory*")
1968 (let ((wildcard (not (file-directory-p dirname))))
1969 (insert-directory dirname switches wildcard (not wildcard)))))))
1971 (defvar insert-directory-program "ls"
1972 "Absolute or relative name of the `ls' program used by `insert-directory'.")
1974 ;; insert-directory
1975 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
1976 ;; FULL-DIRECTORY-P is nil.
1977 ;; The single line of output must display FILE's name as it was
1978 ;; given, namely, an absolute path name.
1979 ;; - must insert exactly one line for each file if WILDCARD or
1980 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
1981 ;; before the file lines, plus optional text after the file lines.
1982 ;; Lines are delimited by "\n", so filenames containing "\n" are not
1983 ;; allowed.
1984 ;; File lines should display the basename.
1985 ;; - must be consistent with
1986 ;; - functions dired-move-to-filename, (these two define what a file line is)
1987 ;; dired-move-to-end-of-filename,
1988 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
1989 ;; dired-insert-headerline
1990 ;; dired-after-subdir-garbage (defines what a "total" line is)
1991 ;; - variable dired-subdir-regexp
1992 (defun insert-directory (file switches &optional wildcard full-directory-p)
1993 "Insert directory listing for FILE, formatted according to SWITCHES.
1994 Leaves point after the inserted text.
1995 Optional third arg WILDCARD means treat FILE as shell wildcard.
1996 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
1997 switches do not contain `d', so that a full listing is expected.
1999 This works by running a directory listing program
2000 whose name is in the variable `insert-directory-program'.
2001 If WILDCARD, it also runs the shell specified by `shell-file-name'."
2002 (let ((handler (find-file-name-handler file 'insert-directory)))
2003 (if handler
2004 (funcall handler 'insert-directory file switches
2005 wildcard full-directory-p)
2006 (if (eq system-type 'vax-vms)
2007 (vms-read-directory file switches (current-buffer))
2008 (if wildcard
2009 ;; Run ls in the directory of the file pattern we asked for.
2010 (let ((default-directory
2011 (if (file-name-absolute-p file)
2012 (file-name-directory file)
2013 (file-name-directory (expand-file-name file))))
2014 (pattern (file-name-nondirectory file))
2015 (beg 0))
2016 ;; Quote some characters that have special meanings in shells;
2017 ;; but don't quote the wildcards--we want them to be special.
2018 ;; We also currently don't quote the quoting characters
2019 ;; in case people want to use them explicitly to quote
2020 ;; wildcard characters.
2021 (while (string-match "[ \t\n;<>&|{}()#$]" pattern beg)
2022 (setq pattern
2023 (concat (substring pattern 0 (match-beginning 0))
2024 "\\"
2025 (substring pattern (match-beginning 0)))
2026 beg (1+ (match-end 0))))
2027 (call-process shell-file-name nil t nil
2028 "-c" (concat insert-directory-program
2029 " -d " switches " "
2030 pattern)))
2031 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2032 ;; directory if FILE is a symbolic link.
2033 (call-process insert-directory-program nil t nil switches
2034 (if full-directory-p
2035 (concat (file-name-as-directory file) ".")
2036 file)))))))
2038 (defvar kill-emacs-query-functions nil
2039 "Functions to call with no arguments to query about killing Emacs.")
2041 (defun save-buffers-kill-emacs (&optional arg)
2042 "Offer to save each buffer, then kill this Emacs process.
2043 With prefix arg, silently save all file-visiting buffers, then kill."
2044 (interactive "P")
2045 (save-some-buffers arg t)
2046 (and (or (not (memq t (mapcar (function
2047 (lambda (buf) (and (buffer-file-name buf)
2048 (buffer-modified-p buf))))
2049 (buffer-list))))
2050 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2051 (or (not (fboundp 'process-list))
2052 ;; process-list is not defined on VMS.
2053 (let ((processes (process-list))
2054 active)
2055 (while processes
2056 (and (memq (process-status (car processes)) '(run stop open))
2057 (let ((val (process-kill-without-query (car processes))))
2058 (process-kill-without-query (car processes) val)
2059 val)
2060 (setq active t))
2061 (setq processes (cdr processes)))
2062 (or (not active)
2063 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
2064 ;; Query the user for other things, perhaps.
2065 (let ((functions kill-emacs-query-functions)
2066 (yes t))
2067 (while (and functions yes)
2068 (setq yes (and yes (funcall (car functions))))
2069 (setq functions (cdr functions)))
2070 yes)
2071 (kill-emacs)))
2073 (define-key ctl-x-map "\C-f" 'find-file)
2074 (define-key ctl-x-map "\C-q" 'toggle-read-only)
2075 (define-key ctl-x-map "\C-r" 'find-file-read-only)
2076 (define-key ctl-x-map "\C-v" 'find-alternate-file)
2077 (define-key ctl-x-map "\C-s" 'save-buffer)
2078 (define-key ctl-x-map "s" 'save-some-buffers)
2079 (define-key ctl-x-map "\C-w" 'write-file)
2080 (define-key ctl-x-map "i" 'insert-file)
2081 (define-key esc-map "~" 'not-modified)
2082 (define-key ctl-x-map "\C-d" 'list-directory)
2083 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
2085 (define-key ctl-x-4-map "f" 'find-file-other-window)
2086 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
2087 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
2088 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
2089 (define-key ctl-x-4-map "\C-o" 'display-buffer)
2091 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
2092 (define-key ctl-x-5-map "f" 'find-file-other-frame)
2093 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
2094 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
2096 ;;; files.el ends here