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