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