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