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