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