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