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