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