(rmail-retry-failure): Bind inhibit-read-only.
[bpt/emacs.git] / lisp / files.el
1 ;;; files.el --- file input and output commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 87, 92, 93, 94, 1995 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-number nil
117 "The device number and file number of the file visited in the current buffer.
118 The value is a list of the form (FILENUM DEVNUM).
119 This pair of numbers uniquely identifies the file.
120 If the buffer is visiting a new file, the value is nil.")
121 (make-variable-buffer-local 'buffer-file-number)
122 (put 'buffer-file-number 'permanent-local t)
123
124 (defconst file-precious-flag nil
125 "*Non-nil means protect against I/O errors while saving files.
126 Some modes set this non-nil in particular buffers.
127
128 This feature works by writing the new contents into a temporary file
129 and then renaming the temporary file to replace the original.
130 In this way, any I/O error in writing leaves the original untouched,
131 and there is never any instant where the file is nonexistent.
132
133 Note that this feature forces backups to be made by copying.
134 Yet, at the same time, saving a precious file
135 breaks any hard links between it and other files.")
136
137 (defvar version-control nil
138 "*Control use of version numbers for backup files.
139 t means make numeric backup versions unconditionally.
140 nil means make them for files that have some already.
141 `never' means do not make them.")
142
143 (defvar dired-kept-versions 2
144 "*When cleaning directory, number of versions to keep.")
145
146 (defvar delete-old-versions nil
147 "*If t, delete excess backup versions silently.
148 If nil, ask confirmation. Any other value prevents any trimming.")
149
150 (defvar kept-old-versions 2
151 "*Number of oldest versions to keep when a new numbered backup is made.")
152
153 (defvar kept-new-versions 2
154 "*Number of newest versions to keep when a new numbered backup is made.
155 Includes the new backup. Must be > 0")
156
157 (defconst require-final-newline nil
158 "*Value of t says silently ensure a file ends in a newline when it is saved.
159 Non-nil but not t says ask user whether to add a newline when there isn't one.
160 nil means don't add newlines.")
161
162 (defconst auto-save-default t
163 "*Non-nil says by default do auto-saving of every file-visiting buffer.")
164
165 (defconst auto-save-visited-file-name nil
166 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
167 Normally auto-save files are written under other names.")
168
169 (defconst save-abbrevs nil
170 "*Non-nil means save word abbrevs too when files are saved.
171 Loading an abbrev file sets this to t.")
172
173 (defconst find-file-run-dired t
174 "*Non-nil says run dired if `find-file' is given the name of a directory.")
175
176 ;;;It is not useful to make this a local variable.
177 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
178 (defvar find-file-not-found-hooks nil
179 "List of functions to be called for `find-file' on nonexistent file.
180 These functions are called as soon as the error is detected.
181 `buffer-file-name' is already set up.
182 The functions are called in the order given until one of them returns non-nil.")
183
184 ;;;It is not useful to make this a local variable.
185 ;;;(put 'find-file-hooks 'permanent-local t)
186 (defvar find-file-hooks nil
187 "List of functions to be called after a buffer is loaded from a file.
188 The buffer's local variables (if any) will have been processed before the
189 functions are called.")
190
191 (defvar write-file-hooks nil
192 "List of functions to be called before writing out a buffer to a file.
193 If one of them returns non-nil, the file is considered already written
194 and the rest are not called.
195 These hooks are considered to pertain to the visited file.
196 So this list is cleared if you change the visited file name.
197 See also `write-contents-hooks'.
198 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.")
199 ;;; However, in case someone does make it local...
200 (put 'write-file-hooks 'permanent-local t)
201
202 (defvar local-write-file-hooks nil
203 "Just like `write-file-hooks', except intended for per-buffer use.
204 The functions in this list are called before the ones in
205 `write-file-hooks'.")
206 (make-variable-buffer-local 'local-write-file-hooks)
207 (put 'local-write-file-hooks 'permanent-local t)
208
209 (defvar write-contents-hooks nil
210 "List of functions to be called before writing out a buffer to a file.
211 If one of them returns non-nil, the file is considered already written
212 and the rest are not called.
213 These hooks are considered to pertain to the buffer's contents,
214 not to the particular visited file; thus, `set-visited-file-name' does
215 not clear this variable, but changing the major mode does clear it.
216 See also `write-file-hooks'.")
217
218 (defconst enable-local-variables t
219 "*Control use of local-variables lists in files you visit.
220 The value can be t, nil or something else.
221 A value of t means local-variables lists are obeyed;
222 nil means they are ignored; anything else means query.
223
224 The command \\[normal-mode] always obeys local-variables lists
225 and ignores this variable.")
226
227 (defconst enable-local-eval 'maybe
228 "*Control processing of the \"variable\" `eval' in a file's local variables.
229 The value can be t, nil or something else.
230 A value of t means obey `eval' variables;
231 nil means ignore them; anything else means query.
232
233 The command \\[normal-mode] always obeys local-variables lists
234 and ignores this variable.")
235
236 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
237 (or (fboundp 'lock-buffer)
238 (defalias 'lock-buffer 'ignore))
239 (or (fboundp 'unlock-buffer)
240 (defalias 'unlock-buffer 'ignore))
241
242 ;; This hook function provides support for ange-ftp host name
243 ;; completion. It runs the usual ange-ftp hook, but only for
244 ;; completion operations. Having this here avoids the need
245 ;; to load ange-ftp when it's not really in use.
246 (defun ange-ftp-completion-hook-function (op &rest args)
247 (if (memq op '(file-name-completion file-name-all-completions))
248 (apply 'ange-ftp-hook-function op args)
249 (let ((inhibit-file-name-handlers
250 (cons 'ange-ftp-completion-hook-function
251 (and (eq inhibit-file-name-operation op)
252 inhibit-file-name-handlers)))
253 (inhibit-file-name-operation op))
254 (apply op args))))
255
256 (defun convert-standard-filename (filename)
257 "Convert a standard file's name to something suitable for the current OS.
258 This function's standard definition is trivial; it just returns the argument.
259 However, on some systems, the function is redefined
260 with a definition that really does change some file names."
261 filename)
262 \f
263 (defun pwd ()
264 "Show the current default directory."
265 (interactive nil)
266 (message "Directory %s" default-directory))
267
268 (defvar cd-path nil
269 "Value of the CDPATH environment variable, as a list.
270 Not actually set up until the first time you you use it.")
271
272 (defvar path-separator ":"
273 "Character used to separate concatenated paths.")
274
275 (defun parse-colon-path (cd-path)
276 "Explode a colon-separated list of paths into a string list."
277 (and cd-path
278 (let (cd-prefix cd-list (cd-start 0) cd-colon)
279 (setq cd-path (concat cd-path path-separator))
280 (while (setq cd-colon (string-match path-separator cd-path cd-start))
281 (setq cd-list
282 (nconc cd-list
283 (list (if (= cd-start cd-colon)
284 nil
285 (substitute-in-file-name
286 (file-name-as-directory
287 (substring cd-path cd-start cd-colon)))))))
288 (setq cd-start (+ cd-colon 1)))
289 cd-list)))
290
291 (defun cd-absolute (dir)
292 "Change current directory to given absolute file name DIR."
293 ;; Put the name into directory syntax now,
294 ;; because otherwise expand-file-name may give some bad results.
295 (if (not (eq system-type 'vax-vms))
296 (setq dir (file-name-as-directory dir)))
297 (setq dir (abbreviate-file-name (expand-file-name dir)))
298 (if (not (file-directory-p dir))
299 (error "%s is not a directory" dir)
300 (if (file-executable-p dir)
301 (setq default-directory dir)
302 (error "Cannot cd to %s: Permission denied" dir))))
303
304 (defun cd (dir)
305 "Make DIR become the current buffer's default directory.
306 If your environment includes a `CDPATH' variable, try each one of that
307 colon-separated list of directories when resolving a relative directory name."
308 (interactive
309 (list (read-file-name "Change default directory: "
310 default-directory default-directory
311 (and (member cd-path '(nil ("./")))
312 (null (getenv "CDPATH"))))))
313 (if (file-name-absolute-p dir)
314 (cd-absolute (expand-file-name dir))
315 (if (null cd-path)
316 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
317 (setq cd-path (or trypath (list "./")))))
318 (if (not (catch 'found
319 (mapcar
320 (function (lambda (x)
321 (let ((f (expand-file-name (concat x dir))))
322 (if (file-directory-p f)
323 (progn
324 (cd-absolute f)
325 (throw 'found t))))))
326 cd-path)
327 nil))
328 (error "No such directory found via CDPATH environment variable"))))
329
330 (defun load-file (file)
331 "Load the Lisp file named FILE."
332 (interactive "fLoad file: ")
333 (load (expand-file-name file) nil nil t))
334
335 (defun load-library (library)
336 "Load the library named LIBRARY.
337 This is an interface to the function `load'."
338 (interactive "sLoad library: ")
339 (load library))
340
341 (defun file-local-copy (file &optional buffer)
342 "Copy the file FILE into a temporary file on this machine.
343 Returns the name of the local copy, or nil, if FILE is directly
344 accessible."
345 (let ((handler (find-file-name-handler file 'file-local-copy)))
346 (if handler
347 (funcall handler 'file-local-copy file)
348 nil)))
349
350 (defun file-truename (filename &optional counter prev-dirs)
351 "Return the truename of FILENAME, which should be absolute.
352 The truename of a file name is found by chasing symbolic links
353 both at the level of the file and at the level of the directories
354 containing it, until no links are left at any level.
355
356 The arguments COUNTER and PREV-DIRS are used only in recursive calls.
357 Do not specify them in other calls."
358 ;; COUNTER can be a cons cell whose car is the count of how many more links
359 ;; to chase before getting an error.
360 ;; PREV-DIRS can be a cons cell whose car is an alist
361 ;; of truenames we've just recently computed.
362
363 ;; The last test looks dubious, maybe `+' is meant here? --simon.
364 (if (or (string= filename "") (string= filename "~")
365 (and (string= (substring filename 0 1) "~")
366 (string-match "~[^/]*" filename)))
367 (progn
368 (setq filename (expand-file-name filename))
369 (if (string= filename "")
370 (setq filename "/"))))
371 (or counter (setq counter (list 100)))
372 (let (done
373 ;; For speed, remove the ange-ftp completion handler from the list.
374 ;; We know it's not needed here.
375 ;; For even more speed, do this only on the outermost call.
376 (file-name-handler-alist
377 (if prev-dirs file-name-handler-alist
378 (let ((tem (copy-sequence file-name-handler-alist)))
379 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
380 (or prev-dirs (setq prev-dirs (list nil)))
381 ;; If this file directly leads to a link, process that iteratively
382 ;; so that we don't use lots of stack.
383 (while (not done)
384 (setcar counter (1- (car counter)))
385 (if (< (car counter) 0)
386 (error "Apparent cycle of symbolic links for %s" filename))
387 (let ((handler (find-file-name-handler filename 'file-truename)))
388 ;; For file name that has a special handler, call handler.
389 ;; This is so that ange-ftp can save time by doing a no-op.
390 (if handler
391 (setq filename (funcall handler 'file-truename filename)
392 done t)
393 (let ((dir (or (file-name-directory filename) default-directory))
394 target dirfile)
395 ;; Get the truename of the directory.
396 (setq dirfile (directory-file-name dir))
397 ;; If these are equal, we have the (or a) root directory.
398 (or (string= dir dirfile)
399 ;; If this is the same dir we last got the truename for,
400 ;; save time--don't recalculate.
401 (if (assoc dir (car prev-dirs))
402 (setq dir (cdr (assoc dir (car prev-dirs))))
403 (let ((old dir)
404 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
405 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
406 (setq dir new))))
407 (if (equal ".." (file-name-nondirectory filename))
408 (setq filename
409 (directory-file-name (file-name-directory (directory-file-name dir)))
410 done t)
411 (if (equal "." (file-name-nondirectory filename))
412 (setq filename (directory-file-name dir)
413 done t)
414 ;; Put it back on the file name.
415 (setq filename (concat dir (file-name-nondirectory filename)))
416 ;; Is the file name the name of a link?
417 (setq target (file-symlink-p filename))
418 (if target
419 ;; Yes => chase that link, then start all over
420 ;; since the link may point to a directory name that uses links.
421 ;; We can't safely use expand-file-name here
422 ;; since target might look like foo/../bar where foo
423 ;; is itself a link. Instead, we handle . and .. above.
424 (setq filename
425 (if (file-name-absolute-p target)
426 target
427 (concat dir target))
428 done nil)
429 ;; No, we are done!
430 (setq done t))))))))
431 filename))
432
433 (defun file-chase-links (filename)
434 "Chase links in FILENAME until a name that is not a link.
435 Does not examine containing directories for links,
436 unlike `file-truename'."
437 (let (tem (count 100) (newname filename))
438 (while (setq tem (file-symlink-p newname))
439 (if (= count 0)
440 (error "Apparent cycle of symbolic links for %s" filename))
441 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
442 (while (string-match "//+" tem)
443 (setq tem (concat (substring tem 0 (1+ (match-beginning 0)))
444 (substring tem (match-end 0)))))
445 ;; Handle `..' by hand, since it needs to work in the
446 ;; target of any directory symlink.
447 ;; This code is not quite complete; it does not handle
448 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
449 (while (string-match "\\`\\.\\./" tem)
450 (setq tem (substring tem 3))
451 (setq newname (file-name-as-directory
452 ;; Do the .. by hand.
453 (directory-file-name
454 (file-name-directory
455 ;; Chase links in the default dir of the symlink.
456 (file-chase-links
457 (directory-file-name
458 (file-name-directory newname))))))))
459 (setq newname (expand-file-name tem (file-name-directory newname)))
460 (setq count (1- count)))
461 newname))
462 \f
463 (defun switch-to-buffer-other-window (buffer)
464 "Select buffer BUFFER in another window."
465 (interactive "BSwitch to buffer in other window: ")
466 (let ((pop-up-windows t))
467 (pop-to-buffer buffer t)))
468
469 (defun switch-to-buffer-other-frame (buffer)
470 "Switch to buffer BUFFER in another frame."
471 (interactive "BSwitch to buffer in other frame: ")
472 (let ((pop-up-frames t))
473 (pop-to-buffer buffer t)
474 (raise-frame (window-frame (selected-window)))))
475
476 (defun find-file (filename)
477 "Edit file FILENAME.
478 Switch to a buffer visiting file FILENAME,
479 creating one if none already exists."
480 (interactive "FFind file: ")
481 (switch-to-buffer (find-file-noselect filename)))
482
483 (defun find-file-other-window (filename)
484 "Edit file FILENAME, in another window.
485 May create a new window, or reuse an existing one.
486 See the function `display-buffer'."
487 (interactive "FFind file in other window: ")
488 (switch-to-buffer-other-window (find-file-noselect filename)))
489
490 (defun find-file-other-frame (filename)
491 "Edit file FILENAME, in another frame.
492 May create a new frame, or reuse an existing one.
493 See the function `display-buffer'."
494 (interactive "FFind file in other frame: ")
495 (switch-to-buffer-other-frame (find-file-noselect filename)))
496
497 (defun find-file-read-only (filename)
498 "Edit file FILENAME but don't allow changes.
499 Like \\[find-file] but marks buffer as read-only.
500 Use \\[toggle-read-only] to permit editing."
501 (interactive "fFind file read-only: ")
502 (find-file filename)
503 (setq buffer-read-only t)
504 (current-buffer))
505
506 (defun find-file-read-only-other-window (filename)
507 "Edit file FILENAME in another window but don't allow changes.
508 Like \\[find-file-other-window] but marks buffer as read-only.
509 Use \\[toggle-read-only] to permit editing."
510 (interactive "fFind file read-only other window: ")
511 (find-file-other-window filename)
512 (setq buffer-read-only t)
513 (current-buffer))
514
515 (defun find-file-read-only-other-frame (filename)
516 "Edit file FILENAME in another frame but don't allow changes.
517 Like \\[find-file-other-frame] but marks buffer as read-only.
518 Use \\[toggle-read-only] to permit editing."
519 (interactive "fFind file read-only other frame: ")
520 (find-file-other-frame filename)
521 (setq buffer-read-only t)
522 (current-buffer))
523
524 (defun find-alternate-file-other-window (filename)
525 "Find file FILENAME as a replacement for the file in the next window.
526 This command does not select that window."
527 (interactive
528 (save-selected-window
529 (other-window 1)
530 (let ((file buffer-file-name)
531 (file-name nil)
532 (file-dir nil))
533 (and file
534 (setq file-name (file-name-nondirectory file)
535 file-dir (file-name-directory file)))
536 (list (read-file-name
537 "Find alternate file: " file-dir nil nil file-name)))))
538 (if (one-window-p)
539 (find-file-other-window filename)
540 (save-selected-window
541 (other-window 1)
542 (find-alternate-file filename))))
543
544 (defun find-alternate-file (filename)
545 "Find file FILENAME, select its buffer, kill previous buffer.
546 If the current buffer now contains an empty file that you just visited
547 \(presumably by mistake), use this command to visit the file you really want."
548 (interactive
549 (let ((file buffer-file-name)
550 (file-name nil)
551 (file-dir nil))
552 (and file
553 (setq file-name (file-name-nondirectory file)
554 file-dir (file-name-directory file)))
555 (list (read-file-name
556 "Find alternate file: " file-dir nil nil file-name))))
557 (and (buffer-modified-p) (buffer-file-name)
558 ;; (not buffer-read-only)
559 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
560 (buffer-name))))
561 (error "Aborted"))
562 (let ((obuf (current-buffer))
563 (ofile buffer-file-name)
564 (onum buffer-file-number)
565 (otrue buffer-file-truename)
566 (oname (buffer-name)))
567 (if (get-buffer " **lose**")
568 (kill-buffer " **lose**"))
569 (rename-buffer " **lose**")
570 (setq buffer-file-name nil)
571 (setq buffer-file-number nil)
572 (setq buffer-file-truename nil)
573 (unwind-protect
574 (progn
575 (unlock-buffer)
576 (find-file filename))
577 (cond ((eq obuf (current-buffer))
578 (setq buffer-file-name ofile)
579 (setq buffer-file-number onum)
580 (setq buffer-file-truename otrue)
581 (lock-buffer)
582 (rename-buffer oname))))
583 (or (eq (current-buffer) obuf)
584 (kill-buffer obuf))))
585
586 (defun create-file-buffer (filename)
587 "Create a suitably named buffer for visiting FILENAME, and return it.
588 FILENAME (sans directory) is used unchanged if that name is free;
589 otherwise a string <2> or <3> or ... is appended to get an unused name."
590 (let ((lastname (file-name-nondirectory filename)))
591 (if (string= lastname "")
592 (setq lastname filename))
593 (generate-new-buffer lastname)))
594
595 (defun generate-new-buffer (name)
596 "Create and return a buffer with a name based on NAME.
597 Choose the buffer's name using `generate-new-buffer-name'."
598 (get-buffer-create (generate-new-buffer-name name)))
599
600 (defconst automount-dir-prefix "^/tmp_mnt/"
601 "Regexp to match the automounter prefix in a directory name.")
602
603 (defvar abbreviated-home-dir nil
604 "The user's homedir abbreviated according to `directory-abbrev-list'.")
605
606 (defun abbreviate-file-name (filename)
607 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
608 This also substitutes \"~\" for the user's home directory.
609 Type \\[describe-variable] directory-abbrev-alist RET for more information."
610 ;; Get rid of the prefixes added by the automounter.
611 (if (and (string-match automount-dir-prefix filename)
612 (file-exists-p (file-name-directory
613 (substring filename (1- (match-end 0))))))
614 (setq filename (substring filename (1- (match-end 0)))))
615 (let ((tail directory-abbrev-alist))
616 ;; If any elt of directory-abbrev-alist matches this name,
617 ;; abbreviate accordingly.
618 (while tail
619 (if (string-match (car (car tail)) filename)
620 (setq filename
621 (concat (cdr (car tail)) (substring filename (match-end 0)))))
622 (setq tail (cdr tail)))
623 ;; Compute and save the abbreviated homedir name.
624 ;; We defer computing this until the first time it's needed, to
625 ;; give time for directory-abbrev-alist to be set properly.
626 ;; We include a slash at the end, to avoid spurious matches
627 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
628 (or abbreviated-home-dir
629 (setq abbreviated-home-dir
630 (let ((abbreviated-home-dir "$foo"))
631 (concat "^" (abbreviate-file-name (expand-file-name "~"))
632 "\\(/\\|$\\)"))))
633
634 ;; If FILENAME starts with the abbreviated homedir,
635 ;; make it start with `~' instead.
636 (if (and (string-match abbreviated-home-dir filename)
637 ;; If the home dir is just /, don't change it.
638 (not (and (= (match-end 0) 1)
639 (= (aref filename 0) ?/)))
640 ;; MS-DOS root directories can come with a drive letter;
641 ;; Novell Netware allows drive letters beyond `Z:'.
642 (not (and (or (eq system-type 'ms-dos)
643 (eq system-type 'windows-nt))
644 (save-match-data
645 (string-match "^[a-zA-`]:/$" filename)))))
646 (setq filename
647 (concat "~"
648 (substring filename (match-beginning 1) (match-end 1))
649 (substring filename (match-end 0)))))
650 filename))
651
652 (defvar find-file-not-true-dirname-list nil
653 "*List of logical names for which visiting shouldn't save the true dirname.
654 On VMS, when you visit a file using a logical name that searches a path,
655 you may or may not want the visited file name to record the specific
656 directory where the file was found. If you *do not* want that, add the logical
657 name to this list as a string.")
658
659 (defun find-buffer-visiting (filename)
660 "Return the buffer visiting file FILENAME (a string).
661 This is like `get-file-buffer', except that it checks for any buffer
662 visiting the same file, possibly under a different name.
663 If there is no such live buffer, return nil."
664 (let ((buf (get-file-buffer filename))
665 (truename (abbreviate-file-name (file-truename filename))))
666 (or buf
667 (let ((list (buffer-list)) found)
668 (while (and (not found) list)
669 (save-excursion
670 (set-buffer (car list))
671 (if (and buffer-file-name
672 (string= buffer-file-truename truename))
673 (setq found (car list))))
674 (setq list (cdr list)))
675 found)
676 (let ((number (nthcdr 10 (file-attributes truename)))
677 (list (buffer-list)) found)
678 (and number
679 (while (and (not found) list)
680 (save-excursion
681 (set-buffer (car list))
682 (if (and buffer-file-name
683 (equal buffer-file-number number)
684 ;; Verify this buffer's file number
685 ;; still belongs to its file.
686 (file-exists-p buffer-file-name)
687 (equal (nthcdr 10 (file-attributes buffer-file-name))
688 number))
689 (setq found (car list))))
690 (setq list (cdr list))))
691 found))))
692
693 (defun insert-file-contents-literally (filename &optional visit beg end replace)
694 "Like `insert-file-contents', q.v., but only reads in the file.
695 A buffer may be modified in several ways after reading into the buffer due
696 to advanced Emacs features, such as file-name-handlers, format decoding,
697 find-file-hooks, etc.
698 This function ensures that none of these modifications will take place."
699 (let ((file-name-handler-alist nil)
700 (format-alist nil)
701 (after-insert-file-functions nil)
702 (find-buffer-file-type-function
703 (if (fboundp 'find-buffer-file-type)
704 (symbol-function 'find-buffer-file-type)
705 nil)))
706 (unwind-protect
707 (progn
708 (fset 'find-buffer-file-type (lambda (filename) t))
709 (insert-file-contents filename visit beg end replace))
710 (if find-buffer-file-type-function
711 (fset 'find-buffer-file-type find-buffer-file-type-function)
712 (fmakunbound 'find-buffer-file-type)))))
713
714 (defun find-file-noselect (filename &optional nowarn rawfile)
715 "Read file FILENAME into a buffer and return the buffer.
716 If a buffer exists visiting FILENAME, return that one, but
717 verify that the file has not changed since visited or saved.
718 The buffer is not selected, just returned to the caller."
719 (setq filename
720 (abbreviate-file-name
721 (expand-file-name filename)))
722 (if (file-directory-p filename)
723 (if find-file-run-dired
724 (dired-noselect (if find-file-visit-truename
725 (abbreviate-file-name (file-truename filename))
726 filename))
727 (error "%s is a directory." filename))
728 (let* ((buf (get-file-buffer filename))
729 (truename (abbreviate-file-name (file-truename filename)))
730 (number (nthcdr 10 (file-attributes truename)))
731 ;; Find any buffer for a file which has same truename.
732 (other (and (not buf) (find-buffer-visiting filename)))
733 error)
734 ;; Let user know if there is a buffer with the same truename.
735 (if other
736 (progn
737 (or nowarn
738 (string-equal filename (buffer-file-name other))
739 (message "%s and %s are the same file"
740 filename (buffer-file-name other)))
741 ;; Optionally also find that buffer.
742 (if (or find-file-existing-other-name find-file-visit-truename)
743 (setq buf other))))
744 (if buf
745 (or nowarn
746 (verify-visited-file-modtime buf)
747 (cond ((not (file-exists-p filename))
748 (error "File %s no longer exists!" filename))
749 ((yes-or-no-p
750 (if (string= (file-name-nondirectory filename)
751 (buffer-name buf))
752 (format
753 (if (buffer-modified-p buf)
754 "File %s changed on disk. Discard your edits? "
755 "File %s changed on disk. Reread from disk? ")
756 (file-name-nondirectory filename))
757 (format
758 (if (buffer-modified-p buf)
759 "File %s changed on disk. Discard your edits in %s? "
760 "File %s changed on disk. Reread from disk into %s? ")
761 (file-name-nondirectory filename)
762 (buffer-name buf))))
763 (save-excursion
764 (set-buffer buf)
765 (revert-buffer t t)))))
766 (save-excursion
767 ;;; The truename stuff makes this obsolete.
768 ;;; (let* ((link-name (car (file-attributes filename)))
769 ;;; (linked-buf (and (stringp link-name)
770 ;;; (get-file-buffer link-name))))
771 ;;; (if (bufferp linked-buf)
772 ;;; (message "Symbolic link to file in buffer %s"
773 ;;; (buffer-name linked-buf))))
774 (setq buf (create-file-buffer filename))
775 (set-buffer-major-mode buf)
776 (set-buffer buf)
777 (erase-buffer)
778 (if rawfile
779 (condition-case ()
780 (insert-file-contents-literally filename t)
781 (file-error
782 ;; Unconditionally set error
783 (setq error t)))
784 (condition-case ()
785 (insert-file-contents filename t)
786 (file-error
787 ;; Run find-file-not-found-hooks until one returns non-nil.
788 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
789 ;; If they fail too, set error.
790 (setq error t)))))
791 ;; Find the file's truename, and maybe use that as visited name.
792 (setq buffer-file-truename truename)
793 (setq buffer-file-number number)
794 ;; On VMS, we may want to remember which directory in a search list
795 ;; the file was found in.
796 (and (eq system-type 'vax-vms)
797 (let (logical)
798 (if (string-match ":" (file-name-directory filename))
799 (setq logical (substring (file-name-directory filename)
800 0 (match-beginning 0))))
801 (not (member logical find-file-not-true-dirname-list)))
802 (setq buffer-file-name buffer-file-truename))
803 (if find-file-visit-truename
804 (setq buffer-file-name
805 (setq filename
806 (expand-file-name buffer-file-truename))))
807 ;; Set buffer's default directory to that of the file.
808 (setq default-directory (file-name-directory filename))
809 ;; Turn off backup files for certain file names. Since
810 ;; this is a permanent local, the major mode won't eliminate it.
811 (and (not (funcall backup-enable-predicate buffer-file-name))
812 (progn
813 (make-local-variable 'backup-inhibited)
814 (setq backup-inhibited t)))
815 (if rawfile
816 nil
817 (after-find-file error (not nowarn)))))
818 buf)))
819 \f
820 (defvar after-find-file-from-revert-buffer nil)
821
822 (defun after-find-file (&optional error warn noauto
823 after-find-file-from-revert-buffer
824 nomodes)
825 "Called after finding a file and by the default revert function.
826 Sets buffer mode, parses local variables.
827 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
828 error in reading the file. WARN non-nil means warn if there
829 exists an auto-save file more recent than the visited file.
830 NOAUTO means don't mess with auto-save mode.
831 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
832 means this call was from `revert-buffer'.
833 Fifth arg NOMODES non-nil means don't alter the file's modes.
834 Finishes by calling the functions in `find-file-hooks'
835 unless NOMODES is non-nil."
836 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
837 (if noninteractive
838 nil
839 (let* (not-serious
840 (msg
841 (cond ((and error (file-attributes buffer-file-name))
842 (setq buffer-read-only t)
843 "File exists, but cannot be read.")
844 ((not buffer-read-only)
845 (if (and warn
846 (file-newer-than-file-p (make-auto-save-file-name)
847 buffer-file-name))
848 "Auto save file is newer; consider M-x recover-file"
849 (setq not-serious t)
850 (if error "(New file)" nil)))
851 ((not error)
852 (setq not-serious t)
853 "Note: file is write protected")
854 ((file-attributes (directory-file-name default-directory))
855 "File not found and directory write-protected")
856 ((file-exists-p (file-name-directory buffer-file-name))
857 (setq buffer-read-only nil))
858 (t
859 (setq buffer-read-only nil)
860 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
861 "Use M-x make-dir RET RET to create the directory"
862 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
863 (if msg
864 (progn
865 (message msg)
866 (or not-serious (sit-for 1 nil t)))))
867 (if (and auto-save-default (not noauto))
868 (auto-save-mode t)))
869 (if nomodes
870 nil
871 (normal-mode t)
872 (run-hooks 'find-file-hooks)))
873
874 (defun normal-mode (&optional find-file)
875 "Choose the major mode for this buffer automatically.
876 Also sets up any specified local variables of the file.
877 Uses the visited file name, the -*- line, and the local variables spec.
878
879 This function is called automatically from `find-file'. In that case,
880 we may set up specified local variables depending on the value of
881 `enable-local-variables': if it is t, we do; if it is nil, we don't;
882 otherwise, we query. `enable-local-variables' is ignored if you
883 run `normal-mode' explicitly."
884 (interactive)
885 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
886 (condition-case err
887 (set-auto-mode)
888 (error (message "File mode specification error: %s"
889 (prin1-to-string err))))
890 (condition-case err
891 (let ((enable-local-variables (or (not find-file)
892 enable-local-variables)))
893 (hack-local-variables))
894 (error (message "File local-variables error: %s"
895 (prin1-to-string err)))))
896
897 (defvar auto-mode-alist
898 '(("\\.te?xt\\'" . text-mode)
899 ("\\.c\\'" . c-mode)
900 ("\\.h\\'" . c-mode)
901 ("\\.tex\\'" . tex-mode)
902 ("\\.ltx\\'" . latex-mode)
903 ("\\.el\\'" . emacs-lisp-mode)
904 ("\\.mm\\'" . nroff-mode)
905 ("\\.me\\'" . nroff-mode)
906 ("\\.ms\\'" . nroff-mode)
907 ("\\.man\\'" . nroff-mode)
908 ("\\.scm\\'" . scheme-mode)
909 ("\\.l\\'" . lisp-mode)
910 ("\\.lisp\\'" . lisp-mode)
911 ("\\.f\\'" . fortran-mode)
912 ("\\.for\\'" . fortran-mode)
913 ("\\.p\\'" . pascal-mode)
914 ("\\.pas\\'" . pascal-mode)
915 ("\\.mss\\'" . scribe-mode)
916 ("\\.ad[abs]\\'" . ada-mode)
917 ("\\.icn\\'" . icon-mode)
918 ("\\.pl\\'" . perl-mode)
919 ("\\.cc\\'" . c++-mode)
920 ("\\.hh\\'" . c++-mode)
921 ("\\.C\\'" . c++-mode)
922 ("\\.H\\'" . c++-mode)
923 ("\\.cpp\\'" . c++-mode)
924 ("\\.cxx\\'" . c++-mode)
925 ("\\.hxx\\'" . c++-mode)
926 ("\\.c\\+\\+\\'" . c++-mode)
927 ("\\.h\\+\\+\\'" . c++-mode)
928 ("\\.mk\\'" . makefile-mode)
929 ("[Mm]akefile\\(.in\\)?\\'" . makefile-mode)
930 ;;; Less common extensions come here
931 ;;; so more common ones above are found faster.
932 ("\\.texinfo\\'" . texinfo-mode)
933 ("\\.te?xi\\'" . texinfo-mode)
934 ("\\.s\\'" . asm-mode)
935 ("\\.S\\'" . asm-mode)
936 ("\\.asm\\'" . asm-mode)
937 ("ChangeLog\\'" . change-log-mode)
938 ("change.log\\'" . change-log-mode)
939 ("changelo\\'" . change-log-mode)
940 ("ChangeLog.[0-9]+\\'" . change-log-mode)
941 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
942 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
943 ("\\.c?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
944 ("/\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
945 ("/\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
946 ("/\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
947 ;;; The following should come after the ChangeLog pattern
948 ;;; for the sake of ChangeLog.1, etc.
949 ;;; and after the .scm.[0-9] pattern too.
950 ("\\.[12345678]\\'" . nroff-mode)
951 ("\\.TeX\\'" . tex-mode)
952 ("\\.sty\\'" . latex-mode)
953 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
954 ("\\.bbl\\'" . latex-mode)
955 ("\\.bib\\'" . bibtex-mode)
956 ("\\.article\\'" . text-mode)
957 ("\\.letter\\'" . text-mode)
958 ("\\.tcl\\'" . tcl-mode)
959 ("\\.f90\\'" . f90-mode)
960 ("\\.lsp\\'" . lisp-mode)
961 ("\\.awk\\'" . awk-mode)
962 ("\\.prolog\\'" . prolog-mode)
963 ("\\.tar\\'" . tar-mode)
964 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\)\\'" . archive-mode)
965 ;; Mailer puts message to be edited in
966 ;; /tmp/Re.... or Message
967 ("^/tmp/Re" . text-mode)
968 ("/Message[0-9]*\\'" . text-mode)
969 ("/drafts/[0-9]+\\'" . mh-letter-mode)
970 ;; some news reader is reported to use this
971 ("^/tmp/fol/" . text-mode)
972 ("\\.y\\'" . c-mode)
973 ("\\.lex\\'" . c-mode)
974 ("\\.oak\\'" . scheme-mode)
975 ("\\.sgm\\'" . sgml-mode)
976 ("\\.sgml\\'" . sgml-mode)
977 ("\\.dtd\\'" . sgml-mode)
978 ;; .emacs following a directory delimiter
979 ;; in either Unix or VMS syntax.
980 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
981 ;; _emacs following a directory delimiter
982 ;; in MsDos syntax
983 ("[:/]_emacs\\'" . emacs-lisp-mode)
984 ("\\.ml\\'" . lisp-mode))
985 "\
986 Alist of filename patterns vs corresponding major mode functions.
987 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
988 \(NON-NIL stands for anything that is not nil; the value does not matter.)
989 Visiting a file whose name matches REGEXP specifies FUNCTION as the
990 mode function to use. FUNCTION will be called, unless it is nil.
991
992 If the element has the form (REGEXP FUNCTION NON-NIL), then after
993 calling FUNCTION (if it's not nil), we delete the suffix that matched
994 REGEXP and search the list again for another match.")
995
996 (defconst interpreter-mode-alist
997 '(("perl" . perl-mode)
998 ("wish" . tcl-mode)
999 ("wishx" . tcl-mode)
1000 ("tcl" . tcl-mode)
1001 ("tclsh" . tcl-mode)
1002 ("awk" . awk-mode)
1003 ("nawk" . awk-mode)
1004 ("gawk" . awk-mode)
1005 ("scm" . scheme-mode)
1006 ("ash" . sh-mode)
1007 ("bash" . sh-mode)
1008 ("csh" . sh-mode)
1009 ("dtksh" . sh-mode)
1010 ("es" . sh-mode)
1011 ("itcsh" . sh-mode)
1012 ("jsh" . sh-mode)
1013 ("ksh" . sh-mode)
1014 ("oash" . sh-mode)
1015 ("pdksh" . sh-mode)
1016 ("rc" . sh-mode)
1017 ("sh" . sh-mode)
1018 ("sh5" . sh-mode)
1019 ("tcsh" . sh-mode)
1020 ("wksh" . sh-mode)
1021 ("wsh" . sh-mode)
1022 ("zsh" . sh-mode)
1023 ("tail" . text-mode)
1024 ("more" . text-mode)
1025 ("less" . text-mode)
1026 ("pg" . text-mode))
1027 "Alist mapping interpreter names to major modes.
1028 This alist applies to files whose first line starts with `#!'.
1029 Each element looks like (INTERPRETER . MODE).
1030 The car of each element is compared with
1031 the name of the interpreter specified in the first line.
1032 If it matches, mode MODE is selected.")
1033
1034 (defconst inhibit-first-line-modes-regexps '("\\.tar\\'")
1035 "List of regexps; if one matches a file name, don't look for `-*-'.")
1036
1037 (defconst inhibit-first-line-modes-suffixes nil
1038 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1039 When checking `inhibit-first-line-modes-regexps', we first discard
1040 from the end of the file name anything that matches one of these regexps.")
1041
1042 (defvar user-init-file
1043 "" ; set by command-line
1044 "File name including directory of user's initialization file.")
1045
1046 (defun set-auto-mode ()
1047 "Select major mode appropriate for current buffer.
1048 This checks for a -*- mode tag in the buffer's text,
1049 compares the filename against the entries in `auto-mode-alist',
1050 or checks the interpreter that runs this file against
1051 `interpreter-mode-alist'.
1052
1053 It does not check for the `mode:' local variable in the
1054 Local Variables section of the file; for that, use `hack-local-variables'.
1055
1056 If `enable-local-variables' is nil, this function does not check for a
1057 -*- mode tag."
1058 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1059 (let (beg end done modes)
1060 (save-excursion
1061 (goto-char (point-min))
1062 (skip-chars-forward " \t\n")
1063 (and enable-local-variables
1064 ;; Don't look for -*- if this file name matches any
1065 ;; of the regexps in inhibit-first-line-modes-regexps.
1066 (let ((temp inhibit-first-line-modes-regexps)
1067 (name (if buffer-file-name
1068 (file-name-sans-versions buffer-file-name)
1069 (buffer-name))))
1070 (while (let ((sufs inhibit-first-line-modes-suffixes))
1071 (while (and sufs (not (string-match (car sufs) name)))
1072 (setq sufs (cdr sufs)))
1073 sufs)
1074 (setq name (substring name 0 (match-beginning 0))))
1075 (while (and temp
1076 (not (string-match (car temp) name)))
1077 (setq temp (cdr temp)))
1078 (not temp))
1079 (search-forward "-*-" (save-excursion
1080 ;; If the file begins with "#!"
1081 ;; (exec interpreter magic), look
1082 ;; for mode frobs in the first two
1083 ;; lines. You cannot necessarily
1084 ;; put them in the first line of
1085 ;; such a file without screwing up
1086 ;; the interpreter invocation.
1087 (end-of-line (and (looking-at "^#!") 2))
1088 (point)) t)
1089 (progn
1090 (skip-chars-forward " \t")
1091 (setq beg (point))
1092 (search-forward "-*-"
1093 (save-excursion (end-of-line) (point))
1094 t))
1095 (progn
1096 (forward-char -3)
1097 (skip-chars-backward " \t")
1098 (setq end (point))
1099 (goto-char beg)
1100 (if (save-excursion (search-forward ":" end t))
1101 ;; Find all specifications for the `mode:' variable
1102 ;; and execute them left to right.
1103 (while (let ((case-fold-search t))
1104 (or (and (looking-at "mode:")
1105 (goto-char (match-end 0)))
1106 (re-search-forward "[ \t;]mode:" end t)))
1107 (skip-chars-forward " \t")
1108 (setq beg (point))
1109 (if (search-forward ";" end t)
1110 (forward-char -1)
1111 (goto-char end))
1112 (skip-chars-backward " \t")
1113 (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1114 modes)))
1115 ;; Simple -*-MODE-*- case.
1116 (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
1117 "-mode"))
1118 modes))))))
1119 ;; If we found modes to use, invoke them now,
1120 ;; outside the save-excursion.
1121 (if modes
1122 (progn (mapcar 'funcall modes)
1123 (setq done t)))
1124 ;; If we didn't find a mode from a -*- line, try using the file name.
1125 (if (and (not done) buffer-file-name)
1126 (let ((name buffer-file-name)
1127 (keep-going t))
1128 ;; Remove backup-suffixes from file name.
1129 (setq name (file-name-sans-versions name))
1130 (while keep-going
1131 (setq keep-going nil)
1132 (let ((alist auto-mode-alist)
1133 (mode nil))
1134 ;; Find first matching alist entry.
1135 (let ((case-fold-search
1136 (memq system-type '(vax-vms windows-nt))))
1137 (while (and (not mode) alist)
1138 (if (string-match (car (car alist)) name)
1139 (if (and (consp (cdr (car alist)))
1140 (nth 2 (car alist)))
1141 (progn
1142 (setq mode (car (cdr (car alist)))
1143 name (substring name 0 (match-beginning 0))
1144 keep-going t))
1145 (setq mode (cdr (car alist))
1146 keep-going nil)))
1147 (setq alist (cdr alist))))
1148 (if mode
1149 (funcall mode)
1150 ;; If we can't deduce a mode from the file name,
1151 ;; look for an interpreter specified in the first line.
1152 ;; As a special case, allow for things like "#!/bin/env perl",
1153 ;; which finds the interpreter anywhere in $PATH.
1154 (let ((interpreter
1155 (save-excursion
1156 (goto-char (point-min))
1157 (if (looking-at "#! *\\([^ \t\n]*/bin/env +\\)?\\([^ \t\n]+\\)")
1158 (buffer-substring (match-beginning 2)
1159 (match-end 2))
1160 "")))
1161 elt)
1162 ;; Map interpreter name to a mode.
1163 (setq elt (assoc (file-name-nondirectory interpreter)
1164 interpreter-mode-alist))
1165 (if elt
1166 (funcall (cdr elt)))))))))))
1167
1168 (defun hack-local-variables-prop-line ()
1169 ;; Set local variables specified in the -*- line.
1170 ;; Ignore any specification for `mode:';
1171 ;; set-auto-mode should already have handled that.
1172 (save-excursion
1173 (goto-char (point-min))
1174 (let ((result nil)
1175 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
1176 ;; Parse the -*- line into the `result' alist.
1177 (cond ((not (search-forward "-*-" end t))
1178 ;; doesn't have one.
1179 nil)
1180 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1181 ;; Simple form: "-*- MODENAME -*-". Already handled.
1182 nil)
1183 (t
1184 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1185 ;; (last ";" is optional).
1186 (save-excursion
1187 (if (search-forward "-*-" end t)
1188 (setq end (- (point) 3))
1189 (error "-*- not terminated before end of line")))
1190 (while (< (point) end)
1191 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1192 (error "malformed -*- line"))
1193 (goto-char (match-end 0))
1194 ;; There used to be a downcase here,
1195 ;; but the manual didn't say so,
1196 ;; and people want to set var names that aren't all lc.
1197 (let ((key (intern (buffer-substring
1198 (match-beginning 1)
1199 (match-end 1))))
1200 (val (save-restriction
1201 (narrow-to-region (point) end)
1202 (read (current-buffer)))))
1203 (or (eq key 'mode)
1204 (setq result (cons (cons key val) result)))
1205 (skip-chars-forward " \t;")))
1206 (setq result (nreverse result))))
1207
1208 (if (and result
1209 (or (eq enable-local-variables t)
1210 (and enable-local-variables
1211 (save-window-excursion
1212 (condition-case nil
1213 (switch-to-buffer (current-buffer))
1214 (error
1215 ;; If we fail to switch in the selected window,
1216 ;; it is probably a minibuffer.
1217 ;; So try another window.
1218 (condition-case nil
1219 (switch-to-buffer-other-window (current-buffer))
1220 (error
1221 (switch-to-buffer-other-frame (current-buffer))))))
1222 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1223 (file-name-nondirectory buffer-file-name)))))))
1224 (while result
1225 (hack-one-local-variable (car (car result)) (cdr (car result)))
1226 (setq result (cdr result)))))))
1227
1228 (defvar hack-local-variables-hook nil
1229 "Normal hook run after processing a file's local variables specs.
1230 Major modes can use this to examine user-specified local variables
1231 in order to initialize other data structure based on them.")
1232
1233 (defun hack-local-variables ()
1234 "Parse and put into effect this buffer's local variables spec."
1235 (hack-local-variables-prop-line)
1236 ;; Look for "Local variables:" line in last page.
1237 (save-excursion
1238 (goto-char (point-max))
1239 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1240 (if (let ((case-fold-search t))
1241 (and (search-forward "Local Variables:" nil t)
1242 (or (eq enable-local-variables t)
1243 (and enable-local-variables
1244 (save-window-excursion
1245 (switch-to-buffer (current-buffer))
1246 (save-excursion
1247 (beginning-of-line)
1248 (set-window-start (selected-window) (point)))
1249 (y-or-n-p (format "Set local variables as specified at end of %s? "
1250 (if buffer-file-name
1251 (file-name-nondirectory
1252 buffer-file-name)
1253 (concat "buffer "
1254 (buffer-name))))))))))
1255 (let ((continue t)
1256 prefix prefixlen suffix beg
1257 (enable-local-eval enable-local-eval))
1258 ;; The prefix is what comes before "local variables:" in its line.
1259 ;; The suffix is what comes after "local variables:" in its line.
1260 (skip-chars-forward " \t")
1261 (or (eolp)
1262 (setq suffix (buffer-substring (point)
1263 (progn (end-of-line) (point)))))
1264 (goto-char (match-beginning 0))
1265 (or (bolp)
1266 (setq prefix
1267 (buffer-substring (point)
1268 (progn (beginning-of-line) (point)))))
1269
1270 (if prefix (setq prefixlen (length prefix)
1271 prefix (regexp-quote prefix)))
1272 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1273 (while continue
1274 ;; Look at next local variable spec.
1275 (if selective-display (re-search-forward "[\n\C-m]")
1276 (forward-line 1))
1277 ;; Skip the prefix, if any.
1278 (if prefix
1279 (if (looking-at prefix)
1280 (forward-char prefixlen)
1281 (error "Local variables entry is missing the prefix")))
1282 ;; Find the variable name; strip whitespace.
1283 (skip-chars-forward " \t")
1284 (setq beg (point))
1285 (skip-chars-forward "^:\n")
1286 (if (eolp) (error "Missing colon in local variables entry"))
1287 (skip-chars-backward " \t")
1288 (let* ((str (buffer-substring beg (point)))
1289 (var (read str))
1290 val)
1291 ;; Setting variable named "end" means end of list.
1292 (if (string-equal (downcase str) "end")
1293 (setq continue nil)
1294 ;; Otherwise read the variable value.
1295 (skip-chars-forward "^:")
1296 (forward-char 1)
1297 (setq val (read (current-buffer)))
1298 (skip-chars-backward "\n")
1299 (skip-chars-forward " \t")
1300 (or (if suffix (looking-at suffix) (eolp))
1301 (error "Local variables entry is terminated incorrectly"))
1302 ;; Set the variable. "Variables" mode and eval are funny.
1303 (hack-one-local-variable var val)))))))
1304 (run-hooks 'hack-local-variables-hook))
1305
1306 (defconst ignored-local-variables
1307 '(enable-local-eval)
1308 "Variables to be ignored in a file's local variable spec.")
1309
1310 ;; Get confirmation before setting these variables as locals in a file.
1311 (put 'debugger 'risky-local-variable t)
1312 (put 'enable-local-eval 'risky-local-variable t)
1313 (put 'ignored-local-variables 'risky-local-variable t)
1314 (put 'eval 'risky-local-variable t)
1315 (put 'file-name-handler-alist 'risky-local-variable t)
1316 (put 'minor-mode-map-alist 'risky-local-variable t)
1317 (put 'after-load-alist 'risky-local-variable t)
1318 (put 'buffer-file-name 'risky-local-variable t)
1319 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1320 (put 'buffer-file-truename 'risky-local-variable t)
1321 (put 'exec-path 'risky-local-variable t)
1322 (put 'load-path 'risky-local-variable t)
1323 (put 'exec-directory 'risky-local-variable t)
1324 (put 'process-environment 'risky-local-variable t)
1325 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1326 (put 'outline-level 'risky-local-variable t)
1327 (put 'rmail-output-file-alist 'risky-local-variable t)
1328
1329 ;; This one is safe because the user gets to check it before it is used.
1330 (put 'compile-command 'safe-local-variable t)
1331
1332 (defun hack-one-local-variable-quotep (exp)
1333 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1334
1335 ;; "Set" one variable in a local variables spec.
1336 ;; A few variable names are treated specially.
1337 (defun hack-one-local-variable (var val)
1338 (cond ((eq var 'mode)
1339 (funcall (intern (concat (downcase (symbol-name val))
1340 "-mode"))))
1341 ((memq var ignored-local-variables)
1342 nil)
1343 ;; "Setting" eval means either eval it or do nothing.
1344 ;; Likewise for setting hook variables.
1345 ((or (get var 'risky-local-variable)
1346 (and
1347 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
1348 (symbol-name var))
1349 (not (get var 'safe-local-variable))))
1350 ;; Permit evalling a put of a harmless property.
1351 ;; if the args do nothing tricky.
1352 (if (or (and (eq var 'eval)
1353 (consp val)
1354 (eq (car val) 'put)
1355 (hack-one-local-variable-quotep (nth 1 val))
1356 (hack-one-local-variable-quotep (nth 2 val))
1357 ;; Only allow safe values of lisp-indent-hook;
1358 ;; not functions.
1359 (or (numberp (nth 3 val))
1360 (equal (nth 3 val) ''defun))
1361 (memq (nth 1 (nth 2 val))
1362 '(lisp-indent-hook)))
1363 ;; Permit eval if not root and user says ok.
1364 (and (not (zerop (user-uid)))
1365 (or (eq enable-local-eval t)
1366 (and enable-local-eval
1367 (save-window-excursion
1368 (switch-to-buffer (current-buffer))
1369 (save-excursion
1370 (beginning-of-line)
1371 (set-window-start (selected-window) (point)))
1372 (setq enable-local-eval
1373 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1374 (file-name-nondirectory buffer-file-name)))))))))
1375 (if (eq var 'eval)
1376 (save-excursion (eval val))
1377 (make-local-variable var)
1378 (set var val))
1379 (message "Ignoring `eval:' in file's local variables")))
1380 ;; Ordinary variable, really set it.
1381 (t (make-local-variable var)
1382 (set var val))))
1383
1384 \f
1385 (defun set-visited-file-name (filename)
1386 "Change name of file visited in current buffer to FILENAME.
1387 The next time the buffer is saved it will go in the newly specified file.
1388 nil or empty string as argument means make buffer not be visiting any file.
1389 Remember to delete the initial contents of the minibuffer
1390 if you wish to pass an empty string as the argument."
1391 (interactive "FSet visited file name: ")
1392 (if (buffer-base-buffer)
1393 (error "An indirect buffer cannot visit a file"))
1394 (let (truename)
1395 (if filename
1396 (setq filename
1397 (if (string-equal filename "")
1398 nil
1399 (expand-file-name filename))))
1400 (if filename
1401 (progn
1402 (setq truename (file-truename filename))
1403 (if find-file-visit-truename
1404 (setq filename truename))))
1405 (or (equal filename buffer-file-name)
1406 (progn
1407 (and filename (lock-buffer filename))
1408 (unlock-buffer)))
1409 (setq buffer-file-name filename)
1410 (if filename ; make buffer name reflect filename.
1411 (let ((new-name (file-name-nondirectory buffer-file-name)))
1412 (if (string= new-name "")
1413 (error "Empty file name"))
1414 (if (eq system-type 'vax-vms)
1415 (setq new-name (downcase new-name)))
1416 (setq default-directory (file-name-directory buffer-file-name))
1417 (or (string= new-name (buffer-name))
1418 (rename-buffer new-name t))))
1419 (setq buffer-backed-up nil)
1420 (clear-visited-file-modtime)
1421 ;; Abbreviate the file names of the buffer.
1422 (if truename
1423 (progn
1424 (setq buffer-file-truename (abbreviate-file-name truename))
1425 (if find-file-visit-truename
1426 (setq buffer-file-name buffer-file-truename))))
1427 (setq buffer-file-number
1428 (if filename
1429 (nthcdr 10 (file-attributes buffer-file-name))
1430 nil)))
1431 ;; write-file-hooks is normally used for things like ftp-find-file
1432 ;; that visit things that are not local files as if they were files.
1433 ;; Changing to visit an ordinary local file instead should flush the hook.
1434 (kill-local-variable 'write-file-hooks)
1435 (kill-local-variable 'local-write-file-hooks)
1436 (kill-local-variable 'revert-buffer-function)
1437 (kill-local-variable 'backup-inhibited)
1438 ;; If buffer was read-only because of version control,
1439 ;; that reason is gone now, so make it writable.
1440 (if vc-mode
1441 (setq buffer-read-only nil))
1442 (kill-local-variable 'vc-mode)
1443 ;; Turn off backup files for certain file names.
1444 ;; Since this is a permanent local, the major mode won't eliminate it.
1445 (and (not (funcall backup-enable-predicate buffer-file-name))
1446 (progn
1447 (make-local-variable 'backup-inhibited)
1448 (setq backup-inhibited t)))
1449 (let ((oauto buffer-auto-save-file-name))
1450 ;; If auto-save was not already on, turn it on if appropriate.
1451 (if (not buffer-auto-save-file-name)
1452 (and buffer-file-name auto-save-default
1453 (auto-save-mode t))
1454 ;; If auto save is on, start using a new name.
1455 ;; We deliberately don't rename or delete the old auto save
1456 ;; for the old visited file name. This is because perhaps
1457 ;; the user wants to save the new state and then compare with the
1458 ;; previous state from the auto save file.
1459 (setq buffer-auto-save-file-name
1460 (make-auto-save-file-name)))
1461 ;; Rename the old auto save file if any.
1462 (and oauto buffer-auto-save-file-name
1463 (file-exists-p oauto)
1464 (rename-file oauto buffer-auto-save-file-name t)))
1465 (if buffer-file-name
1466 (set-buffer-modified-p t)))
1467
1468 (defun write-file (filename &optional confirm)
1469 "Write current buffer into file FILENAME.
1470 Makes buffer visit that file, and marks it not modified.
1471 If the buffer is already visiting a file, you can specify
1472 a directory name as FILENAME, to write a file of the same
1473 old name in that directory.
1474 If optional second arg CONFIRM is non-nil,
1475 ask for confirmation for overwriting an existing file."
1476 ;; (interactive "FWrite file: ")
1477 (interactive
1478 (list (if buffer-file-name
1479 (read-file-name "Write file: "
1480 nil nil nil nil)
1481 (read-file-name "Write file: "
1482 (cdr (assq 'default-directory
1483 (buffer-local-variables)))
1484 nil nil (buffer-name)))
1485 t))
1486 (or (null filename) (string-equal filename "")
1487 (progn
1488 ;; If arg is just a directory,
1489 ;; use same file name, but in that directory.
1490 (if (and (file-directory-p filename) buffer-file-name)
1491 (setq filename (concat (file-name-as-directory filename)
1492 (file-name-nondirectory buffer-file-name))))
1493 (and confirm
1494 (file-exists-p filename)
1495 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1496 (error "Canceled")))
1497 (set-visited-file-name filename)))
1498 (set-buffer-modified-p t)
1499 (save-buffer))
1500 \f
1501 (defun backup-buffer ()
1502 "Make a backup of the disk file visited by the current buffer, if appropriate.
1503 This is normally done before saving the buffer the first time.
1504 If the value is non-nil, it is the result of `file-modes' on the original
1505 file; this means that the caller, after saving the buffer, should change
1506 the modes of the new file to agree with the old modes."
1507 (if (and make-backup-files (not backup-inhibited)
1508 (not buffer-backed-up)
1509 (file-exists-p buffer-file-name)
1510 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1511 '(?- ?l)))
1512 (let ((real-file-name buffer-file-name)
1513 backup-info backupname targets setmodes)
1514 ;; If specified name is a symbolic link, chase it to the target.
1515 ;; Thus we make the backups in the directory where the real file is.
1516 (setq real-file-name (file-chase-links real-file-name))
1517 (setq backup-info (find-backup-file-name real-file-name)
1518 backupname (car backup-info)
1519 targets (cdr backup-info))
1520 ;;; (if (file-directory-p buffer-file-name)
1521 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1522 (if backup-info
1523 (condition-case ()
1524 (let ((delete-old-versions
1525 ;; If have old versions to maybe delete,
1526 ;; ask the user to confirm now, before doing anything.
1527 ;; But don't actually delete til later.
1528 (and targets
1529 (or (eq delete-old-versions t) (eq delete-old-versions nil))
1530 (or delete-old-versions
1531 (y-or-n-p (format "Delete excess backup versions of %s? "
1532 real-file-name))))))
1533 ;; Actually write the back up file.
1534 (condition-case ()
1535 (if (or file-precious-flag
1536 ; (file-symlink-p buffer-file-name)
1537 backup-by-copying
1538 (and backup-by-copying-when-linked
1539 (> (file-nlinks real-file-name) 1))
1540 (and backup-by-copying-when-mismatch
1541 (let ((attr (file-attributes real-file-name)))
1542 (or (nth 9 attr)
1543 (not (file-ownership-preserved-p real-file-name))))))
1544 (condition-case ()
1545 (copy-file real-file-name backupname t t)
1546 (file-error
1547 ;; If copying fails because file BACKUPNAME
1548 ;; is not writable, delete that file and try again.
1549 (if (and (file-exists-p backupname)
1550 (not (file-writable-p backupname)))
1551 (delete-file backupname))
1552 (copy-file real-file-name backupname t t)))
1553 ;; rename-file should delete old backup.
1554 (rename-file real-file-name backupname t)
1555 (setq setmodes (file-modes backupname)))
1556 (file-error
1557 ;; If trouble writing the backup, write it in ~.
1558 (setq backupname (expand-file-name
1559 (convert-standard-filename
1560 "~/%backup%~")))
1561 (message "Cannot write backup file; backing up in %s"
1562 (file-name-nondirectory backupname))
1563 (sleep-for 1)
1564 (condition-case ()
1565 (copy-file real-file-name backupname t t)
1566 (file-error
1567 ;; If copying fails because file BACKUPNAME
1568 ;; is not writable, delete that file and try again.
1569 (if (and (file-exists-p backupname)
1570 (not (file-writable-p backupname)))
1571 (delete-file backupname))
1572 (copy-file real-file-name backupname t t)))))
1573 (setq buffer-backed-up t)
1574 ;; Now delete the old versions, if desired.
1575 (if delete-old-versions
1576 (while targets
1577 (condition-case ()
1578 (delete-file (car targets))
1579 (file-error nil))
1580 (setq targets (cdr targets))))
1581 setmodes)
1582 (file-error nil))))))
1583
1584 (defun file-name-sans-versions (name &optional keep-backup-version)
1585 "Return FILENAME sans backup versions or strings.
1586 This is a separate procedure so your site-init or startup file can
1587 redefine it.
1588 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1589 we do not remove backup version numbers, only true file version numbers."
1590 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1591 (if handler
1592 (funcall handler 'file-name-sans-versions name keep-backup-version)
1593 (substring name 0
1594 (if (eq system-type 'vax-vms)
1595 ;; VMS version number is (a) semicolon, optional
1596 ;; sign, zero or more digits or (b) period, option
1597 ;; sign, zero or more digits, provided this is the
1598 ;; second period encountered outside of the
1599 ;; device/directory part of the file name.
1600 (or (string-match ";[-+]?[0-9]*\\'" name)
1601 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1602 name)
1603 (match-beginning 1))
1604 (length name))
1605 (if keep-backup-version
1606 (length name)
1607 (or (string-match "\\.~[0-9.]+~\\'" name)
1608 (string-match "~\\'" name)
1609 (length name))))))))
1610
1611 (defun file-ownership-preserved-p (file)
1612 "Returns t if deleting FILE and rewriting it would preserve the owner."
1613 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1614 (if handler
1615 (funcall handler 'file-ownership-preserved-p file)
1616 (let ((attributes (file-attributes file)))
1617 ;; Return t if the file doesn't exist, since it's true that no
1618 ;; information would be lost by an (attempted) delete and create.
1619 (or (null attributes)
1620 (= (nth 2 attributes) (user-uid)))))))
1621
1622 (defun file-name-sans-extension (filename)
1623 "Return FILENAME sans final \"extension\".
1624 The extension, in a file name, is the part that follows the last `.'."
1625 (save-match-data
1626 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1627 directory)
1628 (if (string-match "\\.[^.]*\\'" file)
1629 (if (setq directory (file-name-directory filename))
1630 (expand-file-name (substring file 0 (match-beginning 0))
1631 directory)
1632 (substring file 0 (match-beginning 0)))
1633 filename))))
1634
1635 (defun make-backup-file-name (file)
1636 "Create the non-numeric backup file name for FILE.
1637 This is a separate function so you can redefine it for customization."
1638 (if (eq system-type 'ms-dos)
1639 (let ((fn (file-name-nondirectory file)))
1640 (concat (file-name-directory file)
1641 (or
1642 (and (string-match "\\`[^.]+\\'" fn)
1643 (concat (match-string 0 fn) ".~"))
1644 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
1645 (concat (match-string 0 fn) "~")))))
1646 (concat file "~")))
1647
1648 (defun backup-file-name-p (file)
1649 "Return non-nil if FILE is a backup file name (numeric or not).
1650 This is a separate function so you can redefine it for customization.
1651 You may need to redefine `file-name-sans-versions' as well."
1652 (string-match "~\\'" file))
1653
1654 ;; This is used in various files.
1655 ;; The usage of bv-length is not very clean,
1656 ;; but I can't see a good alternative,
1657 ;; so as of now I am leaving it alone.
1658 (defun backup-extract-version (fn)
1659 "Given the name of a numeric backup file, return the backup number.
1660 Uses the free variable `bv-length', whose value should be
1661 the index in the name where the version number begins."
1662 (if (and (string-match "[0-9]+~$" fn bv-length)
1663 (= (match-beginning 0) bv-length))
1664 (string-to-int (substring fn bv-length -1))
1665 0))
1666
1667 ;; I believe there is no need to alter this behavior for VMS;
1668 ;; since backup files are not made on VMS, it should not get called.
1669 (defun find-backup-file-name (fn)
1670 "Find a file name for a backup file, and suggestions for deletions.
1671 Value is a list whose car is the name for the backup file
1672 and whose cdr is a list of old versions to consider deleting now.
1673 If the value is nil, don't make a backup."
1674 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
1675 ;; Run a handler for this function so that ange-ftp can refuse to do it.
1676 (if handler
1677 (funcall handler 'find-backup-file-name fn)
1678 (if (eq version-control 'never)
1679 (list (make-backup-file-name fn))
1680 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1681 (bv-length (length base-versions))
1682 possibilities
1683 (versions nil)
1684 (high-water-mark 0)
1685 (deserve-versions-p nil)
1686 (number-to-delete 0))
1687 (condition-case ()
1688 (setq possibilities (file-name-all-completions
1689 base-versions
1690 (file-name-directory fn))
1691 versions (sort (mapcar
1692 (function backup-extract-version)
1693 possibilities)
1694 '<)
1695 high-water-mark (apply 'max 0 versions)
1696 deserve-versions-p (or version-control
1697 (> high-water-mark 0))
1698 number-to-delete (- (length versions)
1699 kept-old-versions kept-new-versions -1))
1700 (file-error
1701 (setq possibilities nil)))
1702 (if (not deserve-versions-p)
1703 (list (make-backup-file-name fn))
1704 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
1705 (if (and (> number-to-delete 0)
1706 ;; Delete nothing if there is overflow
1707 ;; in the number of versions to keep.
1708 (>= (+ kept-new-versions kept-old-versions -1) 0))
1709 (mapcar (function (lambda (n)
1710 (concat fn ".~" (int-to-string n) "~")))
1711 (let ((v (nthcdr kept-old-versions versions)))
1712 (rplacd (nthcdr (1- number-to-delete) v) ())
1713 v))))))))))
1714
1715 (defun file-nlinks (filename)
1716 "Return number of names file FILENAME has."
1717 (car (cdr (file-attributes filename))))
1718
1719 (defun file-relative-name (filename &optional directory)
1720 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1721 (setq filename (expand-file-name filename)
1722 directory (file-name-as-directory (expand-file-name
1723 (or directory default-directory))))
1724 (let ((ancestor ""))
1725 (while (not (string-match (concat "^" (regexp-quote directory)) filename))
1726 (setq directory (file-name-directory (substring directory 0 -1))
1727 ancestor (concat "../" ancestor)))
1728 (concat ancestor (substring filename (match-end 0)))))
1729 \f
1730 (defun save-buffer (&optional args)
1731 "Save current buffer in visited file if modified. Versions described below.
1732 By default, makes the previous version into a backup file
1733 if previously requested or if this is the first save.
1734 With 1 \\[universal-argument], marks this version
1735 to become a backup when the next save is done.
1736 With 2 \\[universal-argument]'s,
1737 unconditionally makes the previous version into a backup file.
1738 With 3 \\[universal-argument]'s, marks this version
1739 to become a backup when the next save is done,
1740 and unconditionally makes the previous version into a backup file.
1741
1742 With argument of 0, never makes the previous version into a backup file.
1743
1744 If a file's name is FOO, the names of its numbered backup versions are
1745 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1746 Numeric backups (rather than FOO~) will be made if value of
1747 `version-control' is not the atom `never' and either there are already
1748 numeric versions of the file being backed up, or `version-control' is
1749 non-nil.
1750 We don't want excessive versions piling up, so there are variables
1751 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1752 and `kept-new-versions', which tells how many newest versions to keep.
1753 Defaults are 2 old versions and 2 new.
1754 `dired-kept-versions' controls dired's clean-directory (.) command.
1755 If `delete-old-versions' is nil, system will query user
1756 before trimming versions. Otherwise it does it silently."
1757 (interactive "p")
1758 (let ((modp (buffer-modified-p))
1759 (large (> (buffer-size) 50000))
1760 (make-backup-files (or (and make-backup-files (not (eq args 0)))
1761 (memq args '(16 64)))))
1762 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
1763 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
1764 (basic-save-buffer)
1765 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
1766
1767 (defun delete-auto-save-file-if-necessary (&optional force)
1768 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1769 Normally delete only if the file was written by this Emacs since
1770 the last real save, but optional arg FORCE non-nil means delete anyway."
1771 (and buffer-auto-save-file-name delete-auto-save-files
1772 (not (string= buffer-file-name buffer-auto-save-file-name))
1773 (or force (recent-auto-save-p))
1774 (progn
1775 (condition-case ()
1776 (delete-file buffer-auto-save-file-name)
1777 (file-error nil))
1778 (set-buffer-auto-saved))))
1779
1780 (defvar after-save-hook nil
1781 "Normal hook that is run after a buffer is saved to its file.")
1782
1783 (defun basic-save-buffer ()
1784 "Save the current buffer in its visited file, if it has been modified.
1785 After saving the buffer, run `after-save-hook'."
1786 (interactive)
1787 (save-excursion
1788 ;; In an indirect buffer, save its base buffer instead.
1789 (if (buffer-base-buffer)
1790 (set-buffer (buffer-base-buffer)))
1791 (if (buffer-modified-p)
1792 (let ((recent-save (recent-auto-save-p))
1793 setmodes tempsetmodes)
1794 ;; On VMS, rename file and buffer to get rid of version number.
1795 (if (and (eq system-type 'vax-vms)
1796 (not (string= buffer-file-name
1797 (file-name-sans-versions buffer-file-name))))
1798 (let (buffer-new-name)
1799 ;; Strip VMS version number before save.
1800 (setq buffer-file-name
1801 (file-name-sans-versions buffer-file-name))
1802 ;; Construct a (unique) buffer name to correspond.
1803 (let ((buf (create-file-buffer (downcase buffer-file-name))))
1804 (setq buffer-new-name (buffer-name buf))
1805 (kill-buffer buf))
1806 (rename-buffer buffer-new-name)))
1807 ;; If buffer has no file name, ask user for one.
1808 (or buffer-file-name
1809 (let ((filename
1810 (expand-file-name
1811 (read-file-name "File to save in: ") nil)))
1812 (and (file-exists-p filename)
1813 (or (y-or-n-p (format "File `%s' exists; overwrite? "
1814 filename))
1815 (error "Canceled")))
1816 (set-visited-file-name filename)))
1817 (or (verify-visited-file-modtime (current-buffer))
1818 (not (file-exists-p buffer-file-name))
1819 (yes-or-no-p
1820 (format "%s has changed since visited or saved. Save anyway? "
1821 (file-name-nondirectory buffer-file-name)))
1822 (error "Save not confirmed"))
1823 (save-restriction
1824 (widen)
1825 (and (> (point-max) 1)
1826 (/= (char-after (1- (point-max))) ?\n)
1827 (not (and (eq selective-display t)
1828 (= (char-after (1- (point-max))) ?\r)))
1829 (or (eq require-final-newline t)
1830 (and require-final-newline
1831 (y-or-n-p
1832 (format "Buffer %s does not end in newline. Add one? "
1833 (buffer-name)))))
1834 (save-excursion
1835 (goto-char (point-max))
1836 (insert ?\n)))
1837 (or (run-hook-with-args-until-success 'write-contents-hooks)
1838 (run-hook-with-args-until-success 'local-write-file-hooks)
1839 (run-hook-with-args-until-success 'write-file-hooks)
1840 ;; If a hook returned t, file is already "written".
1841 ;; Otherwise, write it the usual way now.
1842 (setq setmodes (basic-save-buffer-1)))
1843 (setq buffer-file-number
1844 (nthcdr 10 (file-attributes buffer-file-name)))
1845 (if setmodes
1846 (condition-case ()
1847 (set-file-modes buffer-file-name setmodes)
1848 (error nil))))
1849 ;; If the auto-save file was recent before this command,
1850 ;; delete it now.
1851 (delete-auto-save-file-if-necessary recent-save)
1852 ;; Support VC `implicit' locking.
1853 (vc-after-save)
1854 (run-hooks 'after-save-hook))
1855 (message "(No changes need to be saved)"))))
1856
1857 ;; This does the "real job" of writing a buffer into its visited file
1858 ;; and making a backup file. This is what is normally done
1859 ;; but inhibited if one of write-file-hooks returns non-nil.
1860 ;; It returns a value to store in setmodes.
1861 (defun basic-save-buffer-1 ()
1862 (let (tempsetmodes setmodes)
1863 (if (not (file-writable-p buffer-file-name))
1864 (let ((dir (file-name-directory buffer-file-name)))
1865 (if (not (file-directory-p dir))
1866 (error "%s is not a directory" dir)
1867 (if (not (file-exists-p buffer-file-name))
1868 (error "Directory %s write-protected" dir)
1869 (if (yes-or-no-p
1870 (format "File %s is write-protected; try to save anyway? "
1871 (file-name-nondirectory
1872 buffer-file-name)))
1873 (setq tempsetmodes t)
1874 (error "Attempt to save to a file which you aren't allowed to write"))))))
1875 (or buffer-backed-up
1876 (setq setmodes (backup-buffer)))
1877 (let ((dir (file-name-directory buffer-file-name)))
1878 (if (and file-precious-flag
1879 (file-writable-p dir))
1880 ;; If file is precious, write temp name, then rename it.
1881 ;; This requires write access to the containing dir,
1882 ;; which is why we don't try it if we don't have that access.
1883 (let ((realname buffer-file-name)
1884 tempname temp nogood i succeed
1885 (old-modtime (visited-file-modtime)))
1886 (setq i 0)
1887 (setq nogood t)
1888 ;; Find the temporary name to write under.
1889 (while nogood
1890 (setq tempname (format
1891 (if (eq system-type 'ms-dos)
1892 "%s#%d.tm#" ; MSDOS limits files to 8+3
1893 "%s#tmp#%d")
1894 dir i))
1895 (setq nogood (file-exists-p tempname))
1896 (setq i (1+ i)))
1897 (unwind-protect
1898 (progn (clear-visited-file-modtime)
1899 (write-region (point-min) (point-max)
1900 tempname nil realname
1901 buffer-file-truename)
1902 (setq succeed t))
1903 ;; If writing the temp file fails,
1904 ;; delete the temp file.
1905 (or succeed
1906 (progn
1907 (delete-file tempname)
1908 (set-visited-file-modtime old-modtime))))
1909 ;; Since we have created an entirely new file
1910 ;; and renamed it, make sure it gets the
1911 ;; right permission bits set.
1912 (setq setmodes (file-modes buffer-file-name))
1913 ;; We succeeded in writing the temp file,
1914 ;; so rename it.
1915 (rename-file tempname buffer-file-name t))
1916 ;; If file not writable, see if we can make it writable
1917 ;; temporarily while we write it.
1918 ;; But no need to do so if we have just backed it up
1919 ;; (setmodes is set) because that says we're superseding.
1920 (cond ((and tempsetmodes (not setmodes))
1921 ;; Change the mode back, after writing.
1922 (setq setmodes (file-modes buffer-file-name))
1923 (set-file-modes buffer-file-name 511)))
1924 (write-region (point-min) (point-max)
1925 buffer-file-name nil t buffer-file-truename)))
1926 setmodes))
1927
1928 (defun save-some-buffers (&optional arg exiting)
1929 "Save some modified file-visiting buffers. Asks user about each one.
1930 Optional argument (the prefix) non-nil means save all with no questions.
1931 Optional second argument EXITING means ask about certain non-file buffers
1932 as well as about file buffers."
1933 (interactive "P")
1934 (save-window-excursion
1935 (let* ((queried nil)
1936 (files-done
1937 (map-y-or-n-p
1938 (function
1939 (lambda (buffer)
1940 (and (buffer-modified-p buffer)
1941 (not (buffer-base-buffer buffer))
1942 (or
1943 (buffer-file-name buffer)
1944 (and exiting
1945 (progn
1946 (set-buffer buffer)
1947 (and buffer-offer-save (> (buffer-size) 0)))))
1948 (if arg
1949 t
1950 (setq queried t)
1951 (if (buffer-file-name buffer)
1952 (format "Save file %s? "
1953 (buffer-file-name buffer))
1954 (format "Save buffer %s? "
1955 (buffer-name buffer)))))))
1956 (function
1957 (lambda (buffer)
1958 (set-buffer buffer)
1959 (save-buffer)))
1960 (buffer-list)
1961 '("buffer" "buffers" "save")
1962 (list (list ?\C-r (lambda (buf)
1963 (view-buffer buf)
1964 (setq view-exit-action
1965 '(lambda (ignore)
1966 (exit-recursive-edit)))
1967 (recursive-edit)
1968 ;; Return nil to ask about BUF again.
1969 nil)
1970 "display the current buffer"))))
1971 (abbrevs-done
1972 (and save-abbrevs abbrevs-changed
1973 (progn
1974 (if (or arg
1975 (y-or-n-p (format "Save abbrevs in %s? "
1976 abbrev-file-name)))
1977 (write-abbrev-file nil))
1978 ;; Don't keep bothering user if he says no.
1979 (setq abbrevs-changed nil)
1980 t))))
1981 (or queried (> files-done 0) abbrevs-done
1982 (message "(No files need saving)")))))
1983 \f
1984 (defun not-modified (&optional arg)
1985 "Mark current buffer as unmodified, not needing to be saved.
1986 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
1987
1988 It is not a good idea to use this function in Lisp programs, because it
1989 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
1990 (interactive "P")
1991 (message (if arg "Modification-flag set"
1992 "Modification-flag cleared"))
1993 (set-buffer-modified-p arg))
1994
1995 (defun toggle-read-only (&optional arg)
1996 "Change whether this buffer is visiting its file read-only.
1997 With arg, set read-only iff arg is positive."
1998 (interactive "P")
1999 (setq buffer-read-only
2000 (if (null arg)
2001 (not buffer-read-only)
2002 (> (prefix-numeric-value arg) 0)))
2003 (force-mode-line-update))
2004
2005 (defun insert-file (filename)
2006 "Insert contents of file FILENAME into buffer after point.
2007 Set mark after the inserted text.
2008
2009 This function is meant for the user to run interactively.
2010 Don't call it from programs! Use `insert-file-contents' instead.
2011 \(Its calling sequence is different; see its documentation)."
2012 (interactive "*fInsert file: ")
2013 (if (file-directory-p filename)
2014 (signal 'file-error (list "Opening input file" "file is a directory"
2015 filename)))
2016 (let ((tem (insert-file-contents filename)))
2017 (push-mark (+ (point) (car (cdr tem))))))
2018
2019 (defun append-to-file (start end filename)
2020 "Append the contents of the region to the end of file FILENAME.
2021 When called from a function, expects three arguments,
2022 START, END and FILENAME. START and END are buffer positions
2023 saying what text to write."
2024 (interactive "r\nFAppend to file: ")
2025 (write-region start end filename t))
2026
2027 (defun file-newest-backup (filename)
2028 "Return most recent backup file for FILENAME or nil if no backups exist."
2029 (let* ((filename (expand-file-name filename))
2030 (file (file-name-nondirectory filename))
2031 (dir (file-name-directory filename))
2032 (comp (file-name-all-completions file dir))
2033 newest)
2034 (while comp
2035 (setq file (concat dir (car comp))
2036 comp (cdr comp))
2037 (if (and (backup-file-name-p file)
2038 (or (null newest) (file-newer-than-file-p file newest)))
2039 (setq newest file)))
2040 newest))
2041
2042 (defun rename-uniquely ()
2043 "Rename current buffer to a similar name not already taken.
2044 This function is useful for creating multiple shell process buffers
2045 or multiple mail buffers, etc."
2046 (interactive)
2047 (save-match-data
2048 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2049 (not (and buffer-file-name
2050 (string= (buffer-name)
2051 (file-name-nondirectory
2052 buffer-file-name)))))
2053 ;; If the existing buffer name has a <NNN>,
2054 ;; which isn't part of the file name (if any),
2055 ;; then get rid of that.
2056 (substring (buffer-name) 0 (match-beginning 0))
2057 (buffer-name)))
2058 (new-buf (generate-new-buffer base-name))
2059 (name (buffer-name new-buf)))
2060 (kill-buffer new-buf)
2061 (rename-buffer name)
2062 (force-mode-line-update))))
2063
2064 (defun make-directory (dir &optional parents)
2065 "Create the directory DIR and any nonexistent parent dirs.
2066 Interactively, the default choice of directory to create
2067 is the current default directory for file names.
2068 That is useful when you have visited a file in a nonexistent directory.
2069
2070 Noninteractively, the second (optional) argument PARENTS says whether
2071 to create parent directories if they don't exist."
2072 (interactive
2073 (list (read-file-name "Make directory: " default-directory default-directory
2074 nil nil)
2075 t))
2076 (let ((handler (find-file-name-handler dir 'make-directory)))
2077 (if handler
2078 (funcall handler 'make-directory dir parents)
2079 (if (not parents)
2080 (make-directory-internal dir)
2081 (let ((dir (directory-file-name (expand-file-name dir)))
2082 create-list)
2083 (while (not (file-exists-p dir))
2084 (setq create-list (cons dir create-list)
2085 dir (directory-file-name (file-name-directory dir))))
2086 (while create-list
2087 (make-directory-internal (car create-list))
2088 (setq create-list (cdr create-list))))))))
2089 \f
2090 (put 'revert-buffer-function 'permanent-local t)
2091 (defvar revert-buffer-function nil
2092 "Function to use to revert this buffer, or nil to do the default.
2093 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2094 which are the arguments that `revert-buffer' received.")
2095
2096 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2097 (defvar revert-buffer-insert-file-contents-function nil
2098 "Function to use to insert contents when reverting this buffer.
2099 Gets two args, first the nominal file name to use,
2100 and second, t if reading the auto-save file.")
2101
2102 (defvar before-revert-hook nil
2103 "Normal hook for `revert-buffer' to run before reverting.
2104 If `revert-buffer-function' is used to override the normal revert
2105 mechanism, this hook is not used.")
2106
2107 (defvar after-revert-hook nil
2108 "Normal hook for `revert-buffer' to run after reverting.
2109 Note that the hook value that it runs is the value that was in effect
2110 before reverting; that makes a difference if you have buffer-local
2111 hook functions.
2112
2113 If `revert-buffer-function' is used to override the normal revert
2114 mechanism, this hook is not used.")
2115
2116 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2117 "Replace the buffer text with the text of the visited file on disk.
2118 This undoes all changes since the file was visited or saved.
2119 With a prefix argument, offer to revert from latest auto-save file, if
2120 that is more recent than the visited file.
2121
2122 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2123 to revert from the auto-save file when this is nil. Note that the
2124 sense of this argument is the reverse of the prefix argument, for the
2125 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2126 to nil.
2127
2128 Optional second argument NOCONFIRM means don't ask for confirmation at
2129 all.
2130
2131 If the value of `revert-buffer-function' is non-nil, it is called to
2132 do the work.
2133
2134 The default revert function runs the hook `before-revert-hook' at the
2135 beginning and `after-revert-hook' at the end."
2136 ;; I admit it's odd to reverse the sense of the prefix argument, but
2137 ;; there is a lot of code out there which assumes that the first
2138 ;; argument should be t to avoid consulting the auto-save file, and
2139 ;; there's no straightforward way to encourage authors to notice a
2140 ;; reversal of the argument sense. So I'm just changing the user
2141 ;; interface, but leaving the programmatic interface the same.
2142 (interactive (list (not current-prefix-arg)))
2143 (if revert-buffer-function
2144 (funcall revert-buffer-function ignore-auto noconfirm)
2145 (let* ((opoint (point))
2146 (auto-save-p (and (not ignore-auto)
2147 (recent-auto-save-p)
2148 buffer-auto-save-file-name
2149 (file-readable-p buffer-auto-save-file-name)
2150 (y-or-n-p
2151 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2152 (file-name (if auto-save-p
2153 buffer-auto-save-file-name
2154 buffer-file-name)))
2155 (cond ((null file-name)
2156 (error "Buffer does not seem to be associated with any file"))
2157 ((or noconfirm
2158 (yes-or-no-p (format "Revert buffer from file %s? "
2159 file-name)))
2160 (run-hooks 'before-revert-hook)
2161 ;; If file was backed up but has changed since,
2162 ;; we shd make another backup.
2163 (and (not auto-save-p)
2164 (not (verify-visited-file-modtime (current-buffer)))
2165 (setq buffer-backed-up nil))
2166 ;; Get rid of all undo records for this buffer.
2167 (or (eq buffer-undo-list t)
2168 (setq buffer-undo-list nil))
2169 ;; Effectively copy the after-revert-hook status,
2170 ;; since after-find-file will clobber it.
2171 (let ((global-hook (default-value 'after-revert-hook))
2172 (local-hook-p (local-variable-p 'after-revert-hook))
2173 (local-hook (and (local-variable-p 'after-revert-hook)
2174 after-revert-hook)))
2175 (let (buffer-read-only
2176 ;; Don't make undo records for the reversion.
2177 (buffer-undo-list t))
2178 (if revert-buffer-insert-file-contents-function
2179 (funcall revert-buffer-insert-file-contents-function
2180 file-name auto-save-p)
2181 (if (not (file-exists-p file-name))
2182 (error "File %s no longer exists!" file-name))
2183 ;; Bind buffer-file-name to nil
2184 ;; so that we don't try to lock the file.
2185 (let ((buffer-file-name nil))
2186 (or auto-save-p
2187 (unlock-buffer)))
2188 (widen)
2189 (insert-file-contents file-name (not auto-save-p)
2190 nil nil t)))
2191 (goto-char (min opoint (point-max)))
2192 ;; Recompute the truename in case changes in symlinks
2193 ;; have changed the truename.
2194 (setq buffer-file-truename
2195 (abbreviate-file-name (file-truename buffer-file-name)))
2196 (after-find-file nil nil t t preserve-modes)
2197 ;; Run after-revert-hook as it was before we reverted.
2198 (setq-default revert-buffer-internal-hook global-hook)
2199 (if local-hook-p
2200 (progn
2201 (make-local-variable 'revert-buffer-internal-hook)
2202 (setq revert-buffer-internal-hook local-hook))
2203 (kill-local-variable 'revert-buffer-internal-hook))
2204 (run-hooks 'revert-buffer-internal-hook))
2205 t)))))
2206
2207 (defun recover-file (file)
2208 "Visit file FILE, but get contents from its last auto-save file."
2209 ;; Actually putting the file name in the minibuffer should be used
2210 ;; only rarely.
2211 ;; Not just because users often use the default.
2212 (interactive "FRecover file: ")
2213 (setq file (expand-file-name file))
2214 (if (auto-save-file-name-p (file-name-nondirectory file))
2215 (error "%s is an auto-save file" file))
2216 (let ((file-name (let ((buffer-file-name file))
2217 (make-auto-save-file-name))))
2218 (cond ((if (file-exists-p file)
2219 (not (file-newer-than-file-p file-name file))
2220 (not (file-exists-p file-name)))
2221 (error "Auto-save file %s not current" file-name))
2222 ((save-window-excursion
2223 (if (not (eq system-type 'vax-vms))
2224 (with-output-to-temp-buffer "*Directory*"
2225 (buffer-disable-undo standard-output)
2226 (call-process "ls" nil standard-output nil
2227 (if (file-symlink-p file) "-lL" "-l")
2228 file file-name)))
2229 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2230 (switch-to-buffer (find-file-noselect file t))
2231 (let ((buffer-read-only nil))
2232 (erase-buffer)
2233 (insert-file-contents file-name nil))
2234 (after-find-file nil nil t))
2235 (t (error "Recover-file cancelled.")))))
2236
2237 (defun recover-session ()
2238 "Recover auto save files from a previous Emacs session.
2239 This command first displays a Dired buffer showing you the
2240 previous sessions that you could recover from.
2241 To choose one, move point to the proper line and then type C-c C-c.
2242 Then you'll be asked about a number of files to recover."
2243 (interactive)
2244 (let ((ls-lisp-support-shell-wildcards t))
2245 (dired (concat auto-save-list-file-prefix "*")))
2246 (goto-char (point-min))
2247 (or (looking-at "Move to the session you want to recover,")
2248 (let ((inhibit-read-only t))
2249 (insert "Move to the session you want to recover,\n"
2250 "then type C-c C-c to select it.\n\n"
2251 "You can also delete some of these files;\n"
2252 "type d on a line to mark that file for deletion.\n\n")))
2253 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2254 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
2255
2256 (defun recover-session-finish ()
2257 "Choose one saved session to recover auto-save files from.
2258 This command is used in the special Dired buffer created by
2259 \\[recover-session]."
2260 (interactive)
2261 ;; Get the name of the session file to recover from.
2262 (let ((file (dired-get-filename))
2263 files
2264 (buffer (get-buffer-create " *recover*")))
2265 (dired-do-flagged-delete t)
2266 (unwind-protect
2267 (save-excursion
2268 ;; Read in the auto-save-list file.
2269 (set-buffer buffer)
2270 (erase-buffer)
2271 (insert-file-contents file)
2272 ;; Loop thru the text of that file
2273 ;; and get out the names of the files to recover.
2274 (while (not (eobp))
2275 (let (thisfile autofile)
2276 (if (eolp)
2277 ;; This is a pair of lines for a non-file-visiting buffer.
2278 ;; Get the auto-save file name and manufacture
2279 ;; a "visited file name" from that.
2280 (progn
2281 (forward-line 1)
2282 (setq autofile
2283 (buffer-substring-no-properties
2284 (point)
2285 (save-excursion
2286 (end-of-line)
2287 (point))))
2288 (setq thisfile
2289 (expand-file-name
2290 (substring
2291 (file-name-nondirectory autofile)
2292 1 -1)
2293 (file-name-directory autofile)))
2294 (forward-line 1))
2295 ;; This pair of lines is a file-visiting
2296 ;; buffer. Use the visited file name.
2297 (progn
2298 (setq thisfile
2299 (buffer-substring-no-properties
2300 (point) (progn (end-of-line) (point))))
2301 (forward-line 1)
2302 (setq autofile
2303 (buffer-substring-no-properties
2304 (point) (progn (end-of-line) (point))))
2305 (forward-line 1)))
2306 ;; Ignore a file if its auto-save file does not exist now.
2307 (if (file-exists-p autofile)
2308 (setq files (cons thisfile files)))))
2309 (setq files (nreverse files))
2310 ;; The file contains a pair of line for each auto-saved buffer.
2311 ;; The first line of the pair contains the visited file name
2312 ;; or is empty if the buffer was not visiting a file.
2313 ;; The second line is the auto-save file name.
2314 (if files
2315 (map-y-or-n-p "Recover %s? "
2316 (lambda (file)
2317 (condition-case nil
2318 (save-excursion (recover-file file))
2319 (error
2320 "Failed to recover `%s'" file)))
2321 files
2322 '("file" "files" "recover"))
2323 (message "No files can be recovered from this session now")))
2324 (kill-buffer buffer))))
2325
2326 (defun kill-some-buffers ()
2327 "For each buffer, ask whether to kill it."
2328 (interactive)
2329 (let ((list (buffer-list)))
2330 (while list
2331 (let* ((buffer (car list))
2332 (name (buffer-name buffer)))
2333 (and (not (string-equal name ""))
2334 (/= (aref name 0) ? )
2335 (yes-or-no-p
2336 (format "Buffer %s %s. Kill? "
2337 name
2338 (if (buffer-modified-p buffer)
2339 "HAS BEEN EDITED" "is unmodified")))
2340 (kill-buffer buffer)))
2341 (setq list (cdr list)))))
2342 \f
2343 (defun auto-save-mode (arg)
2344 "Toggle auto-saving of contents of current buffer.
2345 With prefix argument ARG, turn auto-saving on if positive, else off."
2346 (interactive "P")
2347 (setq buffer-auto-save-file-name
2348 (and (if (null arg)
2349 (or (not buffer-auto-save-file-name)
2350 ;; If autosave is off because buffer has shrunk,
2351 ;; then toggling should turn it on.
2352 (< buffer-saved-size 0))
2353 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2354 (if (and buffer-file-name auto-save-visited-file-name
2355 (not buffer-read-only))
2356 buffer-file-name
2357 (make-auto-save-file-name))))
2358 ;; If -1 was stored here, to temporarily turn off saving,
2359 ;; turn it back on.
2360 (and (< buffer-saved-size 0)
2361 (setq buffer-saved-size 0))
2362 (if (interactive-p)
2363 (message "Auto-save %s (in this buffer)"
2364 (if buffer-auto-save-file-name "on" "off")))
2365 buffer-auto-save-file-name)
2366
2367 (defun rename-auto-save-file ()
2368 "Adjust current buffer's auto save file name for current conditions.
2369 Also rename any existing auto save file, if it was made in this session."
2370 (let ((osave buffer-auto-save-file-name))
2371 (setq buffer-auto-save-file-name
2372 (make-auto-save-file-name))
2373 (if (and osave buffer-auto-save-file-name
2374 (not (string= buffer-auto-save-file-name buffer-file-name))
2375 (not (string= buffer-auto-save-file-name osave))
2376 (file-exists-p osave)
2377 (recent-auto-save-p))
2378 (rename-file osave buffer-auto-save-file-name t))))
2379
2380 (defun make-auto-save-file-name ()
2381 "Return file name to use for auto-saves of current buffer.
2382 Does not consider `auto-save-visited-file-name' as that variable is checked
2383 before calling this function. You can redefine this for customization.
2384 See also `auto-save-file-name-p'."
2385 (if buffer-file-name
2386 (if (eq system-type 'ms-dos)
2387 (let ((fn (file-name-nondirectory buffer-file-name)))
2388 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
2389 (concat (file-name-directory buffer-file-name)
2390 "#" (match-string 1 fn)
2391 "." (match-string 3 fn) "#"))
2392 (concat (file-name-directory buffer-file-name)
2393 "#"
2394 (file-name-nondirectory buffer-file-name)
2395 "#"))
2396
2397 ;; Deal with buffers that don't have any associated files. (Mail
2398 ;; mode tends to create a good number of these.)
2399
2400 (let ((buffer-name (buffer-name))
2401 (limit 0))
2402 ;; Use technique from Sebastian Kremer's auto-save
2403 ;; package to turn slashes into \\!. This ensures that
2404 ;; the auto-save buffer name is unique.
2405
2406 (while (string-match "[/\\]" buffer-name limit)
2407 (setq buffer-name (concat (substring buffer-name 0 (match-beginning 0))
2408 (if (string= (substring buffer-name
2409 (match-beginning 0)
2410 (match-end 0))
2411 "/")
2412 "\\!"
2413 "\\\\")
2414 (substring buffer-name (match-end 0))))
2415 (setq limit (1+ (match-end 0))))
2416
2417 (expand-file-name (format "#%s#%s#" buffer-name (make-temp-name ""))))))
2418
2419 (defun auto-save-file-name-p (filename)
2420 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2421 FILENAME should lack slashes. You can redefine this for customization."
2422 (string-match "^#.*#$" filename))
2423 \f
2424 (defun wildcard-to-regexp (wildcard)
2425 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2426 The generated regexp will match a filename iff the filename
2427 matches that wildcard according to shell rules. Only wildcards known
2428 by `sh' are supported."
2429 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
2430 ;; Copy the initial run of non-special characters.
2431 (result (substring wildcard 0 i))
2432 (len (length wildcard)))
2433 ;; If no special characters, we're almost done.
2434 (if i
2435 (while (< i len)
2436 (let ((ch (aref wildcard i))
2437 j)
2438 (setq
2439 result
2440 (concat result
2441 (cond
2442 ((eq ch ?\[) ; [...] maps to regexp char class
2443 (progn
2444 (setq i (1+ i))
2445 (concat
2446 (cond
2447 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
2448 (progn
2449 (setq i (1+ i))
2450 (if (eq (aref wildcard i) ?\])
2451 (progn
2452 (setq i (1+ i))
2453 "[^]")
2454 "[^")))
2455 ((eq (aref wildcard i) ?^)
2456 ;; Found "[^". Insert a `\0' character
2457 ;; (which cannot happen in a filename)
2458 ;; into the character class, so that `^'
2459 ;; is not the first character after `[',
2460 ;; and thus non-special in a regexp.
2461 (progn
2462 (setq i (1+ i))
2463 "[\000^"))
2464 ((eq (aref wildcard i) ?\])
2465 ;; I don't think `]' can appear in a
2466 ;; character class in a wildcard, but
2467 ;; let's be general here.
2468 (progn
2469 (setq i (1+ i))
2470 "[]"))
2471 (t "["))
2472 (prog1 ; copy everything upto next `]'.
2473 (substring wildcard
2474 i
2475 (setq j (string-match
2476 "]" wildcard i)))
2477 (setq i (if j (1- j) (1- len)))))))
2478 ((eq ch ?.) "\\.")
2479 ((eq ch ?*) "[^\000]*")
2480 ((eq ch ?+) "\\+")
2481 ((eq ch ?^) "\\^")
2482 ((eq ch ?$) "\\$")
2483 ((eq ch ?\\) "\\\\") ; probably cannot happen...
2484 ((eq ch ??) "[^\000]")
2485 (t (char-to-string ch)))))
2486 (setq i (1+ i)))))
2487 ;; Shell wildcards should match the entire filename,
2488 ;; not its part. Make the regexp say so.
2489 (concat "\\`" result "\\'")))
2490 \f
2491 (defconst list-directory-brief-switches
2492 (if (eq system-type 'vax-vms) "" "-CF")
2493 "*Switches for list-directory to pass to `ls' for brief listing,")
2494
2495 (defconst list-directory-verbose-switches
2496 (if (eq system-type 'vax-vms)
2497 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2498 "-l")
2499 "*Switches for list-directory to pass to `ls' for verbose listing,")
2500
2501 (defun list-directory (dirname &optional verbose)
2502 "Display a list of files in or matching DIRNAME, a la `ls'.
2503 DIRNAME is globbed by the shell if necessary.
2504 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2505 Actions controlled by variables `list-directory-brief-switches'
2506 and `list-directory-verbose-switches'."
2507 (interactive (let ((pfx current-prefix-arg))
2508 (list (read-file-name (if pfx "List directory (verbose): "
2509 "List directory (brief): ")
2510 nil default-directory nil)
2511 pfx)))
2512 (let ((switches (if verbose list-directory-verbose-switches
2513 list-directory-brief-switches)))
2514 (or dirname (setq dirname default-directory))
2515 (setq dirname (expand-file-name dirname))
2516 (with-output-to-temp-buffer "*Directory*"
2517 (buffer-disable-undo standard-output)
2518 (princ "Directory ")
2519 (princ dirname)
2520 (terpri)
2521 (save-excursion
2522 (set-buffer "*Directory*")
2523 (setq default-directory (file-name-directory dirname))
2524 (let ((wildcard (not (file-directory-p dirname))))
2525 (insert-directory dirname switches wildcard (not wildcard)))))))
2526
2527 (defvar insert-directory-program "ls"
2528 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2529
2530 ;; insert-directory
2531 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2532 ;; FULL-DIRECTORY-P is nil.
2533 ;; The single line of output must display FILE's name as it was
2534 ;; given, namely, an absolute path name.
2535 ;; - must insert exactly one line for each file if WILDCARD or
2536 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
2537 ;; before the file lines, plus optional text after the file lines.
2538 ;; Lines are delimited by "\n", so filenames containing "\n" are not
2539 ;; allowed.
2540 ;; File lines should display the basename.
2541 ;; - must be consistent with
2542 ;; - functions dired-move-to-filename, (these two define what a file line is)
2543 ;; dired-move-to-end-of-filename,
2544 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2545 ;; dired-insert-headerline
2546 ;; dired-after-subdir-garbage (defines what a "total" line is)
2547 ;; - variable dired-subdir-regexp
2548 (defun insert-directory (file switches &optional wildcard full-directory-p)
2549 "Insert directory listing for FILE, formatted according to SWITCHES.
2550 Leaves point after the inserted text.
2551 SWITCHES may be a string of options, or a list of strings.
2552 Optional third arg WILDCARD means treat FILE as shell wildcard.
2553 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2554 switches do not contain `d', so that a full listing is expected.
2555
2556 This works by running a directory listing program
2557 whose name is in the variable `insert-directory-program'.
2558 If WILDCARD, it also runs the shell specified by `shell-file-name'."
2559 ;; We need the directory in order to find the right handler.
2560 (let ((handler (find-file-name-handler (expand-file-name file)
2561 'insert-directory)))
2562 (if handler
2563 (funcall handler 'insert-directory file switches
2564 wildcard full-directory-p)
2565 (if (eq system-type 'vax-vms)
2566 (vms-read-directory file switches (current-buffer))
2567 (if wildcard
2568 ;; Run ls in the directory of the file pattern we asked for.
2569 (let ((default-directory
2570 (if (file-name-absolute-p file)
2571 (file-name-directory file)
2572 (file-name-directory (expand-file-name file))))
2573 (pattern (file-name-nondirectory file))
2574 (beg 0))
2575 ;; Quote some characters that have special meanings in shells;
2576 ;; but don't quote the wildcards--we want them to be special.
2577 ;; We also currently don't quote the quoting characters
2578 ;; in case people want to use them explicitly to quote
2579 ;; wildcard characters.
2580 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
2581 (setq pattern
2582 (concat (substring pattern 0 (match-beginning 0))
2583 "\\"
2584 (substring pattern (match-beginning 0)))
2585 beg (1+ (match-end 0))))
2586 (call-process shell-file-name nil t nil
2587 "-c" (concat "\\" ;; Disregard shell aliases!
2588 insert-directory-program
2589 " -d "
2590 (if (stringp switches)
2591 switches
2592 (mapconcat 'identity switches " "))
2593 " "
2594 pattern)))
2595 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2596 ;; directory if FILE is a symbolic link.
2597 (apply 'call-process
2598 insert-directory-program nil t nil
2599 (let (list)
2600 (if (listp switches)
2601 (setq list switches)
2602 (if (not (equal switches ""))
2603 (progn
2604 ;; Split the switches at any spaces
2605 ;; so we can pass separate options as separate args.
2606 (while (string-match " " switches)
2607 (setq list (cons (substring switches 0 (match-beginning 0))
2608 list)
2609 switches (substring switches (match-end 0))))
2610 (setq list (cons switches list)))))
2611 (append list
2612 (list
2613 (if full-directory-p
2614 (concat (file-name-as-directory file) ".")
2615 file))))))))))
2616
2617 (defvar kill-emacs-query-functions nil
2618 "Functions to call with no arguments to query about killing Emacs.
2619 If any of these functions returns nil, killing Emacs is cancelled.
2620 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
2621 but `kill-emacs', the low level primitive, does not.
2622 See also `kill-emacs-hook'.")
2623
2624 (defun save-buffers-kill-emacs (&optional arg)
2625 "Offer to save each buffer, then kill this Emacs process.
2626 With prefix arg, silently save all file-visiting buffers, then kill."
2627 (interactive "P")
2628 (save-some-buffers arg t)
2629 (and (or (not (memq t (mapcar (function
2630 (lambda (buf) (and (buffer-file-name buf)
2631 (buffer-modified-p buf))))
2632 (buffer-list))))
2633 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2634 (or (not (fboundp 'process-list))
2635 ;; process-list is not defined on VMS.
2636 (let ((processes (process-list))
2637 active)
2638 (while processes
2639 (and (memq (process-status (car processes)) '(run stop open))
2640 (let ((val (process-kill-without-query (car processes))))
2641 (process-kill-without-query (car processes) val)
2642 val)
2643 (setq active t))
2644 (setq processes (cdr processes)))
2645 (or (not active)
2646 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
2647 ;; Query the user for other things, perhaps.
2648 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
2649 (kill-emacs)))
2650 \f
2651 (define-key ctl-x-map "\C-f" 'find-file)
2652 (define-key ctl-x-map "\C-q" 'toggle-read-only)
2653 (define-key ctl-x-map "\C-r" 'find-file-read-only)
2654 (define-key ctl-x-map "\C-v" 'find-alternate-file)
2655 (define-key ctl-x-map "\C-s" 'save-buffer)
2656 (define-key ctl-x-map "s" 'save-some-buffers)
2657 (define-key ctl-x-map "\C-w" 'write-file)
2658 (define-key ctl-x-map "i" 'insert-file)
2659 (define-key esc-map "~" 'not-modified)
2660 (define-key ctl-x-map "\C-d" 'list-directory)
2661 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
2662
2663 (define-key ctl-x-4-map "f" 'find-file-other-window)
2664 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
2665 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
2666 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
2667 (define-key ctl-x-4-map "\C-o" 'display-buffer)
2668
2669 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
2670 (define-key ctl-x-5-map "f" 'find-file-other-frame)
2671 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
2672 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
2673
2674 ;;; files.el ends here