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