(make-mode): Provide make-mode, not makefile.
[bpt/emacs.git] / lisp / files.el
CommitLineData
c0274f38
ER
1;;; files.el --- file input and output commands for Emacs
2
9596811a
RS
3;; Copyright (C) 1985, 86, 87, 92, 93,
4;; 94, 95, 1996 Free Software Foundation, Inc.
b4da00e9 5
3a801d0c
ER
6;; Maintainer: FSF
7
b4da00e9
RM
8;; This file is part of GNU Emacs.
9
10;; GNU Emacs is free software; you can redistribute it and/or modify
11;; it under the terms of the GNU General Public License as published by
e5167999 12;; the Free Software Foundation; either version 2, or (at your option)
b4da00e9
RM
13;; any later version.
14
15;; GNU Emacs is distributed in the hope that it will be useful,
16;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18;; GNU General Public License for more details.
19
20;; You should have received a copy of the GNU General Public License
693f800d
RS
21;; along with GNU Emacs; see the file COPYING. If not, write to the
22;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23;; Boston, MA 02111-1307, USA.
b4da00e9 24
e41b2db1
ER
25;;; Commentary:
26
27;; Defines most of Emacs's file- and directory-handling functions,
28;; including basic file visiting, backup generation, link handling,
29;; ITS-id version control, load- and write-hook handling, and the like.
30
e5167999
ER
31;;; Code:
32
21540597
RS
33(defgroup backup nil
34 "Backups of edited data files."
2a9fe1e2 35 :group 'files)
b4da00e9 36
21540597 37(defgroup find-file nil
2a9fe1e2
RS
38 "Finding files."
39 :group 'files)
21540597
RS
40
41
42(defcustom delete-auto-save-files t
92631216
EZ
43 "*Non-nil means delete auto-save file when a buffer is saved or killed.
44
45Note that auto-save file will not be deleted if the buffer is killed
46when it has unsaved changes."
21540597
RS
47 :type 'boolean
48 :group 'auto-save)
49
50(defcustom directory-abbrev-alist
b4da00e9
RM
51 nil
52 "*Alist of abbreviations for file directories.
53A list of elements of the form (FROM . TO), each meaning to replace
54FROM with TO when it appears in a directory name. This replacement is
55done when setting up the default directory of a newly visited file.
56*Every* FROM string should start with `^'.
57
65151a1b
RS
58Do not use `~' in the TO strings.
59They should be ordinary absolute directory names.
60
b4da00e9
RM
61Use this feature when you have directories which you normally refer to
62via absolute symbolic links. Make TO the name of the link, and FROM
21540597
RS
63the name it is linked to."
64 :type '(repeat (cons :format "%v"
65 :value ("" . "")
66 (regexp :tag "From")
67 (regexp :tag "To")))
68 :group 'abbrev
69 :group 'find-file)
b4da00e9
RM
70
71;;; Turn off backup files on VMS since it has version numbers.
21540597 72(defcustom make-backup-files (not (eq system-type 'vax-vms))
4ea836c1 73 "*Non-nil means make a backup of a file the first time it is saved.
b4da00e9
RM
74This can be done by renaming the file or by copying.
75
76Renaming means that Emacs renames the existing file so that it is a
77backup file, then writes the buffer into a new file. Any other names
78that the old file had will now refer to the backup file. The new file
79is owned by you and its group is defaulted.
80
81Copying means that Emacs copies the existing file into the backup
82file, then writes the buffer on top of the existing file. Any other
83names that the old file had will now refer to the new (edited) file.
84The file's owner and group are unchanged.
85
86The choice of renaming or copying is controlled by the variables
87`backup-by-copying', `backup-by-copying-when-linked' and
21540597
RS
88`backup-by-copying-when-mismatch'. See also `backup-inhibited'."
89 :type 'boolean
90 :group 'backup)
b4da00e9
RM
91
92;; Do this so that local variables based on the file name
93;; are not overridden by the major mode.
94(defvar backup-inhibited nil
f862241d
RS
95 "Non-nil means don't make a backup, regardless of the other parameters.
96This variable is intended for use by making it local to a buffer.
97But it is local only if you make it local.")
b4da00e9
RM
98(put 'backup-inhibited 'permanent-local t)
99
21540597 100(defcustom backup-by-copying nil
b4da00e9 101 "*Non-nil means always use copying to create backup files.
21540597
RS
102See documentation of variable `make-backup-files'."
103 :type 'boolean
104 :group 'backup)
b4da00e9 105
21540597 106(defcustom backup-by-copying-when-linked nil
b4da00e9
RM
107 "*Non-nil means use copying to create backups for files with multiple names.
108This causes the alternate names to refer to the latest version as edited.
21540597
RS
109This variable is relevant only if `backup-by-copying' is nil."
110 :type 'boolean
111 :group 'backup)
b4da00e9 112
21540597 113(defcustom backup-by-copying-when-mismatch nil
b4da00e9
RM
114 "*Non-nil means create backups by copying if this preserves owner or group.
115Renaming may still be used (subject to control of other variables)
116when it would not result in changing the owner or group of the file;
117that is, for files which are owned by you and whose group matches
118the default for a new file created there by you.
21540597
RS
119This variable is relevant only if `backup-by-copying' is nil."
120 :type 'boolean
121 :group 'backup)
b4da00e9
RM
122
123(defvar backup-enable-predicate
124 '(lambda (name)
125 (or (< (length name) 5)
126 (not (string-equal "/tmp/" (substring name 0 5)))))
127 "Predicate that looks at a file name and decides whether to make backups.
128Called with an absolute file name as argument, it returns t to enable backup.")
129
21540597 130(defcustom buffer-offer-save nil
b4da00e9
RM
131 "*Non-nil in a buffer means offer to save the buffer on exit
132even if the buffer is not visiting a file.
21540597
RS
133Automatically local in all buffers."
134 :type 'boolean
135 :group 'backup)
b4da00e9
RM
136(make-variable-buffer-local 'buffer-offer-save)
137
21540597 138(defcustom find-file-existing-other-name t
f3e23606
RS
139 "*Non-nil means find a file under alternative names, in existing buffers.
140This means if any existing buffer is visiting the file you want
21540597
RS
141under another name, you get the existing buffer instead of a new buffer."
142 :type 'boolean
143 :group 'find-file)
f3e23606 144
21540597 145(defcustom find-file-visit-truename nil
f3e23606
RS
146 "*Non-nil means visit a file under its truename.
147The truename of a file is found by chasing all links
21540597
RS
148both at the file level and at the levels of the containing directories."
149 :type 'boolean
150 :group 'find-file)
f3e23606 151
db8c4866 152(defcustom revert-without-query
d7fa5aa2 153 nil
ebeb898f
RS
154 "*Specify which files should be reverted without query.
155The value is a list of regular expressions.
156If the file name matches one of these regular expressions,
db8c4866 157then `revert-buffer' reverts the file without querying
21540597 158if the file has changed on disk and you have not edited the buffer."
a0d809f2 159 :type '(repeat regexp)
21540597 160 :group 'find-file)
ebeb898f 161
f3e23606
RS
162(defvar buffer-file-number nil
163 "The device number and file number of the file visited in the current buffer.
164The value is a list of the form (FILENUM DEVNUM).
165This pair of numbers uniquely identifies the file.
166If the buffer is visiting a new file, the value is nil.")
167(make-variable-buffer-local 'buffer-file-number)
168(put 'buffer-file-number 'permanent-local t)
169
de88363f
RS
170(defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
171 "Non-nil means that buffer-file-number uniquely identifies files.")
172
21540597 173(defcustom file-precious-flag nil
b4da00e9 174 "*Non-nil means protect against I/O errors while saving files.
560f4415 175Some modes set this non-nil in particular buffers.
4b7271c1
KH
176
177This feature works by writing the new contents into a temporary file
178and then renaming the temporary file to replace the original.
179In this way, any I/O error in writing leaves the original untouched,
180and there is never any instant where the file is nonexistent.
181
182Note that this feature forces backups to be made by copying.
560f4415 183Yet, at the same time, saving a precious file
21540597
RS
184breaks any hard links between it and other files."
185 :type 'boolean
186 :group 'backup)
b4da00e9 187
21540597 188(defcustom version-control nil
b4da00e9
RM
189 "*Control use of version numbers for backup files.
190t means make numeric backup versions unconditionally.
191nil means make them for files that have some already.
21540597
RS
192`never' means do not make them."
193 :type 'boolean
194 :group 'backup
195 :group 'vc)
196
197(defcustom dired-kept-versions 2
198 "*When cleaning directory, number of versions to keep."
199 :type 'integer
200 :group 'backup
201 :group 'dired)
202
203(defcustom delete-old-versions nil
de7d5e1b 204 "*If t, delete excess backup versions silently.
21540597
RS
205If nil, ask confirmation. Any other value prevents any trimming."
206 :type '(choice (const :tag "Delete" t)
207 (const :tag "Ask" nil)
208 (sexp :tag "Leave" :format "%t\n" other))
209 :group 'backup)
210
211(defcustom kept-old-versions 2
212 "*Number of oldest versions to keep when a new numbered backup is made."
213 :type 'integer
214 :group 'backup)
215
216(defcustom kept-new-versions 2
b4da00e9 217 "*Number of newest versions to keep when a new numbered backup is made.
21540597
RS
218Includes the new backup. Must be > 0"
219 :type 'integer
220 :group 'backup)
b4da00e9 221
21540597 222(defcustom require-final-newline nil
b4da00e9
RM
223 "*Value of t says silently ensure a file ends in a newline when it is saved.
224Non-nil but not t says ask user whether to add a newline when there isn't one.
21540597 225nil means don't add newlines."
ad375092
RS
226 :type '(choice (const :tag "Off" nil)
227 (const :tag "Add" t)
228 (sexp :tag "Ask" :format "%t\n" ask))
21540597 229 :group 'editing-basics)
b4da00e9 230
21540597
RS
231(defcustom auto-save-default t
232 "*Non-nil says by default do auto-saving of every file-visiting buffer."
233 :type 'boolean
234 :group 'auto-save)
b4da00e9 235
21540597 236(defcustom auto-save-visited-file-name nil
b4da00e9 237 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
21540597
RS
238Normally auto-save files are written under other names."
239 :type 'boolean
240 :group 'auto-save)
b4da00e9 241
21540597 242(defcustom save-abbrevs nil
b4da00e9 243 "*Non-nil means save word abbrevs too when files are saved.
21540597
RS
244Loading an abbrev file sets this to t."
245 :type 'boolean
246 :group 'abbrev)
b4da00e9 247
21540597
RS
248(defcustom find-file-run-dired t
249 "*Non-nil says run dired if `find-file' is given the name of a directory."
250 :type 'boolean
251 :group 'find-file)
b4da00e9 252
92966e6f
RS
253;;;It is not useful to make this a local variable.
254;;;(put 'find-file-not-found-hooks 'permanent-local t)
b4da00e9
RM
255(defvar find-file-not-found-hooks nil
256 "List of functions to be called for `find-file' on nonexistent file.
257These functions are called as soon as the error is detected.
258`buffer-file-name' is already set up.
259The functions are called in the order given until one of them returns non-nil.")
260
92966e6f
RS
261;;;It is not useful to make this a local variable.
262;;;(put 'find-file-hooks 'permanent-local t)
b4da00e9
RM
263(defvar find-file-hooks nil
264 "List of functions to be called after a buffer is loaded from a file.
265The buffer's local variables (if any) will have been processed before the
266functions are called.")
267
b4da00e9
RM
268(defvar write-file-hooks nil
269 "List of functions to be called before writing out a buffer to a file.
270If one of them returns non-nil, the file is considered already written
8c0e7b73
JB
271and the rest are not called.
272These hooks are considered to pertain to the visited file.
273So this list is cleared if you change the visited file name.
f82966e4
KH
274
275Don't make this variable buffer-local; instead, use `local-write-file-hooks'.
276See also `write-contents-hooks'.")
b19f1da4
BF
277;;; However, in case someone does make it local...
278(put 'write-file-hooks 'permanent-local t)
c9dca4e0 279
c9dca4e0
RS
280(defvar local-write-file-hooks nil
281 "Just like `write-file-hooks', except intended for per-buffer use.
282The functions in this list are called before the ones in
f82966e4
KH
283`write-file-hooks'.
284
285This variable is meant to be used for hooks that have to do with a
286particular visited file. Therefore, it is a permanent local, so that
287changing the major mode does not clear it. However, calling
288`set-visited-file-name' does clear it.")
b19f1da4
BF
289(make-variable-buffer-local 'local-write-file-hooks)
290(put 'local-write-file-hooks 'permanent-local t)
8c0e7b73
JB
291
292(defvar write-contents-hooks nil
293 "List of functions to be called before writing out a buffer to a file.
294If one of them returns non-nil, the file is considered already written
295and the rest are not called.
f82966e4
KH
296
297This variable is meant to be used for hooks that pertain to the
298buffer's contents, not to the particular visited file; thus,
299`set-visited-file-name' does not clear this variable; but changing the
693f800d
RS
300major mode does clear it.
301
302This variable automatically becomes buffer-local whenever it is set.
659ebcc6 303If you use `add-hook' to add elements to the list, use nil for the
693f800d 304LOCAL argument.
f82966e4 305
8c0e7b73 306See also `write-file-hooks'.")
f82966e4 307(make-variable-buffer-local 'write-contents-hooks)
b4da00e9 308
21540597 309(defcustom enable-local-variables t
93a2702d 310 "*Control use of local variables in files you visit.
b4da00e9 311The value can be t, nil or something else.
93a2702d 312A value of t means file local variables specifications are obeyed;
b4da00e9
RM
313nil means they are ignored; anything else means query.
314
93a2702d 315The command \\[normal-mode] always obeys file local variable
21540597
RS
316specifications and ignores this variable."
317 :type '(choice (const :tag "Obey" t)
318 (const :tag "Ignore" nil)
319 (sexp :tag "Query" :format "%t\n" other))
320 :group 'find-file)
b4da00e9 321
21540597 322(defcustom enable-local-eval 'maybe
d207b766
RS
323 "*Control processing of the \"variable\" `eval' in a file's local variables.
324The value can be t, nil or something else.
325A value of t means obey `eval' variables;
326nil means ignore them; anything else means query.
327
328The command \\[normal-mode] always obeys local-variables lists
21540597
RS
329and ignores this variable."
330 :type '(choice (const :tag "Obey" t)
331 (const :tag "Ignore" nil)
332 (sexp :tag "Query" :format "%t\n" other))
333 :group 'find-file)
b4da00e9
RM
334
335;; Avoid losing in versions where CLASH_DETECTION is disabled.
336(or (fboundp 'lock-buffer)
231c4e10 337 (defalias 'lock-buffer 'ignore))
b4da00e9 338(or (fboundp 'unlock-buffer)
231c4e10 339 (defalias 'unlock-buffer 'ignore))
a7305f6e
RS
340(or (fboundp 'file-locked-p)
341 (defalias 'file-locked-p 'ignore))
93fe0a35 342
2a9fe1e2
RS
343(defvar view-read-only nil
344 "*Non-nil means buffers visiting files read-only, do it in view mode.")
345
93fe0a35
RS
346;; This hook function provides support for ange-ftp host name
347;; completion. It runs the usual ange-ftp hook, but only for
348;; completion operations. Having this here avoids the need
349;; to load ange-ftp when it's not really in use.
350(defun ange-ftp-completion-hook-function (op &rest args)
351 (if (memq op '(file-name-completion file-name-all-completions))
352 (apply 'ange-ftp-hook-function op args)
57e81f57
RS
353 (let ((inhibit-file-name-handlers
354 (cons 'ange-ftp-completion-hook-function
355 (and (eq inhibit-file-name-operation op)
356 inhibit-file-name-handlers)))
357 (inhibit-file-name-operation op))
93fe0a35 358 (apply op args))))
567c1ca9
RS
359
360(defun convert-standard-filename (filename)
361 "Convert a standard file's name to something suitable for the current OS.
362This function's standard definition is trivial; it just returns the argument.
363However, on some systems, the function is redefined
364with a definition that really does change some file names."
365 filename)
b4da00e9
RM
366\f
367(defun pwd ()
368 "Show the current default directory."
369 (interactive nil)
370 (message "Directory %s" default-directory))
371
231c4e10
ER
372(defvar cd-path nil
373 "Value of the CDPATH environment variable, as a list.
374Not actually set up until the first time you you use it.")
375
306faa42 376(defvar path-separator ":"
db8c4866 377 "Character used to separate directories in search paths.")
306faa42 378
231c4e10 379(defun parse-colon-path (cd-path)
db8c4866 380 "Explode a colon-separated search path into a list of directory names."
231c4e10
ER
381 (and cd-path
382 (let (cd-prefix cd-list (cd-start 0) cd-colon)
306faa42
RS
383 (setq cd-path (concat cd-path path-separator))
384 (while (setq cd-colon (string-match path-separator cd-path cd-start))
231c4e10 385 (setq cd-list
9daefb36 386 (nconc cd-list
c52e4104
RS
387 (list (if (= cd-start cd-colon)
388 nil
389 (substitute-in-file-name
e33e80e4
RS
390 (file-name-as-directory
391 (substring cd-path cd-start cd-colon)))))))
231c4e10
ER
392 (setq cd-start (+ cd-colon 1)))
393 cd-list)))
394
395(defun cd-absolute (dir)
30c5ce9c 396 "Change current directory to given absolute file name DIR."
f4a0f59b
RS
397 ;; Put the name into directory syntax now,
398 ;; because otherwise expand-file-name may give some bad results.
b4da00e9
RM
399 (if (not (eq system-type 'vax-vms))
400 (setq dir (file-name-as-directory dir)))
f4a0f59b 401 (setq dir (abbreviate-file-name (expand-file-name dir)))
b4da00e9 402 (if (not (file-directory-p dir))
83c6f446
RS
403 (if (file-exists-p dir)
404 (error "%s is not a directory" dir)
31c691c1 405 (error "%s: no such directory" dir))
b4da00e9
RM
406 (if (file-executable-p dir)
407 (setq default-directory dir)
9daefb36 408 (error "Cannot cd to %s: Permission denied" dir))))
b4da00e9 409
231c4e10
ER
410(defun cd (dir)
411 "Make DIR become the current buffer's default directory.
30c5ce9c
RS
412If your environment includes a `CDPATH' variable, try each one of that
413colon-separated list of directories when resolving a relative directory name."
dac4ea74
RS
414 (interactive
415 (list (read-file-name "Change default directory: "
2121cd9c
RM
416 default-directory default-directory
417 (and (member cd-path '(nil ("./")))
418 (null (getenv "CDPATH"))))))
30c5ce9c
RS
419 (if (file-name-absolute-p dir)
420 (cd-absolute (expand-file-name dir))
421 (if (null cd-path)
422 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
423 (setq cd-path (or trypath (list "./")))))
424 (if (not (catch 'found
425 (mapcar
426 (function (lambda (x)
427 (let ((f (expand-file-name (concat x dir))))
428 (if (file-directory-p f)
429 (progn
430 (cd-absolute f)
431 (throw 'found t))))))
432 cd-path)
433 nil))
434 (error "No such directory found via CDPATH environment variable"))))
231c4e10 435
b4da00e9
RM
436(defun load-file (file)
437 "Load the Lisp file named FILE."
438 (interactive "fLoad file: ")
439 (load (expand-file-name file) nil nil t))
440
441(defun load-library (library)
442 "Load the library named LIBRARY.
443This is an interface to the function `load'."
444 (interactive "sLoad library: ")
445 (load library))
5d68c2c2 446
7c4b8f8c 447(defun file-local-copy (file &optional buffer)
5d68c2c2
RS
448 "Copy the file FILE into a temporary file on this machine.
449Returns the name of the local copy, or nil, if FILE is directly
450accessible."
6eaebaa2 451 (let ((handler (find-file-name-handler file 'file-local-copy)))
5d68c2c2
RS
452 (if handler
453 (funcall handler 'file-local-copy file)
454 nil)))
f3e23606 455
05ef1cda 456(defun file-truename (filename &optional counter prev-dirs)
f3e23606
RS
457 "Return the truename of FILENAME, which should be absolute.
458The truename of a file name is found by chasing symbolic links
459both at the level of the file and at the level of the directories
05ef1cda
RS
460containing it, until no links are left at any level.
461
462The arguments COUNTER and PREV-DIRS are used only in recursive calls.
463Do not specify them in other calls."
464 ;; COUNTER can be a cons cell whose car is the count of how many more links
465 ;; to chase before getting an error.
466 ;; PREV-DIRS can be a cons cell whose car is an alist
467 ;; of truenames we've just recently computed.
cc37a58c 468
cc37a58c
SM
469 ;; The last test looks dubious, maybe `+' is meant here? --simon.
470 (if (or (string= filename "") (string= filename "~")
7a5a26a6
RS
471 (and (string= (substring filename 0 1) "~")
472 (string-match "~[^/]*" filename)))
1cc2fbeb
RS
473 (progn
474 (setq filename (expand-file-name filename))
475 (if (string= filename "")
476 (setq filename "/"))))
05ef1cda 477 (or counter (setq counter (list 100)))
b505828b
RS
478 (let (done
479 ;; For speed, remove the ange-ftp completion handler from the list.
480 ;; We know it's not needed here.
481 ;; For even more speed, do this only on the outermost call.
482 (file-name-handler-alist
483 (if prev-dirs file-name-handler-alist
484 (let ((tem (copy-sequence file-name-handler-alist)))
485 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
486 (or prev-dirs (setq prev-dirs (list nil)))
b1667e6c
GV
487
488 ;; andrewi@harlequin.co.uk - none of the following code (except for
489 ;; invoking the file-name handler) currently applies on Windows
490 ;; (ie. there are no native symlinks), but there is an issue with
491 ;; case differences being ignored by the OS, and short "8.3 DOS"
492 ;; name aliases existing for all files. (The short names are not
493 ;; reported by directory-files, but can be used to refer to files.)
494 ;; It seems appropriate for file-truename to resolve these issues in
495 ;; the most natural way, which on Windows is to call the function
496 ;; `w32-long-file-name' - this returns the exact name of a file as
497 ;; it is stored on disk (expanding short name aliases with the full
498 ;; name in the process).
499 (if (eq system-type 'windows-nt)
500 (let ((handler (find-file-name-handler filename 'file-truename))
501 newname)
502 ;; For file name that has a special handler, call handler.
503 ;; This is so that ange-ftp can save time by doing a no-op.
504 (if handler
505 (setq filename (funcall handler 'file-truename filename))
506 ;; If filename contains a wildcard, newname will be the old name.
507 (if (string-match "[*?]" filename)
508 (setq newname filename)
509 ;; If filename doesn't exist, newname will be nil.
510 (setq newname (w32-long-file-name filename)))
511 (setq filename (or newname filename)))
512 (setq done t)))
513
05ef1cda
RS
514 ;; If this file directly leads to a link, process that iteratively
515 ;; so that we don't use lots of stack.
516 (while (not done)
517 (setcar counter (1- (car counter)))
518 (if (< (car counter) 0)
519 (error "Apparent cycle of symbolic links for %s" filename))
520 (let ((handler (find-file-name-handler filename 'file-truename)))
521 ;; For file name that has a special handler, call handler.
522 ;; This is so that ange-ftp can save time by doing a no-op.
523 (if handler
524 (setq filename (funcall handler 'file-truename filename)
525 done t)
fb145562 526 (let ((dir (or (file-name-directory filename) default-directory))
05ef1cda
RS
527 target dirfile)
528 ;; Get the truename of the directory.
529 (setq dirfile (directory-file-name dir))
530 ;; If these are equal, we have the (or a) root directory.
531 (or (string= dir dirfile)
532 ;; If this is the same dir we last got the truename for,
533 ;; save time--don't recalculate.
534 (if (assoc dir (car prev-dirs))
535 (setq dir (cdr (assoc dir (car prev-dirs))))
536 (let ((old dir)
537 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
538 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
539 (setq dir new))))
540 (if (equal ".." (file-name-nondirectory filename))
541 (setq filename
542 (directory-file-name (file-name-directory (directory-file-name dir)))
543 done t)
544 (if (equal "." (file-name-nondirectory filename))
545 (setq filename (directory-file-name dir)
546 done t)
547 ;; Put it back on the file name.
548 (setq filename (concat dir (file-name-nondirectory filename)))
549 ;; Is the file name the name of a link?
550 (setq target (file-symlink-p filename))
551 (if target
552 ;; Yes => chase that link, then start all over
553 ;; since the link may point to a directory name that uses links.
554 ;; We can't safely use expand-file-name here
555 ;; since target might look like foo/../bar where foo
556 ;; is itself a link. Instead, we handle . and .. above.
557 (setq filename
558 (if (file-name-absolute-p target)
559 target
560 (concat dir target))
561 done nil)
562 ;; No, we are done!
563 (setq done t))))))))
564 filename))
5dbfdacd 565
5dadeb29
RS
566(defun file-chase-links (filename)
567 "Chase links in FILENAME until a name that is not a link.
568Does not examine containing directories for links,
569unlike `file-truename'."
570 (let (tem (count 100) (newname filename))
571 (while (setq tem (file-symlink-p newname))
9695aac6
RS
572 (save-match-data
573 (if (= count 0)
574 (error "Apparent cycle of symbolic links for %s" filename))
575 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
576 (while (string-match "//+" tem)
577 (setq tem (replace-match "/" nil nil tem)))
578 ;; Handle `..' by hand, since it needs to work in the
579 ;; target of any directory symlink.
580 ;; This code is not quite complete; it does not handle
581 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
582 (while (string-match "\\`\\.\\./" tem)
583 (setq tem (substring tem 3))
584 (setq newname (expand-file-name newname))
585 ;; Chase links in the default dir of the symlink.
586 (setq newname
587 (file-chase-links
588 (directory-file-name (file-name-directory newname))))
589 ;; Now find the parent of that dir.
590 (setq newname (file-name-directory newname)))
591 (setq newname (expand-file-name tem (file-name-directory newname)))
592 (setq count (1- count))))
5dadeb29 593 newname))
b4da00e9 594\f
467ff692
RS
595(defun switch-to-buffer-other-window (buffer &optional norecord)
596 "Select buffer BUFFER in another window.
597Optional second arg NORECORD non-nil means
598do not put this buffer at the front of the list of recently selected ones."
b4da00e9
RM
599 (interactive "BSwitch to buffer in other window: ")
600 (let ((pop-up-windows t))
467ff692 601 (pop-to-buffer buffer t norecord)))
b4da00e9 602
467ff692
RS
603(defun switch-to-buffer-other-frame (buffer &optional norecord)
604 "Switch to buffer BUFFER in another frame.
605Optional second arg NORECORD non-nil means
606do not put this buffer at the front of the list of recently selected ones."
f98955ea
JB
607 (interactive "BSwitch to buffer in other frame: ")
608 (let ((pop-up-frames t))
467ff692 609 (pop-to-buffer buffer t norecord)
336b7f41 610 (raise-frame (window-frame (selected-window)))))
5bbbceb1 611
912192d1 612(defun find-file (filename)
b4da00e9
RM
613 "Edit file FILENAME.
614Switch to a buffer visiting file FILENAME,
912192d1
KH
615creating one if none already exists."
616 (interactive "FFind file: ")
617 (switch-to-buffer (find-file-noselect filename)))
82d0954a 618
912192d1 619(defun find-file-other-window (filename)
b4da00e9
RM
620 "Edit file FILENAME, in another window.
621May create a new window, or reuse an existing one.
622See the function `display-buffer'."
912192d1
KH
623 (interactive "FFind file in other window: ")
624 (switch-to-buffer-other-window (find-file-noselect filename)))
b4da00e9 625
912192d1 626(defun find-file-other-frame (filename)
f98955ea
JB
627 "Edit file FILENAME, in another frame.
628May create a new frame, or reuse an existing one.
5bbbceb1 629See the function `display-buffer'."
912192d1
KH
630 (interactive "FFind file in other frame: ")
631 (switch-to-buffer-other-frame (find-file-noselect filename)))
5bbbceb1 632
912192d1 633(defun find-file-read-only (filename)
b4da00e9
RM
634 "Edit file FILENAME but don't allow changes.
635Like \\[find-file] but marks buffer as read-only.
636Use \\[toggle-read-only] to permit editing."
912192d1
KH
637 (interactive "fFind file read-only: ")
638 (find-file filename)
2a9fe1e2 639 (toggle-read-only 1)
320b4233 640 (current-buffer))
b4da00e9 641
912192d1 642(defun find-file-read-only-other-window (filename)
b4da00e9
RM
643 "Edit file FILENAME in another window but don't allow changes.
644Like \\[find-file-other-window] but marks buffer as read-only.
645Use \\[toggle-read-only] to permit editing."
912192d1
KH
646 (interactive "fFind file read-only other window: ")
647 (find-file-other-window filename)
2a9fe1e2 648 (toggle-read-only 1)
320b4233 649 (current-buffer))
b4da00e9 650
912192d1 651(defun find-file-read-only-other-frame (filename)
f98955ea
JB
652 "Edit file FILENAME in another frame but don't allow changes.
653Like \\[find-file-other-frame] but marks buffer as read-only.
5bbbceb1 654Use \\[toggle-read-only] to permit editing."
912192d1
KH
655 (interactive "fFind file read-only other frame: ")
656 (find-file-other-frame filename)
2a9fe1e2 657 (toggle-read-only 1)
320b4233 658 (current-buffer))
5bbbceb1 659
912192d1 660(defun find-alternate-file-other-window (filename)
60eaf370 661 "Find file FILENAME as a replacement for the file in the next window.
912192d1 662This command does not select that window."
60eaf370
RS
663 (interactive
664 (save-selected-window
665 (other-window 1)
666 (let ((file buffer-file-name)
667 (file-name nil)
668 (file-dir nil))
669 (and file
670 (setq file-name (file-name-nondirectory file)
671 file-dir (file-name-directory file)))
672 (list (read-file-name
912192d1 673 "Find alternate file: " file-dir nil nil file-name)))))
60eaf370 674 (if (one-window-p)
912192d1 675 (find-file-other-window filename)
60eaf370
RS
676 (save-selected-window
677 (other-window 1)
912192d1 678 (find-alternate-file filename))))
60eaf370 679
912192d1 680(defun find-alternate-file (filename)
b4da00e9
RM
681 "Find file FILENAME, select its buffer, kill previous buffer.
682If the current buffer now contains an empty file that you just visited
912192d1 683\(presumably by mistake), use this command to visit the file you really want."
b4da00e9
RM
684 (interactive
685 (let ((file buffer-file-name)
686 (file-name nil)
687 (file-dir nil))
688 (and file
689 (setq file-name (file-name-nondirectory file)
690 file-dir (file-name-directory file)))
a61f59b4 691 (list (read-file-name
912192d1 692 "Find alternate file: " file-dir nil nil file-name))))
2aa8cc2d 693 (and (buffer-modified-p) (buffer-file-name)
b4da00e9
RM
694 ;; (not buffer-read-only)
695 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
696 (buffer-name))))
697 (error "Aborted"))
698 (let ((obuf (current-buffer))
699 (ofile buffer-file-name)
8bb27285
RS
700 (onum buffer-file-number)
701 (otrue buffer-file-truename)
b4da00e9 702 (oname (buffer-name)))
baf9b8c4
RS
703 (if (get-buffer " **lose**")
704 (kill-buffer " **lose**"))
b4da00e9 705 (rename-buffer " **lose**")
b4da00e9
RM
706 (unwind-protect
707 (progn
708 (unlock-buffer)
a4ad4d96
RS
709 (setq buffer-file-name nil)
710 (setq buffer-file-number nil)
711 (setq buffer-file-truename nil)
912192d1 712 (find-file filename))
b4da00e9
RM
713 (cond ((eq obuf (current-buffer))
714 (setq buffer-file-name ofile)
8bb27285
RS
715 (setq buffer-file-number onum)
716 (setq buffer-file-truename otrue)
b4da00e9
RM
717 (lock-buffer)
718 (rename-buffer oname))))
719 (or (eq (current-buffer) obuf)
720 (kill-buffer obuf))))
9b8ef27d 721\f
b4da00e9
RM
722(defun create-file-buffer (filename)
723 "Create a suitably named buffer for visiting FILENAME, and return it.
724FILENAME (sans directory) is used unchanged if that name is free;
725otherwise a string <2> or <3> or ... is appended to get an unused name."
726 (let ((lastname (file-name-nondirectory filename)))
727 (if (string= lastname "")
728 (setq lastname filename))
729 (generate-new-buffer lastname)))
730
5bbbceb1
JB
731(defun generate-new-buffer (name)
732 "Create and return a buffer with a name based on NAME.
29165787 733Choose the buffer's name using `generate-new-buffer-name'."
5bbbceb1
JB
734 (get-buffer-create (generate-new-buffer-name name)))
735
d7fa5aa2 736(defvar automount-dir-prefix "^/tmp_mnt/"
e373f201
JB
737 "Regexp to match the automounter prefix in a directory name.")
738
ffb3a4db 739(defvar abbreviated-home-dir nil
292297c6 740 "The user's homedir abbreviated according to `directory-abbrev-list'.")
ffb3a4db 741
5bbbceb1 742(defun abbreviate-file-name (filename)
29165787 743 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
5bbbceb1 744This also substitutes \"~\" for the user's home directory.
29165787 745Type \\[describe-variable] directory-abbrev-alist RET for more information."
e373f201 746 ;; Get rid of the prefixes added by the automounter.
a8f34fc0
RS
747 (if (and automount-dir-prefix
748 (string-match automount-dir-prefix filename)
e373f201
JB
749 (file-exists-p (file-name-directory
750 (substring filename (1- (match-end 0))))))
751 (setq filename (substring filename (1- (match-end 0)))))
5bbbceb1 752 (let ((tail directory-abbrev-alist))
ffb3a4db
RS
753 ;; If any elt of directory-abbrev-alist matches this name,
754 ;; abbreviate accordingly.
5bbbceb1
JB
755 (while tail
756 (if (string-match (car (car tail)) filename)
757 (setq filename
758 (concat (cdr (car tail)) (substring filename (match-end 0)))))
759 (setq tail (cdr tail)))
ffb3a4db
RS
760 ;; Compute and save the abbreviated homedir name.
761 ;; We defer computing this until the first time it's needed, to
762 ;; give time for directory-abbrev-alist to be set properly.
e98dda89
RS
763 ;; We include a slash at the end, to avoid spurious matches
764 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
ffb3a4db
RS
765 (or abbreviated-home-dir
766 (setq abbreviated-home-dir
767 (let ((abbreviated-home-dir "$foo"))
3a8a836d
RS
768 (concat "^" (abbreviate-file-name (expand-file-name "~"))
769 "\\(/\\|$\\)"))))
76d5492b 770
ffb3a4db
RS
771 ;; If FILENAME starts with the abbreviated homedir,
772 ;; make it start with `~' instead.
ca33ccb5
RS
773 (if (and (string-match abbreviated-home-dir filename)
774 ;; If the home dir is just /, don't change it.
775 (not (and (= (match-end 0) 1)
288201bd 776 (= (aref filename 0) ?/)))
567c1ca9
RS
777 ;; MS-DOS root directories can come with a drive letter;
778 ;; Novell Netware allows drive letters beyond `Z:'.
76d5492b 779 (not (and (or (eq system-type 'ms-dos)
c32d49e8 780 (eq system-type 'windows-nt))
288201bd 781 (save-match-data
567c1ca9 782 (string-match "^[a-zA-`]:/$" filename)))))
5bbbceb1 783 (setq filename
28dbf501 784 (concat "~"
3a8a836d 785 (substring filename (match-beginning 1) (match-end 1))
28dbf501 786 (substring filename (match-end 0)))))
5bbbceb1
JB
787 filename))
788
21540597 789(defcustom find-file-not-true-dirname-list nil
1770543d
RS
790 "*List of logical names for which visiting shouldn't save the true dirname.
791On VMS, when you visit a file using a logical name that searches a path,
792you may or may not want the visited file name to record the specific
793directory where the file was found. If you *do not* want that, add the logical
21540597
RS
794name to this list as a string."
795 :type '(repeat (string :tag "Name"))
796 :group 'find-file)
1770543d 797
138c44f6
KH
798(defun find-buffer-visiting (filename)
799 "Return the buffer visiting file FILENAME (a string).
800This is like `get-file-buffer', except that it checks for any buffer
801visiting the same file, possibly under a different name.
802If there is no such live buffer, return nil."
803 (let ((buf (get-file-buffer filename))
804 (truename (abbreviate-file-name (file-truename filename))))
805 (or buf
806 (let ((list (buffer-list)) found)
807 (while (and (not found) list)
808 (save-excursion
809 (set-buffer (car list))
810 (if (and buffer-file-name
811 (string= buffer-file-truename truename))
812 (setq found (car list))))
813 (setq list (cdr list)))
814 found)
0f933cf6 815 (let ((number (nthcdr 10 (file-attributes truename)))
138c44f6 816 (list (buffer-list)) found)
de88363f
RS
817 (and buffer-file-numbers-unique
818 number
181c830f
RS
819 (while (and (not found) list)
820 (save-excursion
821 (set-buffer (car list))
d49ab5a0
RS
822 (if (and buffer-file-name
823 (equal buffer-file-number number)
181c830f
RS
824 ;; Verify this buffer's file number
825 ;; still belongs to its file.
826 (file-exists-p buffer-file-name)
827 (equal (nthcdr 10 (file-attributes buffer-file-name))
828 number))
829 (setq found (car list))))
830 (setq list (cdr list))))
138c44f6 831 found))))
9b8ef27d 832\f
40dfe94d 833(defun find-file-noselect (filename &optional nowarn rawfile)
b4da00e9
RM
834 "Read file FILENAME into a buffer and return the buffer.
835If a buffer exists visiting FILENAME, return that one, but
836verify that the file has not changed since visited or saved.
82d0954a
KH
837The buffer is not selected, just returned to the caller.
838Optional first arg NOWARN non-nil means suppress any warning messages.
e65db7b8 839Optional second arg RAWFILE non-nil means the file is read literally."
e373f201
JB
840 (setq filename
841 (abbreviate-file-name
842 (expand-file-name filename)))
b4da00e9
RM
843 (if (file-directory-p filename)
844 (if find-file-run-dired
4147a3cc
KH
845 (dired-noselect (if find-file-visit-truename
846 (abbreviate-file-name (file-truename filename))
847 filename))
ba369f54 848 (error "%s is a directory" filename))
f3e23606
RS
849 (let* ((buf (get-file-buffer filename))
850 (truename (abbreviate-file-name (file-truename filename)))
851 (number (nthcdr 10 (file-attributes truename)))
852 ;; Find any buffer for a file which has same truename.
138c44f6 853 (other (and (not buf) (find-buffer-visiting filename)))
f3e23606
RS
854 error)
855 ;; Let user know if there is a buffer with the same truename.
138c44f6
KH
856 (if other
857 (progn
327bebe8
RS
858 (or nowarn
859 (string-equal filename (buffer-file-name other))
860 (message "%s and %s are the same file"
861 filename (buffer-file-name other)))
138c44f6
KH
862 ;; Optionally also find that buffer.
863 (if (or find-file-existing-other-name find-file-visit-truename)
864 (setq buf other))))
b4da00e9
RM
865 (if buf
866 (or nowarn
867 (verify-visited-file-modtime buf)
868 (cond ((not (file-exists-p filename))
869 (error "File %s no longer exists!" filename))
ebeb898f
RS
870 ;; Certain files should be reverted automatically
871 ;; if they have changed on disk and not in the buffer.
872 ((and (not (buffer-modified-p buf))
db8c4866 873 (let ((tail revert-without-query)
ebeb898f
RS
874 (found nil))
875 (while tail
876 (if (string-match (car tail) filename)
877 (setq found t))
878 (setq tail (cdr tail)))
879 found))
880 (with-current-buffer buf
881 (message "Reverting file %s..." filename)
882 (revert-buffer t t)
883 (message "Reverting file %s...done" filename)))
b4da00e9 884 ((yes-or-no-p
b7d19f4a
KH
885 (if (string= (file-name-nondirectory filename)
886 (buffer-name buf))
887 (format
888 (if (buffer-modified-p buf)
889 "File %s changed on disk. Discard your edits? "
890 "File %s changed on disk. Reread from disk? ")
891 (file-name-nondirectory filename))
892 (format
893 (if (buffer-modified-p buf)
894 "File %s changed on disk. Discard your edits in %s? "
895 "File %s changed on disk. Reread from disk into %s? ")
896 (file-name-nondirectory filename)
897 (buffer-name buf))))
ebeb898f 898 (with-current-buffer buf
9b8ef27d
RS
899 (revert-buffer t t)))
900 ((not (eq rawfile (not (null find-file-literally))))
901 (if rawfile
902 (message "File is already visited, and not literally")
903 (message "File is already visited, and visited literally")))))
b4da00e9 904 (save-excursion
f3e23606
RS
905;;; The truename stuff makes this obsolete.
906;;; (let* ((link-name (car (file-attributes filename)))
907;;; (linked-buf (and (stringp link-name)
908;;; (get-file-buffer link-name))))
909;;; (if (bufferp linked-buf)
910;;; (message "Symbolic link to file in buffer %s"
911;;; (buffer-name linked-buf))))
b4da00e9 912 (setq buf (create-file-buffer filename))
a2e12c0c 913 (set-buffer-major-mode buf)
b4da00e9
RM
914 (set-buffer buf)
915 (erase-buffer)
40dfe94d
RS
916 (if rawfile
917 (condition-case ()
918 (insert-file-contents-literally filename t)
919 (file-error
7b3d6b9c
RS
920 (when (and (file-exists-p filename)
921 (not (file-readable-p filename)))
944ef994
RS
922 (kill-buffer buf)
923 (signal 'file-error (list "File is not readable"
924 filename)))
40dfe94d
RS
925 ;; Unconditionally set error
926 (setq error t)))
927 (condition-case ()
928 (insert-file-contents filename t)
929 (file-error
7b3d6b9c
RS
930 (when (and (file-exists-p filename)
931 (not (file-readable-p filename)))
944ef994
RS
932 (kill-buffer buf)
933 (signal 'file-error (list "File is not readable"
934 filename)))
40dfe94d
RS
935 ;; Run find-file-not-found-hooks until one returns non-nil.
936 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
937 ;; If they fail too, set error.
938 (setq error t)))))
f3e23606 939 ;; Find the file's truename, and maybe use that as visited name.
138c44f6 940 (setq buffer-file-truename truename)
1770543d
RS
941 (setq buffer-file-number number)
942 ;; On VMS, we may want to remember which directory in a search list
943 ;; the file was found in.
944 (and (eq system-type 'vax-vms)
945 (let (logical)
946 (if (string-match ":" (file-name-directory filename))
947 (setq logical (substring (file-name-directory filename)
948 0 (match-beginning 0))))
949 (not (member logical find-file-not-true-dirname-list)))
950 (setq buffer-file-name buffer-file-truename))
1cc2fbeb 951 (if find-file-visit-truename
27d0420c
RS
952 (setq buffer-file-name
953 (setq filename
954 (expand-file-name buffer-file-truename))))
b4da00e9
RM
955 ;; Set buffer's default directory to that of the file.
956 (setq default-directory (file-name-directory filename))
957 ;; Turn off backup files for certain file names. Since
958 ;; this is a permanent local, the major mode won't eliminate it.
959 (and (not (funcall backup-enable-predicate buffer-file-name))
960 (progn
961 (make-local-variable 'backup-inhibited)
962 (setq backup-inhibited t)))
40dfe94d 963 (if rawfile
9b8ef27d
RS
964 (progn
965 (setq enable-multibyte-characters nil)
966 (make-local-variable 'find-file-literally)
967 (setq find-file-literally t))
fa660969
KH
968 (after-find-file error (not nowarn))
969 (setq buf (current-buffer)))))
b4da00e9 970 buf)))
9b8ef27d
RS
971\f
972(defun insert-file-contents-literally (filename &optional visit beg end replace)
973 "Like `insert-file-contents', but only reads in the file literally.
974A buffer may be modified in several ways after reading into the buffer,
975to Emacs features such as format decoding, character code
976conversion, find-file-hooks, automatic uncompression, etc.
977
978This function ensures that none of these modifications will take place."
979 (let ((format-alist nil)
980 (after-insert-file-functions nil)
981 (coding-system-for-read 'no-conversion)
982 (coding-system-for-write 'no-conversion)
983 (jka-compr-compression-info-list nil)
984 (find-buffer-file-type-function
985 (if (fboundp 'find-buffer-file-type)
986 (symbol-function 'find-buffer-file-type)
987 nil)))
988 (unwind-protect
989 (progn
990 (fset 'find-buffer-file-type (lambda (filename) t))
991 (insert-file-contents filename visit beg end replace))
992 (if find-buffer-file-type-function
993 (fset 'find-buffer-file-type find-buffer-file-type-function)
994 (fmakunbound 'find-buffer-file-type)))))
995
996(defun insert-file-literally (filename)
997 "Insert contents of file FILENAME into buffer after point with no conversion.
998
999This function is meant for the user to run interactively.
1000Don't call it from programs! Use `insert-file-contents-literally' instead.
1001\(Its calling sequence is different; see its documentation)."
1002 (interactive "*fInsert file literally: ")
1003 (if (file-directory-p filename)
1004 (signal 'file-error (list "Opening input file" "file is a directory"
1005 filename)))
1006 (let ((tem (insert-file-contents-literally filename)))
1007 (push-mark (+ (point) (car (cdr tem))))))
1008
1009(defvar find-file-literally nil
1010 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
1011This is a permanent local.")
1012(put 'find-file-literally 'permanent-local t)
5fc196af
RS
1013
1014(defun find-file-literally (filename)
1015 "Visit file FILENAME with no conversion of any kind.
1016Format conversion and character code conversion are both disabled,
1017and multibyte characters are disabled in the resulting buffer.
e65db7b8
RS
1018The major mode used is Fundamental mode regardless of the file name,
1019and local variable specifications in the file are ignored.
9b8ef27d
RS
1020Automatic uncompression is also disabled.
1021
1022You cannot absolutely rely on this function to result in
b9aa9537 1023visiting the file literally. If Emacs already has a buffer
9b8ef27d
RS
1024which is visiting the file, you get the existing buffer,
1025regardless of whether it was created literally or not.
1026
1027In a Lisp program, if you want to be sure of accessing a file's
1028contents literally, you should create a temporary buffer and then read
1029the file contents into it using `insert-file-contents-literally'."
5fc196af 1030 (interactive "FFind file literally: ")
9b8ef27d 1031 (switch-to-buffer (find-file-noselect filename nil t)))
b4da00e9 1032\f
f7d786d0
RS
1033(defvar after-find-file-from-revert-buffer nil)
1034
e0ab8879 1035(defun after-find-file (&optional error warn noauto
9a30563f
RS
1036 after-find-file-from-revert-buffer
1037 nomodes)
b4da00e9
RM
1038 "Called after finding a file and by the default revert function.
1039Sets buffer mode, parses local variables.
8cfb9d46 1040Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
b4da00e9
RM
1041error in reading the file. WARN non-nil means warn if there
1042exists an auto-save file more recent than the visited file.
8cfb9d46 1043NOAUTO means don't mess with auto-save mode.
e0ab8879
RS
1044Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1045 means this call was from `revert-buffer'.
9a30563f
RS
1046Fifth arg NOMODES non-nil means don't alter the file's modes.
1047Finishes by calling the functions in `find-file-hooks'
1048unless NOMODES is non-nil."
b4da00e9
RM
1049 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1050 (if noninteractive
1051 nil
1052 (let* (not-serious
1053 (msg
1054 (cond ((and error (file-attributes buffer-file-name))
1055 (setq buffer-read-only t)
ff78d520 1056 "File exists, but cannot be read.")
b4da00e9
RM
1057 ((not buffer-read-only)
1058 (if (and warn
1059 (file-newer-than-file-p (make-auto-save-file-name)
1060 buffer-file-name))
6a6a0b8b
RS
1061 (format "%s has auto save data; consider M-x recover-file"
1062 (file-name-nondirectory buffer-file-name))
b4da00e9
RM
1063 (setq not-serious t)
1064 (if error "(New file)" nil)))
1065 ((not error)
1066 (setq not-serious t)
1067 "Note: file is write protected")
1068 ((file-attributes (directory-file-name default-directory))
1069 "File not found and directory write-protected")
4e43240a
RS
1070 ((file-exists-p (file-name-directory buffer-file-name))
1071 (setq buffer-read-only nil))
b4da00e9 1072 (t
5bbbceb1 1073 (setq buffer-read-only nil)
4e43240a
RS
1074 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
1075 "Use M-x make-dir RET RET to create the directory"
1076 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
b4da00e9
RM
1077 (if msg
1078 (progn
1079 (message msg)
1080 (or not-serious (sit-for 1 nil t)))))
8cfb9d46 1081 (if (and auto-save-default (not noauto))
b4da00e9 1082 (auto-save-mode t)))
9a30563f
RS
1083 (if nomodes
1084 nil
1085 (normal-mode t)
2a9fe1e2
RS
1086 (if (and buffer-read-only view-read-only
1087 (not (eq (get major-mode 'mode-class) 'special)))
1088 (view-mode-enter))
9a30563f 1089 (run-hooks 'find-file-hooks)))
b4da00e9
RM
1090
1091(defun normal-mode (&optional find-file)
1092 "Choose the major mode for this buffer automatically.
1093Also sets up any specified local variables of the file.
1094Uses the visited file name, the -*- line, and the local variables spec.
1095
1096This function is called automatically from `find-file'. In that case,
1097we may set up specified local variables depending on the value of
1098`enable-local-variables': if it is t, we do; if it is nil, we don't;
1099otherwise, we query. `enable-local-variables' is ignored if you
1100run `normal-mode' explicitly."
1101 (interactive)
1102 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1103 (condition-case err
1104 (set-auto-mode)
1105 (error (message "File mode specification error: %s"
1106 (prin1-to-string err))))
1107 (condition-case err
7b3f3dc2
JB
1108 (let ((enable-local-variables (or (not find-file)
1109 enable-local-variables)))
1110 (hack-local-variables))
b4da00e9
RM
1111 (error (message "File local-variables error: %s"
1112 (prin1-to-string err)))))
1113
f76e0cd0 1114(defvar auto-mode-alist
567c1ca9 1115 '(("\\.te?xt\\'" . text-mode)
f76e0cd0
RS
1116 ("\\.c\\'" . c-mode)
1117 ("\\.h\\'" . c-mode)
1118 ("\\.tex\\'" . tex-mode)
1119 ("\\.ltx\\'" . latex-mode)
1120 ("\\.el\\'" . emacs-lisp-mode)
1121 ("\\.mm\\'" . nroff-mode)
1122 ("\\.me\\'" . nroff-mode)
1123 ("\\.ms\\'" . nroff-mode)
1124 ("\\.man\\'" . nroff-mode)
1125 ("\\.scm\\'" . scheme-mode)
1126 ("\\.l\\'" . lisp-mode)
1127 ("\\.lisp\\'" . lisp-mode)
1128 ("\\.f\\'" . fortran-mode)
0254679b 1129 ("\\.F\\'" . fortran-mode)
f76e0cd0
RS
1130 ("\\.for\\'" . fortran-mode)
1131 ("\\.p\\'" . pascal-mode)
1132 ("\\.pas\\'" . pascal-mode)
f76e0cd0 1133 ("\\.ad[abs]\\'" . ada-mode)
ebff6b7d 1134 ("\\.\\([pP][Llm]\\|al\\)\\'" . perl-mode)
f89cbd61 1135 ("\\.s?html?\\'" . html-mode)
f76e0cd0
RS
1136 ("\\.cc\\'" . c++-mode)
1137 ("\\.hh\\'" . c++-mode)
bfc6cac9 1138 ("\\.hpp\\'" . c++-mode)
f76e0cd0
RS
1139 ("\\.C\\'" . c++-mode)
1140 ("\\.H\\'" . c++-mode)
1141 ("\\.cpp\\'" . c++-mode)
1142 ("\\.cxx\\'" . c++-mode)
1143 ("\\.hxx\\'" . c++-mode)
1144 ("\\.c\\+\\+\\'" . c++-mode)
1145 ("\\.h\\+\\+\\'" . c++-mode)
1fbd6d0f 1146 ("\\.m\\'" . objc-mode)
95b53225 1147 ("\\.java\\'" . java-mode)
f76e0cd0 1148 ("\\.mk\\'" . makefile-mode)
5da565f8 1149 ("\\(M\\|m\\|GNUm\\)akefile\\(.in\\)?\\'" . makefile-mode)
3ad08c11 1150 ("\\.am\\'" . makefile-mode) ;For Automake.
7b3f3dc2
JB
1151;;; Less common extensions come here
1152;;; so more common ones above are found faster.
f76e0cd0 1153 ("\\.texinfo\\'" . texinfo-mode)
567c1ca9 1154 ("\\.te?xi\\'" . texinfo-mode)
f76e0cd0 1155 ("\\.s\\'" . asm-mode)
600a5f71
KH
1156 ("\\.S\\'" . asm-mode)
1157 ("\\.asm\\'" . asm-mode)
f76e0cd0
RS
1158 ("ChangeLog\\'" . change-log-mode)
1159 ("change.log\\'" . change-log-mode)
1160 ("changelo\\'" . change-log-mode)
1161 ("ChangeLog.[0-9]+\\'" . change-log-mode)
6e6f5d9e
RS
1162 ;; for MSDOS and MS-Windows (which are case-insensitive)
1163 ("changelog\\'" . change-log-mode)
1164 ("changelog.[0-9]+\\'" . change-log-mode)
f76e0cd0
RS
1165 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
1166 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
7458cc35 1167 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
d1194c85
RS
1168 ("/\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
1169 ("/\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
1170 ("/\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
c1fe251a
KH
1171;;; The following should come after the ChangeLog pattern
1172;;; for the sake of ChangeLog.1, etc.
1173;;; and after the .scm.[0-9] pattern too.
f76e0cd0
RS
1174 ("\\.[12345678]\\'" . nroff-mode)
1175 ("\\.TeX\\'" . tex-mode)
1176 ("\\.sty\\'" . latex-mode)
1177 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
16cb44dd 1178 ("\\.clo\\'" . latex-mode) ;LaTeX 2e class option
f76e0cd0
RS
1179 ("\\.bbl\\'" . latex-mode)
1180 ("\\.bib\\'" . bibtex-mode)
6c4fd436
RS
1181 ("\\.m4\\'" . m4-mode)
1182 ("\\.mc\\'" . m4-mode)
16cb44dd
RS
1183 ("\\.mf\\'" . metafont-mode)
1184 ("\\.mp\\'" . metapost-mode)
798f4b0a 1185 ("\\.vhdl?\\'" . vhdl-mode)
f76e0cd0
RS
1186 ("\\.article\\'" . text-mode)
1187 ("\\.letter\\'" . text-mode)
1188 ("\\.tcl\\'" . tcl-mode)
e1ec01c2 1189 ("\\.exp\\'" . tcl-mode)
c87c4cda
KH
1190 ("\\.itcl\\'" . tcl-mode)
1191 ("\\.itk\\'" . tcl-mode)
f89cbd61
RS
1192 ("\\.icn\\'" . icon-mode)
1193 ("\\.sim\\'" . simula-mode)
1194 ("\\.mss\\'" . scribe-mode)
f76e0cd0
RS
1195 ("\\.f90\\'" . f90-mode)
1196 ("\\.lsp\\'" . lisp-mode)
1197 ("\\.awk\\'" . awk-mode)
1198 ("\\.prolog\\'" . prolog-mode)
1199 ("\\.tar\\'" . tar-mode)
b1667e6c
GV
1200 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\|jar\\)\\'" . archive-mode)
1201 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\|JAR\\)\\'" . archive-mode)
f76e0cd0
RS
1202 ;; Mailer puts message to be edited in
1203 ;; /tmp/Re.... or Message
628b6035 1204 ("\\`/tmp/Re" . text-mode)
f76e0cd0
RS
1205 ("/Message[0-9]*\\'" . text-mode)
1206 ("/drafts/[0-9]+\\'" . mh-letter-mode)
1207 ;; some news reader is reported to use this
628b6035 1208 ("\\`/tmp/fol/" . text-mode)
f76e0cd0
RS
1209 ("\\.y\\'" . c-mode)
1210 ("\\.lex\\'" . c-mode)
1211 ("\\.oak\\'" . scheme-mode)
693f800d 1212 ("\\.sgml?\\'" . sgml-mode)
f76e0cd0 1213 ("\\.dtd\\'" . sgml-mode)
c2c84cd7 1214 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
f76e0cd0 1215 ;; .emacs following a directory delimiter
24813e13
RS
1216 ;; in Unix, MSDOG or VMS syntax.
1217 ("[]>:/\\]\\..*emacs\\'" . emacs-lisp-mode)
f76e0cd0
RS
1218 ;; _emacs following a directory delimiter
1219 ;; in MsDos syntax
1220 ("[:/]_emacs\\'" . emacs-lisp-mode)
1221 ("\\.ml\\'" . lisp-mode))
7b3f3dc2
JB
1222 "\
1223Alist of filename patterns vs corresponding major mode functions.
116987ba
RS
1224Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1225\(NON-NIL stands for anything that is not nil; the value does not matter.)
1226Visiting a file whose name matches REGEXP specifies FUNCTION as the
1227mode function to use. FUNCTION will be called, unless it is nil.
1228
1229If the element has the form (REGEXP FUNCTION NON-NIL), then after
1230calling FUNCTION (if it's not nil), we delete the suffix that matched
1231REGEXP and search the list again for another match.")
7b3f3dc2 1232
d7fa5aa2 1233(defvar interpreter-mode-alist
c907d156 1234 '(("perl" . perl-mode)
e049945b 1235 ("perl5" . perl-mode)
ebff6b7d 1236 ("miniperl" . perl-mode)
c907d156 1237 ("wish" . tcl-mode)
e3998da1 1238 ("wishx" . tcl-mode)
8db739de 1239 ("tcl" . tcl-mode)
e3998da1 1240 ("tclsh" . tcl-mode)
8db739de 1241 ("awk" . awk-mode)
dfeadd84 1242 ("mawk" . awk-mode)
d4f567a1 1243 ("nawk" . awk-mode)
8db739de 1244 ("gawk" . awk-mode)
d1194c85
RS
1245 ("scm" . scheme-mode)
1246 ("ash" . sh-mode)
1247 ("bash" . sh-mode)
1248 ("csh" . sh-mode)
1249 ("dtksh" . sh-mode)
1250 ("es" . sh-mode)
1251 ("itcsh" . sh-mode)
1252 ("jsh" . sh-mode)
1253 ("ksh" . sh-mode)
1254 ("oash" . sh-mode)
1255 ("pdksh" . sh-mode)
1256 ("rc" . sh-mode)
1257 ("sh" . sh-mode)
1258 ("sh5" . sh-mode)
1259 ("tcsh" . sh-mode)
1260 ("wksh" . sh-mode)
1261 ("wsh" . sh-mode)
1262 ("zsh" . sh-mode)
1263 ("tail" . text-mode)
1264 ("more" . text-mode)
1265 ("less" . text-mode)
1266 ("pg" . text-mode))
c907d156
RS
1267 "Alist mapping interpreter names to major modes.
1268This alist applies to files whose first line starts with `#!'.
1269Each element looks like (INTERPRETER . MODE).
1270The car of each element is compared with
1271the name of the interpreter specified in the first line.
1272If it matches, mode MODE is selected.")
1273
d7fa5aa2 1274(defvar inhibit-first-line-modes-regexps '("\\.tar\\'" "\\.tgz\\'")
45fb3bb8 1275 "List of regexps; if one matches a file name, don't look for `-*-'.")
a0c9f21b 1276
d7fa5aa2 1277(defvar inhibit-first-line-modes-suffixes nil
b20ff6d0
RS
1278 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1279When checking `inhibit-first-line-modes-regexps', we first discard
1280from the end of the file name anything that matches one of these regexps.")
1281
bb157910
RS
1282(defvar user-init-file
1283 "" ; set by command-line
1284 "File name including directory of user's initialization file.")
1285
9de9b6a2 1286(defun set-auto-mode (&optional just-from-file-name)
b4da00e9 1287 "Select major mode appropriate for current buffer.
e3998da1
RS
1288This checks for a -*- mode tag in the buffer's text,
1289compares the filename against the entries in `auto-mode-alist',
1290or checks the interpreter that runs this file against
1291`interpreter-mode-alist'.
1292
1293It does not check for the `mode:' local variable in the
1294Local Variables section of the file; for that, use `hack-local-variables'.
7b3f3dc2 1295
f3e23606 1296If `enable-local-variables' is nil, this function does not check for a
9de9b6a2
RS
1297-*- mode tag.
1298
1299If the optional argument JUST-FROM-FILE-NAME is non-nil,
1300then we do not set anything but the major mode,
1301and we don't even do that unless it would come from the file name."
b4da00e9 1302 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
d0fc03ef 1303 (let (beg end done modes)
b4da00e9
RM
1304 (save-excursion
1305 (goto-char (point-min))
1306 (skip-chars-forward " \t\n")
9fa7bfe5
RS
1307 (and enable-local-variables
1308 ;; Don't look for -*- if this file name matches any
45fb3bb8 1309 ;; of the regexps in inhibit-first-line-modes-regexps.
cae111fa 1310 (let ((temp inhibit-first-line-modes-regexps)
4bc3d240
RS
1311 (name (if buffer-file-name
1312 (file-name-sans-versions buffer-file-name)
1313 (buffer-name))))
38832b4c
KH
1314 (while (let ((sufs inhibit-first-line-modes-suffixes))
1315 (while (and sufs (not (string-match (car sufs) name)))
1316 (setq sufs (cdr sufs)))
1317 sufs)
1318 (setq name (substring name 0 (match-beginning 0))))
9fa7bfe5 1319 (while (and temp
b20ff6d0 1320 (not (string-match (car temp) name)))
9fa7bfe5
RS
1321 (setq temp (cdr temp)))
1322 (not temp))
1323 (search-forward "-*-" (save-excursion
1324 ;; If the file begins with "#!"
1325 ;; (exec interpreter magic), look
1326 ;; for mode frobs in the first two
1327 ;; lines. You cannot necessarily
1328 ;; put them in the first line of
1329 ;; such a file without screwing up
1330 ;; the interpreter invocation.
1331 (end-of-line (and (looking-at "^#!") 2))
1332 (point)) t)
1333 (progn
1334 (skip-chars-forward " \t")
1335 (setq beg (point))
1336 (search-forward "-*-"
1337 (save-excursion (end-of-line) (point))
1338 t))
1339 (progn
1340 (forward-char -3)
1341 (skip-chars-backward " \t")
1342 (setq end (point))
1343 (goto-char beg)
1344 (if (save-excursion (search-forward ":" end t))
1345 ;; Find all specifications for the `mode:' variable
57a0155c 1346 ;; and execute them left to right.
9fa7bfe5 1347 (while (let ((case-fold-search t))
6054fcc6
KH
1348 (or (and (looking-at "mode:")
1349 (goto-char (match-end 0)))
1350 (re-search-forward "[ \t;]mode:" end t)))
9fa7bfe5
RS
1351 (skip-chars-forward " \t")
1352 (setq beg (point))
1353 (if (search-forward ";" end t)
1354 (forward-char -1)
1355 (goto-char end))
1356 (skip-chars-backward " \t")
d0fc03ef
RS
1357 (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1358 modes)))
9fa7bfe5 1359 ;; Simple -*-MODE-*- case.
d0fc03ef
RS
1360 (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
1361 "-mode"))
1362 modes))))))
1363 ;; If we found modes to use, invoke them now,
1364 ;; outside the save-excursion.
83c6f446
RS
1365 (when modes
1366 (unless just-from-file-name
1367 (mapcar 'funcall (nreverse modes)))
1368 (setq done t))
d0fc03ef
RS
1369 ;; If we didn't find a mode from a -*- line, try using the file name.
1370 (if (and (not done) buffer-file-name)
1371 (let ((name buffer-file-name)
1372 (keep-going t))
1373 ;; Remove backup-suffixes from file name.
1374 (setq name (file-name-sans-versions name))
1375 (while keep-going
1376 (setq keep-going nil)
1377 (let ((alist auto-mode-alist)
1378 (mode nil))
1379 ;; Find first matching alist entry.
76d5492b 1380 (let ((case-fold-search
d0fc03ef
RS
1381 (memq system-type '(vax-vms windows-nt))))
1382 (while (and (not mode) alist)
1383 (if (string-match (car (car alist)) name)
1384 (if (and (consp (cdr (car alist)))
1385 (nth 2 (car alist)))
1386 (progn
1387 (setq mode (car (cdr (car alist)))
1388 name (substring name 0 (match-beginning 0))
1389 keep-going t))
1390 (setq mode (cdr (car alist))
1391 keep-going nil)))
1392 (setq alist (cdr alist))))
1393 (if mode
1394 (funcall mode)
1395 ;; If we can't deduce a mode from the file name,
1396 ;; look for an interpreter specified in the first line.
1540e4e9
KH
1397 ;; As a special case, allow for things like "#!/bin/env perl",
1398 ;; which finds the interpreter anywhere in $PATH.
d0fc03ef
RS
1399 (let ((interpreter
1400 (save-excursion
1401 (goto-char (point-min))
dfeadd84 1402 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1540e4e9
KH
1403 (buffer-substring (match-beginning 2)
1404 (match-end 2))
d0fc03ef
RS
1405 "")))
1406 elt)
1407 ;; Map interpreter name to a mode.
1408 (setq elt (assoc (file-name-nondirectory interpreter)
1409 interpreter-mode-alist))
9de9b6a2
RS
1410 (unless just-from-file-name
1411 (if elt
1412 (funcall (cdr elt))))))))))))
b4da00e9 1413
f3e23606
RS
1414(defun hack-local-variables-prop-line ()
1415 ;; Set local variables specified in the -*- line.
3fa0a9aa
KH
1416 ;; Ignore any specification for `mode:' and `coding:';
1417 ;; set-auto-mode should already have handled `mode:',
1418 ;; set-auto-coding should already have handled `coding:'.
f3e23606
RS
1419 (save-excursion
1420 (goto-char (point-min))
13a66180
KH
1421 (let ((result nil)
1422 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
f3e23606
RS
1423 ;; Parse the -*- line into the `result' alist.
1424 (cond ((not (search-forward "-*-" end t))
1425 ;; doesn't have one.
1426 nil)
1427 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
13a66180
KH
1428 ;; Simple form: "-*- MODENAME -*-". Already handled.
1429 nil)
f3e23606
RS
1430 (t
1431 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1432 ;; (last ";" is optional).
1433 (save-excursion
1434 (if (search-forward "-*-" end t)
1435 (setq end (- (point) 3))
1436 (error "-*- not terminated before end of line")))
1437 (while (< (point) end)
1438 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1439 (error "malformed -*- line"))
1440 (goto-char (match-end 0))
1c26a6f3
KH
1441 ;; There used to be a downcase here,
1442 ;; but the manual didn't say so,
1443 ;; and people want to set var names that aren't all lc.
1444 (let ((key (intern (buffer-substring
1445 (match-beginning 1)
1446 (match-end 1))))
f3e23606
RS
1447 (val (save-restriction
1448 (narrow-to-region (point) end)
1449 (read (current-buffer)))))
93a2702d
RS
1450 ;; It is traditional to ignore
1451 ;; case when checking for `mode' in set-auto-mode,
1452 ;; so we must do that here as well.
1453 ;; That is inconsistent, but we're stuck with it.
3fa0a9aa 1454 ;; The same can be said for `coding' in set-auto-coding.
93a2702d 1455 (or (equal (downcase (symbol-name key)) "mode")
3fa0a9aa 1456 (equal (downcase (symbol-name key)) "coding")
13a66180 1457 (setq result (cons (cons key val) result)))
f3e23606
RS
1458 (skip-chars-forward " \t;")))
1459 (setq result (nreverse result))))
76d5492b 1460
f3e23606
RS
1461 (if (and result
1462 (or (eq enable-local-variables t)
1463 (and enable-local-variables
1464 (save-window-excursion
6f931919
RS
1465 (condition-case nil
1466 (switch-to-buffer (current-buffer))
1467 (error
1468 ;; If we fail to switch in the selected window,
1469 ;; it is probably a minibuffer.
1470 ;; So try another window.
1471 (condition-case nil
1472 (switch-to-buffer-other-window (current-buffer))
1473 (error
1474 (switch-to-buffer-other-frame (current-buffer))))))
f3e23606
RS
1475 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1476 (file-name-nondirectory buffer-file-name)))))))
2837b9df
RS
1477 (let ((enable-local-eval enable-local-eval))
1478 (while result
1479 (hack-one-local-variable (car (car result)) (cdr (car result)))
1480 (setq result (cdr result))))))))
f3e23606 1481
1d517019
RS
1482(defvar hack-local-variables-hook nil
1483 "Normal hook run after processing a file's local variables specs.
1484Major modes can use this to examine user-specified local variables
1485in order to initialize other data structure based on them.")
1486
9de9b6a2
RS
1487(defun hack-local-variables (&optional mode-only)
1488 "Parse and put into effect this buffer's local variables spec.
1489If MODE-ONLY is non-nil, all we do is check whether the major mode
1490is specified, returning t if it is specified."
1491 (unless mode-only
1492 (hack-local-variables-prop-line))
b4da00e9 1493 ;; Look for "Local variables:" line in last page.
9de9b6a2
RS
1494 (let (mode-specified)
1495 (save-excursion
1496 (goto-char (point-max))
1497 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1498 (if (let ((case-fold-search t))
1499 (and (search-forward "Local Variables:" nil t)
1500 (or (eq enable-local-variables t)
1501 mode-only
1502 (and enable-local-variables
1503 (save-window-excursion
1504 (switch-to-buffer (current-buffer))
1505 (save-excursion
1506 (beginning-of-line)
1507 (set-window-start (selected-window) (point)))
1508 (y-or-n-p (format "Set local variables as specified at end of %s? "
1509 (if buffer-file-name
1510 (file-name-nondirectory
1511 buffer-file-name)
1512 (concat "buffer "
1513 (buffer-name))))))))))
1514 (let ((continue t)
1515 prefix prefixlen suffix beg
1516 mode-specified
1517 (enable-local-eval enable-local-eval))
1518 ;; The prefix is what comes before "local variables:" in its line.
1519 ;; The suffix is what comes after "local variables:" in its line.
b4da00e9 1520 (skip-chars-forward " \t")
9de9b6a2
RS
1521 (or (eolp)
1522 (setq suffix (buffer-substring (point)
1523 (progn (end-of-line) (point)))))
1524 (goto-char (match-beginning 0))
1525 (or (bolp)
1526 (setq prefix
1527 (buffer-substring (point)
1528 (progn (beginning-of-line) (point)))))
1529
1530 (if prefix (setq prefixlen (length prefix)
1531 prefix (regexp-quote prefix)))
1532 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1533 (while continue
1534 ;; Look at next local variable spec.
1535 (if selective-display (re-search-forward "[\n\C-m]")
1536 (forward-line 1))
1537 ;; Skip the prefix, if any.
1538 (if prefix
1539 (if (looking-at prefix)
1540 (forward-char prefixlen)
1541 (error "Local variables entry is missing the prefix")))
1542 ;; Find the variable name; strip whitespace.
1543 (skip-chars-forward " \t")
1544 (setq beg (point))
1545 (skip-chars-forward "^:\n")
1546 (if (eolp) (error "Missing colon in local variables entry"))
1547 (skip-chars-backward " \t")
1548 (let* ((str (buffer-substring beg (point)))
1549 (var (read str))
1550 val)
1551 ;; Setting variable named "end" means end of list.
1552 (if (string-equal (downcase str) "end")
1553 (setq continue nil)
1554 ;; Otherwise read the variable value.
1555 (skip-chars-forward "^:")
1556 (forward-char 1)
1557 (setq val (read (current-buffer)))
1558 (skip-chars-backward "\n")
1559 (skip-chars-forward " \t")
1560 (or (if suffix (looking-at suffix) (eolp))
1561 (error "Local variables entry is terminated incorrectly"))
1562 (if mode-only
1563 (if (eq var 'mode)
1564 (setq mode-specified t))
1565 ;; Set the variable. "Variables" mode and eval are funny.
1566 (hack-one-local-variable var val))))))))
1567 (unless mode-only
1568 (run-hooks 'hack-local-variables-hook))
1569 mode-specified))
f3e23606 1570
d7fa5aa2 1571(defvar ignored-local-variables
f3e23606
RS
1572 '(enable-local-eval)
1573 "Variables to be ignored in a file's local variable spec.")
1574
be0218a8 1575;; Get confirmation before setting these variables as locals in a file.
05ef1cda 1576(put 'debugger 'risky-local-variable t)
f6fa3ee3 1577(put 'enable-local-eval 'risky-local-variable t)
fce47eea 1578(put 'ignored-local-variables 'risky-local-variable t)
be0218a8
RS
1579(put 'eval 'risky-local-variable t)
1580(put 'file-name-handler-alist 'risky-local-variable t)
1581(put 'minor-mode-map-alist 'risky-local-variable t)
1582(put 'after-load-alist 'risky-local-variable t)
f6fa3ee3
RS
1583(put 'buffer-file-name 'risky-local-variable t)
1584(put 'buffer-auto-save-file-name 'risky-local-variable t)
1585(put 'buffer-file-truename 'risky-local-variable t)
b0ffcc0d
RS
1586(put 'exec-path 'risky-local-variable t)
1587(put 'load-path 'risky-local-variable t)
1588(put 'exec-directory 'risky-local-variable t)
1589(put 'process-environment 'risky-local-variable t)
eba1c87a
RS
1590(put 'dabbrev-case-fold-search 'risky-local-variable t)
1591(put 'dabbrev-case-replace 'risky-local-variable t)
9afa8bf7
RS
1592;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1593(put 'outline-level 'risky-local-variable t)
d98b741d 1594(put 'rmail-output-file-alist 'risky-local-variable t)
f6fa3ee3 1595
6672c42b
RS
1596;; This one is safe because the user gets to check it before it is used.
1597(put 'compile-command 'safe-local-variable t)
1598
d0bd3513
RS
1599(defun hack-one-local-variable-quotep (exp)
1600 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1601
f3e23606
RS
1602;; "Set" one variable in a local variables spec.
1603;; A few variable names are treated specially.
1604(defun hack-one-local-variable (var val)
1605 (cond ((eq var 'mode)
1606 (funcall (intern (concat (downcase (symbol-name val))
1607 "-mode"))))
3fa0a9aa
KH
1608 ((eq var 'coding)
1609 ;; We have already handled coding: tag in set-auto-coding.
1610 nil)
f3e23606
RS
1611 ((memq var ignored-local-variables)
1612 nil)
1613 ;; "Setting" eval means either eval it or do nothing.
7d3221d7 1614 ;; Likewise for setting hook variables.
be0218a8 1615 ((or (get var 'risky-local-variable)
6672c42b
RS
1616 (and
1617 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
1618 (symbol-name var))
1619 (not (get var 'safe-local-variable))))
0225ae5e 1620 ;; Permit evalling a put of a harmless property.
d0bd3513
RS
1621 ;; if the args do nothing tricky.
1622 (if (or (and (eq var 'eval)
1623 (consp val)
1624 (eq (car val) 'put)
1625 (hack-one-local-variable-quotep (nth 1 val))
1626 (hack-one-local-variable-quotep (nth 2 val))
1627 ;; Only allow safe values of lisp-indent-hook;
1628 ;; not functions.
1629 (or (numberp (nth 3 val))
dc417415 1630 (equal (nth 3 val) ''defun))
d0bd3513
RS
1631 (memq (nth 1 (nth 2 val))
1632 '(lisp-indent-hook)))
1633 ;; Permit eval if not root and user says ok.
c7e62660 1634 (and (not (zerop (user-uid)))
d0bd3513
RS
1635 (or (eq enable-local-eval t)
1636 (and enable-local-eval
1637 (save-window-excursion
1638 (switch-to-buffer (current-buffer))
1639 (save-excursion
1640 (beginning-of-line)
1641 (set-window-start (selected-window) (point)))
1642 (setq enable-local-eval
1643 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1644 (file-name-nondirectory buffer-file-name)))))))))
7d3221d7
RS
1645 (if (eq var 'eval)
1646 (save-excursion (eval val))
1647 (make-local-variable var)
1648 (set var val))
f3e23606
RS
1649 (message "Ignoring `eval:' in file's local variables")))
1650 ;; Ordinary variable, really set it.
1651 (t (make-local-variable var)
1652 (set var val))))
1653
b4da00e9 1654\f
21540597 1655(defcustom change-major-mode-with-file-name t
9de9b6a2
RS
1656 "*Non-nil means \\[write-file] should set the major mode from the file name.
1657However, the mode will not be changed if
1658\(1) a local variables list or the `-*-' line specifies a major mode, or
1659\(2) the current major mode is a \"special\" mode,
8609911b 1660\ not suitable for ordinary files, or
21540597
RS
1661\(3) the new file name does not particularly specify any mode."
1662 :type 'boolean
1663 :group 'editing-basics)
9de9b6a2 1664
f36012a6 1665(defun set-visited-file-name (filename &optional no-query along-with-file)
b4da00e9
RM
1666 "Change name of file visited in current buffer to FILENAME.
1667The next time the buffer is saved it will go in the newly specified file.
1668nil or empty string as argument means make buffer not be visiting any file.
1669Remember to delete the initial contents of the minibuffer
6a6b62f8
RS
1670if you wish to pass an empty string as the argument.
1671
1672The optional second argument NO-QUERY, if non-nil, inhibits asking for
f36012a6
RS
1673confirmation in the case where another buffer is already visiting FILENAME.
1674
1675The optional third argument ALONG-WITH-FILE, if non-nil, means that
1676the old visited file has been renamed to the new name FILENAME."
b4da00e9 1677 (interactive "FSet visited file name: ")
c11a94fe
RS
1678 (if (buffer-base-buffer)
1679 (error "An indirect buffer cannot visit a file"))
a522e5bf
RS
1680 (let (truename)
1681 (if filename
1682 (setq filename
1683 (if (string-equal filename "")
1684 nil
1685 (expand-file-name filename))))
1686 (if filename
1687 (progn
1688 (setq truename (file-truename filename))
1689 (if find-file-visit-truename
a522e5bf 1690 (setq filename truename))))
11e314fa 1691 (let ((buffer (and filename (find-buffer-visiting filename))))
7b89d38e 1692 (and buffer (not (eq buffer (current-buffer)))
6a6b62f8 1693 (not no-query)
7b89d38e
RS
1694 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1695 filename)))
1696 (error "Aborted")))
a522e5bf
RS
1697 (or (equal filename buffer-file-name)
1698 (progn
1699 (and filename (lock-buffer filename))
1700 (unlock-buffer)))
1701 (setq buffer-file-name filename)
1702 (if filename ; make buffer name reflect filename.
1703 (let ((new-name (file-name-nondirectory buffer-file-name)))
1704 (if (string= new-name "")
1705 (error "Empty file name"))
1706 (if (eq system-type 'vax-vms)
1707 (setq new-name (downcase new-name)))
1708 (setq default-directory (file-name-directory buffer-file-name))
1709 (or (string= new-name (buffer-name))
1710 (rename-buffer new-name t))))
1711 (setq buffer-backed-up nil)
f36012a6
RS
1712 (or along-with-file
1713 (clear-visited-file-modtime))
8ccdc29e 1714 ;; Abbreviate the file names of the buffer.
4826e97f 1715 (if truename
8ccdc29e
RS
1716 (progn
1717 (setq buffer-file-truename (abbreviate-file-name truename))
1718 (if find-file-visit-truename
1719 (setq buffer-file-name buffer-file-truename))))
a522e5bf
RS
1720 (setq buffer-file-number
1721 (if filename
2a47b4f5 1722 (nthcdr 10 (file-attributes buffer-file-name))
a522e5bf 1723 nil)))
b4da00e9
RM
1724 ;; write-file-hooks is normally used for things like ftp-find-file
1725 ;; that visit things that are not local files as if they were files.
1726 ;; Changing to visit an ordinary local file instead should flush the hook.
1727 (kill-local-variable 'write-file-hooks)
c9dca4e0 1728 (kill-local-variable 'local-write-file-hooks)
b4da00e9
RM
1729 (kill-local-variable 'revert-buffer-function)
1730 (kill-local-variable 'backup-inhibited)
ee81c959
RS
1731 ;; If buffer was read-only because of version control,
1732 ;; that reason is gone now, so make it writable.
1733 (if vc-mode
1734 (setq buffer-read-only nil))
1735 (kill-local-variable 'vc-mode)
b4da00e9
RM
1736 ;; Turn off backup files for certain file names.
1737 ;; Since this is a permanent local, the major mode won't eliminate it.
1738 (and (not (funcall backup-enable-predicate buffer-file-name))
1739 (progn
1740 (make-local-variable 'backup-inhibited)
1741 (setq backup-inhibited t)))
c77a81cf
RS
1742 (let ((oauto buffer-auto-save-file-name))
1743 ;; If auto-save was not already on, turn it on if appropriate.
1744 (if (not buffer-auto-save-file-name)
1745 (and buffer-file-name auto-save-default
1746 (auto-save-mode t))
1747 ;; If auto save is on, start using a new name.
1748 ;; We deliberately don't rename or delete the old auto save
1749 ;; for the old visited file name. This is because perhaps
1750 ;; the user wants to save the new state and then compare with the
1751 ;; previous state from the auto save file.
1752 (setq buffer-auto-save-file-name
1753 (make-auto-save-file-name)))
1754 ;; Rename the old auto save file if any.
1755 (and oauto buffer-auto-save-file-name
e6f0e76c 1756 (file-exists-p oauto)
c77a81cf 1757 (rename-file oauto buffer-auto-save-file-name t)))
f36012a6
RS
1758 (and buffer-file-name
1759 (not along-with-file)
9de9b6a2
RS
1760 (set-buffer-modified-p t))
1761 ;; Update the major mode, if the file name determines it.
1762 (condition-case nil
1763 ;; Don't change the mode if it is special.
1764 (or (not change-major-mode-with-file-name)
1765 (get major-mode 'mode-class)
1766 ;; Don't change the mode if the local variable list specifies it.
1767 (hack-local-variables t)
1768 (set-auto-mode t))
1769 (error nil)))
b4da00e9 1770
912192d1 1771(defun write-file (filename &optional confirm)
b4da00e9 1772 "Write current buffer into file FILENAME.
41f48cb1
RS
1773Makes buffer visit that file, and marks it not modified.
1774If the buffer is already visiting a file, you can specify
1775a directory name as FILENAME, to write a file of the same
c2fb8488 1776old name in that directory.
7458cc35 1777
c2fb8488 1778If optional second arg CONFIRM is non-nil,
7458cc35 1779ask for confirmation for overwriting an existing file.
912192d1 1780Interactively, confirmation is required unless you supply a prefix argument."
b4da00e9
RM
1781;; (interactive "FWrite file: ")
1782 (interactive
1783 (list (if buffer-file-name
1784 (read-file-name "Write file: "
1785 nil nil nil nil)
1786 (read-file-name "Write file: "
1787 (cdr (assq 'default-directory
1788 (buffer-local-variables)))
c2fb8488 1789 nil nil (buffer-name)))
912192d1 1790 (not current-prefix-arg)))
b4da00e9 1791 (or (null filename) (string-equal filename "")
41f48cb1
RS
1792 (progn
1793 ;; If arg is just a directory,
1794 ;; use same file name, but in that directory.
1795 (if (and (file-directory-p filename) buffer-file-name)
1796 (setq filename (concat (file-name-as-directory filename)
1797 (file-name-nondirectory buffer-file-name))))
c2fb8488
RS
1798 (and confirm
1799 (file-exists-p filename)
1800 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1801 (error "Canceled")))
5f65549e 1802 (set-visited-file-name filename (not confirm))))
b4da00e9 1803 (set-buffer-modified-p t)
6492b55d
KH
1804 ;; Make buffer writable if file is writable.
1805 (and buffer-file-name
1806 (file-writable-p buffer-file-name)
1807 (setq buffer-read-only nil))
912192d1 1808 (save-buffer))
b4da00e9
RM
1809\f
1810(defun backup-buffer ()
1811 "Make a backup of the disk file visited by the current buffer, if appropriate.
1812This is normally done before saving the buffer the first time.
1813If the value is non-nil, it is the result of `file-modes' on the original
1814file; this means that the caller, after saving the buffer, should change
27ab6944
KH
1815the modes of the new file to agree with the old modes.
1816
1817A backup may be done by renaming or by copying; see documentation of
1818variable `make-backup-files'. If it's done by renaming, then the file is
1819no longer accessible under its old name."
b4da00e9
RM
1820 (if (and make-backup-files (not backup-inhibited)
1821 (not buffer-backed-up)
1822 (file-exists-p buffer-file-name)
1823 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1824 '(?- ?l)))
1825 (let ((real-file-name buffer-file-name)
1826 backup-info backupname targets setmodes)
1827 ;; If specified name is a symbolic link, chase it to the target.
1828 ;; Thus we make the backups in the directory where the real file is.
5dadeb29 1829 (setq real-file-name (file-chase-links real-file-name))
b4da00e9
RM
1830 (setq backup-info (find-backup-file-name real-file-name)
1831 backupname (car backup-info)
1832 targets (cdr backup-info))
1833;;; (if (file-directory-p buffer-file-name)
1834;;; (error "Cannot save buffer in directory %s" buffer-file-name))
eb650569
RS
1835 (if backup-info
1836 (condition-case ()
1837 (let ((delete-old-versions
1838 ;; If have old versions to maybe delete,
1839 ;; ask the user to confirm now, before doing anything.
1840 ;; But don't actually delete til later.
1841 (and targets
1842 (or (eq delete-old-versions t) (eq delete-old-versions nil))
1843 (or delete-old-versions
1844 (y-or-n-p (format "Delete excess backup versions of %s? "
1845 real-file-name))))))
1846 ;; Actually write the back up file.
1847 (condition-case ()
1848 (if (or file-precious-flag
1849 ; (file-symlink-p buffer-file-name)
1850 backup-by-copying
1851 (and backup-by-copying-when-linked
1852 (> (file-nlinks real-file-name) 1))
1853 (and backup-by-copying-when-mismatch
1854 (let ((attr (file-attributes real-file-name)))
1855 (or (nth 9 attr)
1856 (not (file-ownership-preserved-p real-file-name))))))
1857 (condition-case ()
1858 (copy-file real-file-name backupname t t)
1859 (file-error
1860 ;; If copying fails because file BACKUPNAME
1861 ;; is not writable, delete that file and try again.
1862 (if (and (file-exists-p backupname)
1863 (not (file-writable-p backupname)))
1864 (delete-file backupname))
1865 (copy-file real-file-name backupname t t)))
1866 ;; rename-file should delete old backup.
1867 (rename-file real-file-name backupname t)
1868 (setq setmodes (file-modes backupname)))
1869 (file-error
1870 ;; If trouble writing the backup, write it in ~.
567c1ca9
RS
1871 (setq backupname (expand-file-name
1872 (convert-standard-filename
1873 "~/%backup%~")))
1874 (message "Cannot write backup file; backing up in %s"
1875 (file-name-nondirectory backupname))
eb650569
RS
1876 (sleep-for 1)
1877 (condition-case ()
1878 (copy-file real-file-name backupname t t)
1879 (file-error
1880 ;; If copying fails because file BACKUPNAME
1881 ;; is not writable, delete that file and try again.
1882 (if (and (file-exists-p backupname)
1883 (not (file-writable-p backupname)))
1884 (delete-file backupname))
1885 (copy-file real-file-name backupname t t)))))
1886 (setq buffer-backed-up t)
1887 ;; Now delete the old versions, if desired.
1888 (if delete-old-versions
1889 (while targets
1890 (condition-case ()
1891 (delete-file (car targets))
1892 (file-error nil))
1893 (setq targets (cdr targets))))
1894 setmodes)
1895 (file-error nil))))))
b4da00e9 1896
c3554e95 1897(defun file-name-sans-versions (name &optional keep-backup-version)
b4da00e9
RM
1898 "Return FILENAME sans backup versions or strings.
1899This is a separate procedure so your site-init or startup file can
c3554e95
RS
1900redefine it.
1901If the optional argument KEEP-BACKUP-VERSION is non-nil,
1902we do not remove backup version numbers, only true file version numbers."
6eaebaa2 1903 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
c3554e95
RS
1904 (if handler
1905 (funcall handler 'file-name-sans-versions name keep-backup-version)
1906 (substring name 0
1907 (if (eq system-type 'vax-vms)
1908 ;; VMS version number is (a) semicolon, optional
1909 ;; sign, zero or more digits or (b) period, option
1910 ;; sign, zero or more digits, provided this is the
1911 ;; second period encountered outside of the
1912 ;; device/directory part of the file name.
26add1bf
KH
1913 (or (string-match ";[-+]?[0-9]*\\'" name)
1914 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
c3554e95
RS
1915 name)
1916 (match-beginning 1))
1917 (length name))
1918 (if keep-backup-version
1919 (length name)
dbb12f2c 1920 (or (string-match "\\.~[0-9.]+~\\'" name)
c3554e95
RS
1921 (string-match "~\\'" name)
1922 (length name))))))))
b4da00e9 1923
cb0cd911
RS
1924(defun file-ownership-preserved-p (file)
1925 "Returns t if deleting FILE and rewriting it would preserve the owner."
1926 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1927 (if handler
1928 (funcall handler 'file-ownership-preserved-p file)
ec5533be 1929 (let ((attributes (file-attributes file)))
306faa42
RS
1930 ;; Return t if the file doesn't exist, since it's true that no
1931 ;; information would be lost by an (attempted) delete and create.
1932 (or (null attributes)
1933 (= (nth 2 attributes) (user-uid)))))))
cb0cd911 1934
20b5d24c
RS
1935(defun file-name-sans-extension (filename)
1936 "Return FILENAME sans final \"extension\".
1937The extension, in a file name, is the part that follows the last `.'."
1938 (save-match-data
1939 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1940 directory)
1941 (if (string-match "\\.[^.]*\\'" file)
1942 (if (setq directory (file-name-directory filename))
1943 (expand-file-name (substring file 0 (match-beginning 0))
1944 directory)
1945 (substring file 0 (match-beginning 0)))
1946 filename))))
1947
93a2702d
RS
1948(defun file-name-extension (filename &optional period)
1949 "Return FILENAME's final \"extension\".
1950The extension, in a file name, is the part that follows the last `.'.
1951Return nil for extensionless file names such as `foo'.
1952Return the empty string for file names such as `foo.'.
1953
1954If PERIOD is non-nil, then the returned value includes the period
1955that delimits the extension, and if FILENAME has no extension,
1956the value is \"\"."
1957 (save-match-data
1958 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
1959 (if (string-match "\\.[^.]*\\'" file)
1960 (substring file (+ (match-beginning 0) (if period 0 1)))
1961 (if period
1962 "")))))
1963
b4da00e9
RM
1964(defun make-backup-file-name (file)
1965 "Create the non-numeric backup file name for FILE.
1966This is a separate function so you can redefine it for customization."
28ee503c
KH
1967 (if (and (eq system-type 'ms-dos)
1968 (not (msdos-long-file-names)))
bb157910
RS
1969 (let ((fn (file-name-nondirectory file)))
1970 (concat (file-name-directory file)
066327ae
KH
1971 (or
1972 (and (string-match "\\`[^.]+\\'" fn)
1973 (concat (match-string 0 fn) ".~"))
1974 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
1975 (concat (match-string 0 fn) "~")))))
bb157910 1976 (concat file "~")))
b4da00e9
RM
1977
1978(defun backup-file-name-p (file)
1979 "Return non-nil if FILE is a backup file name (numeric or not).
1980This is a separate function so you can redefine it for customization.
1981You may need to redefine `file-name-sans-versions' as well."
066327ae 1982 (string-match "~\\'" file))
b4da00e9 1983
e2b30772
RS
1984(defvar backup-extract-version-start)
1985
2d051399
RS
1986;; This is used in various files.
1987;; The usage of bv-length is not very clean,
1988;; but I can't see a good alternative,
1989;; so as of now I am leaving it alone.
1990(defun backup-extract-version (fn)
1991 "Given the name of a numeric backup file, return the backup number.
e2b30772 1992Uses the free variable `backup-extract-version-start', whose value should be
2d051399 1993the index in the name where the version number begins."
e2b30772
RS
1994 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start)
1995 (= (match-beginning 0) backup-extract-version-start))
1996 (string-to-int (substring fn backup-extract-version-start -1))
2d051399
RS
1997 0))
1998
b4da00e9
RM
1999;; I believe there is no need to alter this behavior for VMS;
2000;; since backup files are not made on VMS, it should not get called.
2001(defun find-backup-file-name (fn)
2002 "Find a file name for a backup file, and suggestions for deletions.
2003Value is a list whose car is the name for the backup file
eb650569
RS
2004 and whose cdr is a list of old versions to consider deleting now.
2005If the value is nil, don't make a backup."
2006 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
2007 ;; Run a handler for this function so that ange-ftp can refuse to do it.
2008 (if handler
2009 (funcall handler 'find-backup-file-name fn)
2010 (if (eq version-control 'never)
b4da00e9 2011 (list (make-backup-file-name fn))
eb650569 2012 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
e2b30772 2013 (backup-extract-version-start (length base-versions))
eb650569
RS
2014 possibilities
2015 (versions nil)
2016 (high-water-mark 0)
2017 (deserve-versions-p nil)
2018 (number-to-delete 0))
2019 (condition-case ()
2020 (setq possibilities (file-name-all-completions
2021 base-versions
2022 (file-name-directory fn))
2023 versions (sort (mapcar
2024 (function backup-extract-version)
2025 possibilities)
2026 '<)
2027 high-water-mark (apply 'max 0 versions)
2028 deserve-versions-p (or version-control
2029 (> high-water-mark 0))
2030 number-to-delete (- (length versions)
2031 kept-old-versions kept-new-versions -1))
2032 (file-error
2033 (setq possibilities nil)))
2034 (if (not deserve-versions-p)
2035 (list (make-backup-file-name fn))
2036 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
2037 (if (and (> number-to-delete 0)
2038 ;; Delete nothing if there is overflow
2039 ;; in the number of versions to keep.
2040 (>= (+ kept-new-versions kept-old-versions -1) 0))
2041 (mapcar (function (lambda (n)
2042 (concat fn ".~" (int-to-string n) "~")))
2043 (let ((v (nthcdr kept-old-versions versions)))
2044 (rplacd (nthcdr (1- number-to-delete) v) ())
2045 v))))))))))
b4da00e9 2046
b4da00e9
RM
2047(defun file-nlinks (filename)
2048 "Return number of names file FILENAME has."
2049 (car (cdr (file-attributes filename))))
6c636af9
RM
2050
2051(defun file-relative-name (filename &optional directory)
2d6562a5
RS
2052 "Convert FILENAME to be relative to DIRECTORY (default: default-directory).
2053This function returns a relative file name which is equivalent to FILENAME
2054when used with that default directory as the default.
2055If this is impossible (which can happen on MSDOS and Windows
2056when the file name and directory use different drive names)
2057then it returns FILENAME."
96c188b0 2058 (save-match-data
e2b30772
RS
2059 (let ((fname (expand-file-name filename)))
2060 (setq directory (file-name-as-directory
2061 (expand-file-name (or directory default-directory))))
2062 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2063 ;; drive names, they can't be relative, so return the absolute name.
2064 (if (and (or (eq system-type 'ms-dos)
2065 (eq system-type 'windows-nt))
2066 (not (string-equal (substring fname 0 2)
2067 (substring directory 0 2))))
2068 filename
9695aac6
RS
2069 (let ((ancestor ".")
2070 (fname-dir (file-name-as-directory fname)))
2071 (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
2072 (not (string-match (concat "^" (regexp-quote directory)) fname)))
e2b30772 2073 (setq directory (file-name-directory (substring directory 0 -1))
9695aac6
RS
2074 ancestor (if (equal ancestor ".")
2075 ".."
2076 (concat "../" ancestor))))
2077 ;; Now ancestor is empty, or .., or ../.., etc.
2078 (if (string-match (concat "^" (regexp-quote directory)) fname)
2079 ;; We matched within FNAME's directory part.
2080 ;; Add the rest of FNAME onto ANCESTOR.
2081 (let ((rest (substring fname (match-end 0))))
2082 (if (and (equal ancestor ".")
2083 (not (equal rest "")))
2084 ;; But don't bother with ANCESTOR if it would give us `./'.
2085 rest
2086 (concat (file-name-as-directory ancestor) rest)))
2087 ;; We matched FNAME's directory equivalent.
2088 ancestor))))))
b4da00e9
RM
2089\f
2090(defun save-buffer (&optional args)
2091 "Save current buffer in visited file if modified. Versions described below.
2092By default, makes the previous version into a backup file
2093 if previously requested or if this is the first save.
ac9650be 2094With 1 \\[universal-argument], marks this version
b4da00e9 2095 to become a backup when the next save is done.
ac9650be 2096With 2 \\[universal-argument]'s,
b4da00e9 2097 unconditionally makes the previous version into a backup file.
ac9650be
RS
2098With 3 \\[universal-argument]'s, marks this version
2099 to become a backup when the next save is done,
2100 and unconditionally makes the previous version into a backup file.
2101
b4da00e9
RM
2102With argument of 0, never makes the previous version into a backup file.
2103
2104If a file's name is FOO, the names of its numbered backup versions are
2105 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2106Numeric backups (rather than FOO~) will be made if value of
2107 `version-control' is not the atom `never' and either there are already
2108 numeric versions of the file being backed up, or `version-control' is
2109 non-nil.
2110We don't want excessive versions piling up, so there are variables
2111 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2112 and `kept-new-versions', which tells how many newest versions to keep.
2113 Defaults are 2 old versions and 2 new.
2114`dired-kept-versions' controls dired's clean-directory (.) command.
de7d5e1b 2115If `delete-old-versions' is nil, system will query user
b4da00e9
RM
2116 before trimming versions. Otherwise it does it silently."
2117 (interactive "p")
2118 (let ((modp (buffer-modified-p))
2119 (large (> (buffer-size) 50000))
b5a8e0fc
RS
2120 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2121 (memq args '(16 64)))))
b4da00e9
RM
2122 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2123 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
2124 (basic-save-buffer)
2125 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2126
2127(defun delete-auto-save-file-if-necessary (&optional force)
2128 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2129Normally delete only if the file was written by this Emacs since
2130the last real save, but optional arg FORCE non-nil means delete anyway."
2131 (and buffer-auto-save-file-name delete-auto-save-files
2132 (not (string= buffer-file-name buffer-auto-save-file-name))
2133 (or force (recent-auto-save-p))
2134 (progn
2135 (condition-case ()
2136 (delete-file buffer-auto-save-file-name)
2137 (file-error nil))
2138 (set-buffer-auto-saved))))
2139
1cc852cc
RS
2140(defvar after-save-hook nil
2141 "Normal hook that is run after a buffer is saved to its file.")
2142
b4da00e9 2143(defun basic-save-buffer ()
1cc852cc
RS
2144 "Save the current buffer in its visited file, if it has been modified.
2145After saving the buffer, run `after-save-hook'."
b4da00e9 2146 (interactive)
c11a94fe
RS
2147 (save-excursion
2148 ;; In an indirect buffer, save its base buffer instead.
2149 (if (buffer-base-buffer)
2150 (set-buffer (buffer-base-buffer)))
2151 (if (buffer-modified-p)
2152 (let ((recent-save (recent-auto-save-p))
2153 setmodes tempsetmodes)
2154 ;; On VMS, rename file and buffer to get rid of version number.
2155 (if (and (eq system-type 'vax-vms)
2156 (not (string= buffer-file-name
2157 (file-name-sans-versions buffer-file-name))))
2158 (let (buffer-new-name)
2159 ;; Strip VMS version number before save.
2160 (setq buffer-file-name
2161 (file-name-sans-versions buffer-file-name))
2162 ;; Construct a (unique) buffer name to correspond.
2163 (let ((buf (create-file-buffer (downcase buffer-file-name))))
2164 (setq buffer-new-name (buffer-name buf))
2165 (kill-buffer buf))
2166 (rename-buffer buffer-new-name)))
2167 ;; If buffer has no file name, ask user for one.
2168 (or buffer-file-name
182891ef
RS
2169 (let ((filename
2170 (expand-file-name
2171 (read-file-name "File to save in: ") nil)))
2172 (and (file-exists-p filename)
2173 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2174 filename))
2175 (error "Canceled")))
2176 (set-visited-file-name filename)))
c11a94fe
RS
2177 (or (verify-visited-file-modtime (current-buffer))
2178 (not (file-exists-p buffer-file-name))
2179 (yes-or-no-p
2180 (format "%s has changed since visited or saved. Save anyway? "
2181 (file-name-nondirectory buffer-file-name)))
2182 (error "Save not confirmed"))
2183 (save-restriction
2184 (widen)
2185 (and (> (point-max) 1)
2186 (/= (char-after (1- (point-max))) ?\n)
2187 (not (and (eq selective-display t)
2188 (= (char-after (1- (point-max))) ?\r)))
2189 (or (eq require-final-newline t)
2190 (and require-final-newline
2191 (y-or-n-p
2192 (format "Buffer %s does not end in newline. Add one? "
2193 (buffer-name)))))
2194 (save-excursion
2195 (goto-char (point-max))
2196 (insert ?\n)))
2197 (or (run-hook-with-args-until-success 'write-contents-hooks)
2198 (run-hook-with-args-until-success 'local-write-file-hooks)
2199 (run-hook-with-args-until-success 'write-file-hooks)
2200 ;; If a hook returned t, file is already "written".
2201 ;; Otherwise, write it the usual way now.
2202 (setq setmodes (basic-save-buffer-1)))
d6e8ea6f
KH
2203 ;; Now we have saved the current buffer. Let's make sure
2204 ;; that buffer-file-coding-system is fixed to what
2205 ;; actually used for saving by binding it locally.
2206 (setq buffer-file-coding-system last-coding-system-used)
2a47b4f5
RS
2207 (setq buffer-file-number
2208 (nthcdr 10 (file-attributes buffer-file-name)))
c11a94fe
RS
2209 (if setmodes
2210 (condition-case ()
2211 (set-file-modes buffer-file-name setmodes)
2212 (error nil))))
2213 ;; If the auto-save file was recent before this command,
2214 ;; delete it now.
2215 (delete-auto-save-file-if-necessary recent-save)
49530862
RS
2216 ;; Support VC `implicit' locking.
2217 (vc-after-save)
c11a94fe
RS
2218 (run-hooks 'after-save-hook))
2219 (message "(No changes need to be saved)"))))
b4da00e9 2220
87d26afc
RS
2221;; This does the "real job" of writing a buffer into its visited file
2222;; and making a backup file. This is what is normally done
2223;; but inhibited if one of write-file-hooks returns non-nil.
2224;; It returns a value to store in setmodes.
2225(defun basic-save-buffer-1 ()
2226 (let (tempsetmodes setmodes)
2227 (if (not (file-writable-p buffer-file-name))
2228 (let ((dir (file-name-directory buffer-file-name)))
2229 (if (not (file-directory-p dir))
83c6f446
RS
2230 (if (file-exists-p dir)
2231 (error "%s is not a directory" dir)
cb2fdcfa 2232 (error "%s: no such directory" buffer-file-name))
87d26afc
RS
2233 (if (not (file-exists-p buffer-file-name))
2234 (error "Directory %s write-protected" dir)
2235 (if (yes-or-no-p
2236 (format "File %s is write-protected; try to save anyway? "
2237 (file-name-nondirectory
2238 buffer-file-name)))
2239 (setq tempsetmodes t)
2240 (error "Attempt to save to a file which you aren't allowed to write"))))))
2241 (or buffer-backed-up
2242 (setq setmodes (backup-buffer)))
76d5492b 2243 (let ((dir (file-name-directory buffer-file-name)))
f4a0f59b
RS
2244 (if (and file-precious-flag
2245 (file-writable-p dir))
2246 ;; If file is precious, write temp name, then rename it.
2247 ;; This requires write access to the containing dir,
2248 ;; which is why we don't try it if we don't have that access.
2249 (let ((realname buffer-file-name)
6782610c
RS
2250 tempname temp nogood i succeed
2251 (old-modtime (visited-file-modtime)))
f4a0f59b
RS
2252 (setq i 0)
2253 (setq nogood t)
2254 ;; Find the temporary name to write under.
2255 (while nogood
567c1ca9 2256 (setq tempname (format
28ee503c
KH
2257 (if (and (eq system-type 'ms-dos)
2258 (not (msdos-long-file-names)))
567c1ca9
RS
2259 "%s#%d.tm#" ; MSDOS limits files to 8+3
2260 "%s#tmp#%d")
2261 dir i))
f4a0f59b
RS
2262 (setq nogood (file-exists-p tempname))
2263 (setq i (1+ i)))
2264 (unwind-protect
2265 (progn (clear-visited-file-modtime)
2266 (write-region (point-min) (point-max)
89095962
RS
2267 tempname nil realname
2268 buffer-file-truename)
f4a0f59b
RS
2269 (setq succeed t))
2270 ;; If writing the temp file fails,
2271 ;; delete the temp file.
76d5492b 2272 (or succeed
6782610c
RS
2273 (progn
2274 (delete-file tempname)
2275 (set-visited-file-modtime old-modtime))))
f4a0f59b
RS
2276 ;; Since we have created an entirely new file
2277 ;; and renamed it, make sure it gets the
2278 ;; right permission bits set.
2279 (setq setmodes (file-modes buffer-file-name))
2280 ;; We succeeded in writing the temp file,
2281 ;; so rename it.
2282 (rename-file tempname buffer-file-name t))
2283 ;; If file not writable, see if we can make it writable
2284 ;; temporarily while we write it.
2285 ;; But no need to do so if we have just backed it up
2286 ;; (setmodes is set) because that says we're superseding.
2287 (cond ((and tempsetmodes (not setmodes))
2288 ;; Change the mode back, after writing.
2289 (setq setmodes (file-modes buffer-file-name))
2290 (set-file-modes buffer-file-name 511)))
2291 (write-region (point-min) (point-max)
89095962 2292 buffer-file-name nil t buffer-file-truename)))
87d26afc
RS
2293 setmodes))
2294
b4da00e9
RM
2295(defun save-some-buffers (&optional arg exiting)
2296 "Save some modified file-visiting buffers. Asks user about each one.
5bbbceb1
JB
2297Optional argument (the prefix) non-nil means save all with no questions.
2298Optional second argument EXITING means ask about certain non-file buffers
2299 as well as about file buffers."
b4da00e9 2300 (interactive "P")
907482b9 2301 (save-window-excursion
76d5492b
RM
2302 (let* ((queried nil)
2303 (files-done
2304 (map-y-or-n-p
2305 (function
2306 (lambda (buffer)
2307 (and (buffer-modified-p buffer)
2308 (not (buffer-base-buffer buffer))
2309 (or
2310 (buffer-file-name buffer)
2311 (and exiting
2312 (progn
2313 (set-buffer buffer)
2314 (and buffer-offer-save (> (buffer-size) 0)))))
2315 (if arg
2316 t
2317 (setq queried t)
2318 (if (buffer-file-name buffer)
2319 (format "Save file %s? "
2320 (buffer-file-name buffer))
2321 (format "Save buffer %s? "
2322 (buffer-name buffer)))))))
2323 (function
2324 (lambda (buffer)
2325 (set-buffer buffer)
2326 (save-buffer)))
2327 (buffer-list)
2328 '("buffer" "buffers" "save")
2329 (list (list ?\C-r (lambda (buf)
2a9fe1e2
RS
2330 (view-buffer buf
2331 (function
2332 (lambda (ignore)
2333 (exit-recursive-edit))))
76d5492b
RM
2334 (recursive-edit)
2335 ;; Return nil to ask about BUF again.
2336 nil)
2337 "display the current buffer"))))
2338 (abbrevs-done
2339 (and save-abbrevs abbrevs-changed
2340 (progn
2341 (if (or arg
2342 (y-or-n-p (format "Save abbrevs in %s? "
2343 abbrev-file-name)))
2344 (write-abbrev-file nil))
2345 ;; Don't keep bothering user if he says no.
2346 (setq abbrevs-changed nil)
2347 t))))
2348 (or queried (> files-done 0) abbrevs-done
5625c2fc 2349 (message "(No files need saving)")))))
b4da00e9
RM
2350\f
2351(defun not-modified (&optional arg)
2352 "Mark current buffer as unmodified, not needing to be saved.
a641f9a1
RM
2353With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2354
2355It is not a good idea to use this function in Lisp programs, because it
2356prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
b4da00e9
RM
2357 (interactive "P")
2358 (message (if arg "Modification-flag set"
2359 "Modification-flag cleared"))
2360 (set-buffer-modified-p arg))
2361
2362(defun toggle-read-only (&optional arg)
2363 "Change whether this buffer is visiting its file read-only.
2a9fe1e2
RS
2364With arg, set read-only iff arg is positive.
2365If visiting file read-only and `view-read-only' is non-nil, enter view mode."
b4da00e9 2366 (interactive "P")
2a9fe1e2
RS
2367 (cond
2368 ((and arg (if (> (prefix-numeric-value arg) 0) buffer-read-only
2369 (not buffer-read-only))) ; If buffer-read-only is set correctly,
2370 nil) ; do nothing.
2371 ;; Toggle.
2372 ((and buffer-read-only view-mode)
2373 (View-exit-and-edit)) ; Must leave view mode.
2374 ((and (not buffer-read-only) view-read-only
2375 (not (eq (get major-mode 'mode-class) 'special)))
2376 (view-mode-enter))
2377 (t (setq buffer-read-only (not buffer-read-only))
2378 (force-mode-line-update))))
b4da00e9 2379
912192d1 2380(defun insert-file (filename)
b4da00e9
RM
2381 "Insert contents of file FILENAME into buffer after point.
2382Set mark after the inserted text.
2383
2384This function is meant for the user to run interactively.
2385Don't call it from programs! Use `insert-file-contents' instead.
2386\(Its calling sequence is different; see its documentation)."
912192d1 2387 (interactive "*fInsert file: ")
3be6243a
RS
2388 (if (file-directory-p filename)
2389 (signal 'file-error (list "Opening input file" "file is a directory"
2390 filename)))
912192d1 2391 (let ((tem (insert-file-contents filename)))
b4da00e9
RM
2392 (push-mark (+ (point) (car (cdr tem))))))
2393
912192d1 2394(defun append-to-file (start end filename)
b4da00e9
RM
2395 "Append the contents of the region to the end of file FILENAME.
2396When called from a function, expects three arguments,
2397START, END and FILENAME. START and END are buffer positions
da30bf98 2398saying what text to write."
912192d1
KH
2399 (interactive "r\nFAppend to file: ")
2400 (write-region start end filename t))
b4da00e9
RM
2401
2402(defun file-newest-backup (filename)
2403 "Return most recent backup file for FILENAME or nil if no backups exist."
2404 (let* ((filename (expand-file-name filename))
2405 (file (file-name-nondirectory filename))
2406 (dir (file-name-directory filename))
2407 (comp (file-name-all-completions file dir))
cf7e94a0
RS
2408 (newest nil)
2409 tem)
b4da00e9 2410 (while comp
cf7e94a0 2411 (setq tem (car comp)
b4da00e9 2412 comp (cdr comp))
cf7e94a0
RS
2413 (cond ((and (backup-file-name-p tem)
2414 (string= (file-name-sans-versions tem) file))
2415 (setq tem (concat dir tem))
2416 (if (or (null newest)
2417 (file-newer-than-file-p tem newest))
2418 (setq newest tem)))))
b4da00e9
RM
2419 newest))
2420
2421(defun rename-uniquely ()
2422 "Rename current buffer to a similar name not already taken.
2423This function is useful for creating multiple shell process buffers
2424or multiple mail buffers, etc."
2425 (interactive)
40eb8038 2426 (save-match-data
e0df3aef
KH
2427 (let ((base-name (buffer-name)))
2428 (and (string-match "<[0-9]+>\\'" base-name)
2429 (not (and buffer-file-name
2430 (string= base-name
2431 (file-name-nondirectory buffer-file-name))))
2432 ;; If the existing buffer name has a <NNN>,
2433 ;; which isn't part of the file name (if any),
2434 ;; then get rid of that.
2435 (setq base-name (substring base-name 0 (match-beginning 0))))
2436 (rename-buffer (generate-new-buffer-name base-name))
3941fe2c 2437 (force-mode-line-update))))
5bbbceb1 2438
4e43240a 2439(defun make-directory (dir &optional parents)
5ce8bb89
RS
2440 "Create the directory DIR and any nonexistent parent dirs.
2441Interactively, the default choice of directory to create
2442is the current default directory for file names.
0225ae5e 2443That is useful when you have visited a file in a nonexistent directory.
5ce8bb89
RS
2444
2445Noninteractively, the second (optional) argument PARENTS says whether
2446to create parent directories if they don't exist."
2447 (interactive
2448 (list (read-file-name "Make directory: " default-directory default-directory
2449 nil nil)
2450 t))
6eaebaa2 2451 (let ((handler (find-file-name-handler dir 'make-directory)))
4e43240a
RS
2452 (if handler
2453 (funcall handler 'make-directory dir parents)
2454 (if (not parents)
2455 (make-directory-internal dir)
2456 (let ((dir (directory-file-name (expand-file-name dir)))
2457 create-list)
2458 (while (not (file-exists-p dir))
76d5492b 2459 (setq create-list (cons dir create-list)
4e43240a
RS
2460 dir (directory-file-name (file-name-directory dir))))
2461 (while create-list
2462 (make-directory-internal (car create-list))
2463 (setq create-list (cdr create-list))))))))
b4da00e9
RM
2464\f
2465(put 'revert-buffer-function 'permanent-local t)
2466(defvar revert-buffer-function nil
0973d78b
RS
2467 "Function to use to revert this buffer, or nil to do the default.
2468The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2469which are the arguments that `revert-buffer' received.")
b4da00e9
RM
2470
2471(put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2472(defvar revert-buffer-insert-file-contents-function nil
2473 "Function to use to insert contents when reverting this buffer.
2474Gets two args, first the nominal file name to use,
2475and second, t if reading the auto-save file.")
2476
5f76e7d4
KH
2477(defvar before-revert-hook nil
2478 "Normal hook for `revert-buffer' to run before reverting.
2479If `revert-buffer-function' is used to override the normal revert
2480mechanism, this hook is not used.")
2481
2482(defvar after-revert-hook nil
2483 "Normal hook for `revert-buffer' to run after reverting.
2484Note that the hook value that it runs is the value that was in effect
2485before reverting; that makes a difference if you have buffer-local
2486hook functions.
2487
2488If `revert-buffer-function' is used to override the normal revert
2489mechanism, this hook is not used.")
2490
9a30563f 2491(defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
7e7c9c4e 2492 "Replace current buffer text with the text of the visited file on disk.
b4da00e9 2493This undoes all changes since the file was visited or saved.
8c0e7b73
JB
2494With a prefix argument, offer to revert from latest auto-save file, if
2495that is more recent than the visited file.
1ab31687 2496
7e7c9c4e
RS
2497This command also works for special buffers that contain text which
2498doesn't come from a file, but reflects some other data base instead:
2499for example, Dired buffers and buffer-list buffers. In these cases,
2500it reconstructs the buffer contents from the appropriate data base.
2501
65ee6096 2502When called from Lisp, the first argument is IGNORE-AUTO; only offer
1ab31687
JB
2503to revert from the auto-save file when this is nil. Note that the
2504sense of this argument is the reverse of the prefix argument, for the
2505sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2506to nil.
2507
2508Optional second argument NOCONFIRM means don't ask for confirmation at
2509all.
b4da00e9 2510
5b2b26d5
RS
2511Optional third argument PRESERVE-MODES non-nil means don't alter
2512the files modes. Normally we reinitialize them using `normal-mode'.
2513
8c0e7b73 2514If the value of `revert-buffer-function' is non-nil, it is called to
7e7c9c4e
RS
2515do all the work for this command. Otherwise, the hooks
2516`before-revert-hook' and `after-revert-hook' are run at the beginning
2517and the end, and if `revert-buffer-insert-file-contents-function' is
2518non-nil, it is called instead of rereading visited file contents."
fb6208a6 2519
1ab31687
JB
2520 ;; I admit it's odd to reverse the sense of the prefix argument, but
2521 ;; there is a lot of code out there which assumes that the first
2522 ;; argument should be t to avoid consulting the auto-save file, and
2523 ;; there's no straightforward way to encourage authors to notice a
2524 ;; reversal of the argument sense. So I'm just changing the user
2525 ;; interface, but leaving the programmatic interface the same.
e0867e99 2526 (interactive (list (not current-prefix-arg)))
b4da00e9 2527 (if revert-buffer-function
1ab31687 2528 (funcall revert-buffer-function ignore-auto noconfirm)
b4da00e9 2529 (let* ((opoint (point))
1ab31687
JB
2530 (auto-save-p (and (not ignore-auto)
2531 (recent-auto-save-p)
b4da00e9
RM
2532 buffer-auto-save-file-name
2533 (file-readable-p buffer-auto-save-file-name)
2534 (y-or-n-p
2535 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2536 (file-name (if auto-save-p
2537 buffer-auto-save-file-name
2538 buffer-file-name)))
2539 (cond ((null file-name)
2540 (error "Buffer does not seem to be associated with any file"))
2541 ((or noconfirm
db8c4866
RS
2542 (and (not (buffer-modified-p))
2543 (let ((tail revert-without-query)
2544 (found nil))
2545 (while tail
2546 (if (string-match (car tail) file-name)
2547 (setq found t))
2548 (setq tail (cdr tail)))
2549 found))
b4da00e9
RM
2550 (yes-or-no-p (format "Revert buffer from file %s? "
2551 file-name)))
4fbf62ee 2552 (run-hooks 'before-revert-hook)
b4da00e9
RM
2553 ;; If file was backed up but has changed since,
2554 ;; we shd make another backup.
2555 (and (not auto-save-p)
5bbbceb1 2556 (not (verify-visited-file-modtime (current-buffer)))
b4da00e9
RM
2557 (setq buffer-backed-up nil))
2558 ;; Get rid of all undo records for this buffer.
2559 (or (eq buffer-undo-list t)
2560 (setq buffer-undo-list nil))
ba5c8c93
KH
2561 ;; Effectively copy the after-revert-hook status,
2562 ;; since after-find-file will clobber it.
2563 (let ((global-hook (default-value 'after-revert-hook))
2564 (local-hook-p (local-variable-p 'after-revert-hook))
2565 (local-hook (and (local-variable-p 'after-revert-hook)
2566 after-revert-hook)))
2567 (let (buffer-read-only
2568 ;; Don't make undo records for the reversion.
2569 (buffer-undo-list t))
2570 (if revert-buffer-insert-file-contents-function
2571 (funcall revert-buffer-insert-file-contents-function
2572 file-name auto-save-p)
2573 (if (not (file-exists-p file-name))
2574 (error "File %s no longer exists!" file-name))
2575 ;; Bind buffer-file-name to nil
2576 ;; so that we don't try to lock the file.
2577 (let ((buffer-file-name nil))
2578 (or auto-save-p
2579 (unlock-buffer)))
2580 (widen)
b77d8211
KH
2581 (let ((coding-system-for-read
2582 ;; Auto-saved file shoule be read without
2583 ;; any code conversion.
2584 (if auto-save-p 'no-conversion
2585 coding-system-for-read)))
2586 (insert-file-contents file-name (not auto-save-p)
2587 nil nil t))))
ba5c8c93
KH
2588 (goto-char (min opoint (point-max)))
2589 ;; Recompute the truename in case changes in symlinks
2590 ;; have changed the truename.
2591 (setq buffer-file-truename
2592 (abbreviate-file-name (file-truename buffer-file-name)))
9a30563f 2593 (after-find-file nil nil t t preserve-modes)
ba5c8c93
KH
2594 ;; Run after-revert-hook as it was before we reverted.
2595 (setq-default revert-buffer-internal-hook global-hook)
2596 (if local-hook-p
2597 (progn
2598 (make-local-variable 'revert-buffer-internal-hook)
2599 (setq revert-buffer-internal-hook local-hook))
2600 (kill-local-variable 'revert-buffer-internal-hook))
2601 (run-hooks 'revert-buffer-internal-hook))
4fbf62ee 2602 t)))))
b4da00e9
RM
2603
2604(defun recover-file (file)
2605 "Visit file FILE, but get contents from its last auto-save file."
10f7c7fc
RS
2606 ;; Actually putting the file name in the minibuffer should be used
2607 ;; only rarely.
2608 ;; Not just because users often use the default.
e1dadc17 2609 (interactive "FRecover file: ")
b4da00e9 2610 (setq file (expand-file-name file))
f7da6740
RS
2611 (if (auto-save-file-name-p (file-name-nondirectory file))
2612 (error "%s is an auto-save file" file))
b4da00e9
RM
2613 (let ((file-name (let ((buffer-file-name file))
2614 (make-auto-save-file-name))))
945e1965
RS
2615 (cond ((if (file-exists-p file)
2616 (not (file-newer-than-file-p file-name file))
2617 (not (file-exists-p file-name)))
b4da00e9
RM
2618 (error "Auto-save file %s not current" file-name))
2619 ((save-window-excursion
b1667e6c 2620 (if (not (memq system-type '(vax-vms windows-nt)))
b4da00e9
RM
2621 (with-output-to-temp-buffer "*Directory*"
2622 (buffer-disable-undo standard-output)
2623 (call-process "ls" nil standard-output nil
2dc2b736
RS
2624 (if (file-symlink-p file) "-lL" "-l")
2625 file file-name)))
b4da00e9
RM
2626 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2627 (switch-to-buffer (find-file-noselect file t))
82d0954a
KH
2628 (let ((buffer-read-only nil)
2629 ;; Auto-saved file shoule be read without any code conversion.
2630 (coding-system-for-read 'no-conversion))
b4da00e9
RM
2631 (erase-buffer)
2632 (insert-file-contents file-name nil))
8cfb9d46 2633 (after-find-file nil nil t))
ffa7ab70 2634 (t (error "Recover-file cancelled")))))
b4da00e9 2635
6598027d 2636(defun recover-session ()
9aee5392
RS
2637 "Recover auto save files from a previous Emacs session.
2638This command first displays a Dired buffer showing you the
2639previous sessions that you could recover from.
2640To choose one, move point to the proper line and then type C-c C-c.
2641Then you'll be asked about a number of files to recover."
2642 (interactive)
363a5030
RS
2643 (if (null auto-save-list-file-prefix)
2644 (error "You set `auto-save-list-file-prefix' to disable making session files"))
6f4983e6 2645 (let ((ls-lisp-support-shell-wildcards t))
7b3478a5
RS
2646 (dired (concat auto-save-list-file-prefix "*")
2647 (concat dired-listing-switches "t")))
9aee5392
RS
2648 (goto-char (point-min))
2649 (or (looking-at "Move to the session you want to recover,")
2650 (let ((inhibit-read-only t))
033ef863
RS
2651 (insert "Move to the session you want to recover,\n"
2652 "then type C-c C-c to select it.\n\n"
2653 "You can also delete some of these files;\n"
2654 "type d on a line to mark that file for deletion.\n\n")))
9aee5392 2655 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
80280bb7 2656 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
9aee5392 2657
80280bb7 2658(defun recover-session-finish ()
9aee5392
RS
2659 "Choose one saved session to recover auto-save files from.
2660This command is used in the special Dired buffer created by
80280bb7 2661\\[recover-session]."
9aee5392
RS
2662 (interactive)
2663 ;; Get the name of the session file to recover from.
2664 (let ((file (dired-get-filename))
953a03b2 2665 files
9aee5392 2666 (buffer (get-buffer-create " *recover*")))
033ef863 2667 (dired-do-flagged-delete t)
9aee5392
RS
2668 (unwind-protect
2669 (save-excursion
2670 ;; Read in the auto-save-list file.
2671 (set-buffer buffer)
2672 (erase-buffer)
2673 (insert-file-contents file)
953a03b2
RS
2674 ;; Loop thru the text of that file
2675 ;; and get out the names of the files to recover.
2676 (while (not (eobp))
2677 (let (thisfile autofile)
2678 (if (eolp)
2679 ;; This is a pair of lines for a non-file-visiting buffer.
2680 ;; Get the auto-save file name and manufacture
2681 ;; a "visited file name" from that.
2682 (progn
2683 (forward-line 1)
2684 (setq autofile
2685 (buffer-substring-no-properties
2686 (point)
2687 (save-excursion
2688 (end-of-line)
2689 (point))))
2690 (setq thisfile
2691 (expand-file-name
2692 (substring
2693 (file-name-nondirectory autofile)
2694 1 -1)
2695 (file-name-directory autofile)))
2696 (forward-line 1))
2697 ;; This pair of lines is a file-visiting
2698 ;; buffer. Use the visited file name.
2699 (progn
2700 (setq thisfile
2701 (buffer-substring-no-properties
2702 (point) (progn (end-of-line) (point))))
2703 (forward-line 1)
2704 (setq autofile
2705 (buffer-substring-no-properties
2706 (point) (progn (end-of-line) (point))))
2707 (forward-line 1)))
2708 ;; Ignore a file if its auto-save file does not exist now.
2709 (if (file-exists-p autofile)
2710 (setq files (cons thisfile files)))))
2711 (setq files (nreverse files))
945e1965
RS
2712 ;; The file contains a pair of line for each auto-saved buffer.
2713 ;; The first line of the pair contains the visited file name
2714 ;; or is empty if the buffer was not visiting a file.
2715 ;; The second line is the auto-save file name.
953a03b2
RS
2716 (if files
2717 (map-y-or-n-p "Recover %s? "
2718 (lambda (file)
2719 (condition-case nil
2720 (save-excursion (recover-file file))
76d5492b 2721 (error
953a03b2
RS
2722 "Failed to recover `%s'" file)))
2723 files
2724 '("file" "files" "recover"))
2725 (message "No files can be recovered from this session now")))
9aee5392
RS
2726 (kill-buffer buffer))))
2727
73ba610a
RS
2728(defun kill-some-buffers (&optional list)
2729 "For each buffer in LIST, ask whether to kill it.
2730LIST defaults to all existing live buffers."
b4da00e9 2731 (interactive)
73ba610a
RS
2732 (if (null list)
2733 (setq list (buffer-list)))
2734 (while list
2735 (let* ((buffer (car list))
2736 (name (buffer-name buffer)))
2737 (and (not (string-equal name ""))
2738 (/= (aref name 0) ? )
2739 (yes-or-no-p
2740 (format "Buffer %s %s. Kill? "
2741 name
2742 (if (buffer-modified-p buffer)
2743 "HAS BEEN EDITED" "is unmodified")))
2744 (kill-buffer buffer)))
2745 (setq list (cdr list))))
b4da00e9
RM
2746\f
2747(defun auto-save-mode (arg)
2748 "Toggle auto-saving of contents of current buffer.
f3e23606 2749With prefix argument ARG, turn auto-saving on if positive, else off."
b4da00e9
RM
2750 (interactive "P")
2751 (setq buffer-auto-save-file-name
2752 (and (if (null arg)
74b9c2af
RS
2753 (or (not buffer-auto-save-file-name)
2754 ;; If autosave is off because buffer has shrunk,
2755 ;; then toggling should turn it on.
2756 (< buffer-saved-size 0))
b4da00e9
RM
2757 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2758 (if (and buffer-file-name auto-save-visited-file-name
2759 (not buffer-read-only))
2760 buffer-file-name
2761 (make-auto-save-file-name))))
0b7f1ef2
RS
2762 ;; If -1 was stored here, to temporarily turn off saving,
2763 ;; turn it back on.
2764 (and (< buffer-saved-size 0)
2765 (setq buffer-saved-size 0))
b4da00e9
RM
2766 (if (interactive-p)
2767 (message "Auto-save %s (in this buffer)"
2768 (if buffer-auto-save-file-name "on" "off")))
2769 buffer-auto-save-file-name)
2770
2771(defun rename-auto-save-file ()
2772 "Adjust current buffer's auto save file name for current conditions.
2773Also rename any existing auto save file, if it was made in this session."
2774 (let ((osave buffer-auto-save-file-name))
2775 (setq buffer-auto-save-file-name
2776 (make-auto-save-file-name))
2777 (if (and osave buffer-auto-save-file-name
2778 (not (string= buffer-auto-save-file-name buffer-file-name))
2779 (not (string= buffer-auto-save-file-name osave))
2780 (file-exists-p osave)
2781 (recent-auto-save-p))
2782 (rename-file osave buffer-auto-save-file-name t))))
2783
2784(defun make-auto-save-file-name ()
2785 "Return file name to use for auto-saves of current buffer.
2786Does not consider `auto-save-visited-file-name' as that variable is checked
2787before calling this function. You can redefine this for customization.
2788See also `auto-save-file-name-p'."
2789 (if buffer-file-name
28ee503c
KH
2790 (if (and (eq system-type 'ms-dos)
2791 (not (msdos-long-file-names)))
4503dacb 2792 (let ((fn (file-name-nondirectory buffer-file-name)))
5b4dd2e2 2793 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
4503dacb
RS
2794 (concat (file-name-directory buffer-file-name)
2795 "#" (match-string 1 fn)
2796 "." (match-string 3 fn) "#"))
2797 (concat (file-name-directory buffer-file-name)
2798 "#"
2799 (file-name-nondirectory buffer-file-name)
2800 "#"))
0a1763b4
RS
2801
2802 ;; Deal with buffers that don't have any associated files. (Mail
2803 ;; mode tends to create a good number of these.)
2804
7d483e8c 2805 (let ((buffer-name (buffer-name))
0a1763b4 2806 (limit 0))
c3348e10
RS
2807 ;; Eliminate all slashes and backslashes by
2808 ;; replacing them with sequences that start with %.
2809 ;; Quote % also, to keep distinct names distinct.
2810 (while (string-match "[/\\%]" buffer-name limit)
2811 (let* ((character (aref buffer-name (match-beginning 0)))
2812 (replacement
2813 (cond ((eq character ?%) "%%")
2814 ((eq character ?/) "%+")
2815 ((eq character ?\\) "%-"))))
2816 (setq buffer-name (replace-match replacement t t buffer-name))
2817 (setq limit (1+ (match-end 0)))))
a8abaf83
RS
2818 ;; Generate the file name.
2819 (expand-file-name
2820 (format "#%s#%s#" buffer-name (make-temp-name ""))
2821 ;; Try a few alternative directories, to get one we can write it.
2822 (cond
2823 ((file-writable-p default-directory) default-directory)
2824 ((file-writable-p "/var/tmp/") "/var/tmp/")
2825 ("~/"))))))
b4da00e9
RM
2826
2827(defun auto-save-file-name-p (filename)
2828 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2829FILENAME should lack slashes. You can redefine this for customization."
2830 (string-match "^#.*#$" filename))
2831\f
6f4983e6
RS
2832(defun wildcard-to-regexp (wildcard)
2833 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2834The generated regexp will match a filename iff the filename
2835matches that wildcard according to shell rules. Only wildcards known
2836by `sh' are supported."
2837 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
2838 ;; Copy the initial run of non-special characters.
2839 (result (substring wildcard 0 i))
2840 (len (length wildcard)))
2841 ;; If no special characters, we're almost done.
2842 (if i
2843 (while (< i len)
2844 (let ((ch (aref wildcard i))
2845 j)
2846 (setq
2847 result
2848 (concat result
2849 (cond
7e7c9c4e
RS
2850 ((and (eq ch ?\[)
2851 (< (1+ i) len)
2852 (eq (aref wildcard (1+ i)) ?\]))
2853 "\\[")
6f4983e6
RS
2854 ((eq ch ?\[) ; [...] maps to regexp char class
2855 (progn
2856 (setq i (1+ i))
2857 (concat
2858 (cond
2859 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
2860 (progn
2861 (setq i (1+ i))
2862 (if (eq (aref wildcard i) ?\])
2863 (progn
2864 (setq i (1+ i))
2865 "[^]")
2866 "[^")))
2867 ((eq (aref wildcard i) ?^)
2868 ;; Found "[^". Insert a `\0' character
2869 ;; (which cannot happen in a filename)
2870 ;; into the character class, so that `^'
2871 ;; is not the first character after `[',
2872 ;; and thus non-special in a regexp.
2873 (progn
2874 (setq i (1+ i))
2875 "[\000^"))
2876 ((eq (aref wildcard i) ?\])
2877 ;; I don't think `]' can appear in a
2878 ;; character class in a wildcard, but
2879 ;; let's be general here.
2880 (progn
2881 (setq i (1+ i))
2882 "[]"))
2883 (t "["))
2884 (prog1 ; copy everything upto next `]'.
2885 (substring wildcard
2886 i
2887 (setq j (string-match
2888 "]" wildcard i)))
2889 (setq i (if j (1- j) (1- len)))))))
2890 ((eq ch ?.) "\\.")
2891 ((eq ch ?*) "[^\000]*")
2892 ((eq ch ?+) "\\+")
2893 ((eq ch ?^) "\\^")
2894 ((eq ch ?$) "\\$")
2895 ((eq ch ?\\) "\\\\") ; probably cannot happen...
2896 ((eq ch ??) "[^\000]")
2897 (t (char-to-string ch)))))
2898 (setq i (1+ i)))))
2899 ;; Shell wildcards should match the entire filename,
2900 ;; not its part. Make the regexp say so.
2901 (concat "\\`" result "\\'")))
2902\f
21540597 2903(defcustom list-directory-brief-switches
b4da00e9 2904 (if (eq system-type 'vax-vms) "" "-CF")
21540597
RS
2905 "*Switches for list-directory to pass to `ls' for brief listing,"
2906 :type 'string
2907 :group 'dired)
b4da00e9 2908
21540597 2909(defcustom list-directory-verbose-switches
b4da00e9
RM
2910 (if (eq system-type 'vax-vms)
2911 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2912 "-l")
21540597
RS
2913 "*Switches for list-directory to pass to `ls' for verbose listing,"
2914 :type 'string
2915 :group 'dired)
b4da00e9
RM
2916
2917(defun list-directory (dirname &optional verbose)
2918 "Display a list of files in or matching DIRNAME, a la `ls'.
2919DIRNAME is globbed by the shell if necessary.
2920Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2921Actions controlled by variables `list-directory-brief-switches'
2922and `list-directory-verbose-switches'."
2923 (interactive (let ((pfx current-prefix-arg))
2924 (list (read-file-name (if pfx "List directory (verbose): "
2925 "List directory (brief): ")
2926 nil default-directory nil)
2927 pfx)))
2928 (let ((switches (if verbose list-directory-verbose-switches
2929 list-directory-brief-switches)))
2930 (or dirname (setq dirname default-directory))
2931 (setq dirname (expand-file-name dirname))
2932 (with-output-to-temp-buffer "*Directory*"
2933 (buffer-disable-undo standard-output)
2934 (princ "Directory ")
2935 (princ dirname)
2936 (terpri)
c3554e95
RS
2937 (save-excursion
2938 (set-buffer "*Directory*")
5a8a160e
RS
2939 (setq default-directory
2940 (if (file-directory-p dirname)
2941 (file-name-as-directory dirname)
2942 (file-name-directory dirname)))
c3554e95
RS
2943 (let ((wildcard (not (file-directory-p dirname))))
2944 (insert-directory dirname switches wildcard (not wildcard)))))))
2945
2946(defvar insert-directory-program "ls"
2947 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2948
2949;; insert-directory
2950;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2951;; FULL-DIRECTORY-P is nil.
2952;; The single line of output must display FILE's name as it was
2953;; given, namely, an absolute path name.
2954;; - must insert exactly one line for each file if WILDCARD or
2955;; FULL-DIRECTORY-P is t, plus one optional "total" line
2956;; before the file lines, plus optional text after the file lines.
2957;; Lines are delimited by "\n", so filenames containing "\n" are not
2958;; allowed.
2959;; File lines should display the basename.
2960;; - must be consistent with
2961;; - functions dired-move-to-filename, (these two define what a file line is)
2962;; dired-move-to-end-of-filename,
2963;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2964;; dired-insert-headerline
2965;; dired-after-subdir-garbage (defines what a "total" line is)
2966;; - variable dired-subdir-regexp
2967(defun insert-directory (file switches &optional wildcard full-directory-p)
a18b7c81 2968 "Insert directory listing for FILE, formatted according to SWITCHES.
c3554e95 2969Leaves point after the inserted text.
727d277d 2970SWITCHES may be a string of options, or a list of strings.
c3554e95
RS
2971Optional third arg WILDCARD means treat FILE as shell wildcard.
2972Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2973switches do not contain `d', so that a full listing is expected.
2974
2975This works by running a directory listing program
406e12d9 2976whose name is in the variable `insert-directory-program'.
c3554e95 2977If WILDCARD, it also runs the shell specified by `shell-file-name'."
c870ab8e
RS
2978 ;; We need the directory in order to find the right handler.
2979 (let ((handler (find-file-name-handler (expand-file-name file)
2980 'insert-directory)))
c3554e95
RS
2981 (if handler
2982 (funcall handler 'insert-directory file switches
2983 wildcard full-directory-p)
b4da00e9 2984 (if (eq system-type 'vax-vms)
c3554e95 2985 (vms-read-directory file switches (current-buffer))
b7fa904c
RS
2986 (or (= 0
2987 (if wildcard
2988 ;; Run ls in the directory of the file pattern we asked for.
2989 (let ((default-directory
2990 (if (file-name-absolute-p file)
2991 (file-name-directory file)
2992 (file-name-directory (expand-file-name file))))
2993 (pattern (file-name-nondirectory file))
2994 (beg 0))
2995 ;; Quote some characters that have special meanings in shells;
2996 ;; but don't quote the wildcards--we want them to be special.
2997 ;; We also currently don't quote the quoting characters
2998 ;; in case people want to use them explicitly to quote
2999 ;; wildcard characters.
3000 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
3001 (setq pattern
3002 (concat (substring pattern 0 (match-beginning 0))
3003 "\\"
3004 (substring pattern (match-beginning 0)))
3005 beg (1+ (match-end 0))))
3006 (call-process shell-file-name nil t nil
ab85f1b1 3007 "-c" (concat "\\" ;; Disregard shell aliases!
b7fa904c
RS
3008 insert-directory-program
3009 " -d "
3010 (if (stringp switches)
3011 switches
3012 (mapconcat 'identity switches " "))
a8bf610e 3013 " -- "
ab85f1b1
RS
3014 (encode-coding-string
3015 pattern
3016 file-name-coding-system t))))
b7fa904c
RS
3017 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
3018 ;; directory if FILE is a symbolic link.
3019 (apply 'call-process
3020 insert-directory-program nil t nil
3021 (let (list)
3022 (if (listp switches)
3023 (setq list switches)
3024 (if (not (equal switches ""))
3025 (progn
3026 ;; Split the switches at any spaces
3027 ;; so we can pass separate options as separate args.
3028 (while (string-match " " switches)
3029 (setq list (cons (substring switches 0 (match-beginning 0))
3030 list)
3031 switches (substring switches (match-end 0))))
3032 (setq list (nreverse (cons switches list))))))
3033 (append list
a8bf610e
RS
3034 ;; Avoid lossage if FILE starts with `-'.
3035 '("--")
b7fa904c 3036 (list
ab85f1b1
RS
3037 (encode-coding-string
3038 (if full-directory-p
3039 (concat (file-name-as-directory file) ".")
3040 file)
3041 file-name-coding-system t)))))))
b7fa904c
RS
3042 ;; We get here if ls failed.
3043 ;; Access the file to get a suitable error.
3044 (access-file file "Reading directory"))))))
b4da00e9 3045
88902b35 3046(defvar kill-emacs-query-functions nil
65d5c6de 3047 "Functions to call with no arguments to query about killing Emacs.
78c793d1
RS
3048If any of these functions returns nil, killing Emacs is cancelled.
3049`save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
3050but `kill-emacs', the low level primitive, does not.
3051See also `kill-emacs-hook'.")
88902b35 3052
b4da00e9
RM
3053(defun save-buffers-kill-emacs (&optional arg)
3054 "Offer to save each buffer, then kill this Emacs process.
3055With prefix arg, silently save all file-visiting buffers, then kill."
3056 (interactive "P")
3057 (save-some-buffers arg t)
3058 (and (or (not (memq t (mapcar (function
3059 (lambda (buf) (and (buffer-file-name buf)
3060 (buffer-modified-p buf))))
3061 (buffer-list))))
3062 (yes-or-no-p "Modified buffers exist; exit anyway? "))
3063 (or (not (fboundp 'process-list))
3064 ;; process-list is not defined on VMS.
3065 (let ((processes (process-list))
3066 active)
3067 (while processes
528415e7 3068 (and (memq (process-status (car processes)) '(run stop open))
b4da00e9
RM
3069 (let ((val (process-kill-without-query (car processes))))
3070 (process-kill-without-query (car processes) val)
3071 val)
3072 (setq active t))
3073 (setq processes (cdr processes)))
3074 (or (not active)
3075 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
88902b35 3076 ;; Query the user for other things, perhaps.
fb15c113 3077 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
b4da00e9
RM
3078 (kill-emacs)))
3079\f
47afc068
RS
3080;; We use /: as a prefix to "quote" a file name
3081;; so that magic file name handlers will not apply to it.
3082
3083(setq file-name-handler-alist
3084 (cons '("\\`/:" . file-name-non-special)
3085 file-name-handler-alist))
3086
3087;; We depend on being the last handler on the list,
3088;; so that anything else which does need handling
3089;; has been handled already.
3090;; So it is safe for us to inhibit *all* magic file name handlers.
3091
3092(defun file-name-non-special (operation &rest arguments)
3093 (let ((file-name-handler-alist nil)
5cb1f728
KH
3094 (default-directory
3095 (if (eq operation 'insert-directory)
3096 (directory-file-name
3097 (expand-file-name
3098 (unhandled-file-name-directory default-directory)))
3099 default-directory))
47afc068
RS
3100 ;; Get a list of the indices of the args which are file names.
3101 (file-arg-indices
3102 (cdr (or (assq operation
3103 ;; The first four are special because they
3104 ;; return a file name. We want to include the /:
3105 ;; in the return value.
3106 ;; So just avoid stripping it in the first place.
3107 '((expand-file-name . nil)
18b9dced
RS
3108 ;; `identity' means just return the first arg
3109 ;; as stripped of its quoting.
3110 (substitute-in-file-name . identity)
47afc068
RS
3111 (file-name-directory . nil)
3112 (file-name-as-directory . nil)
3113 (directory-file-name . nil)
feaec97d
RS
3114 (file-name-completion 0 1)
3115 (file-name-all-completions 0 1)
47afc068
RS
3116 (rename-file 0 1)
3117 (copy-file 0 1)
3118 (make-symbolic-link 0 1)
3119 (add-name-to-file 0 1)))
3120 ;; For all other operations, treat the first argument only
3121 ;; as the file name.
3122 '(nil 0))))
3123 ;; Copy ARGUMENTS so we can replace elements in it.
3124 (arguments (copy-sequence arguments)))
3125 ;; Strip off the /: from the file names that have this handler.
3126 (save-match-data
18b9dced 3127 (while (consp file-arg-indices)
fe4d9852
KH
3128 (let ((pair (nthcdr (car file-arg-indices) arguments)))
3129 (and (car pair)
3130 (string-match "\\`/:" (car pair))
3131 (setcar pair
3132 (if (= (length (car pair)) 2)
3133 "/"
3134 (substring (car pair) 2)))))
47afc068 3135 (setq file-arg-indices (cdr file-arg-indices))))
18b9dced
RS
3136 (if (eq file-arg-indices 'identity)
3137 (car arguments)
3138 (apply operation arguments))))
47afc068 3139\f
b4da00e9 3140(define-key ctl-x-map "\C-f" 'find-file)
b4da00e9
RM
3141(define-key ctl-x-map "\C-r" 'find-file-read-only)
3142(define-key ctl-x-map "\C-v" 'find-alternate-file)
3143(define-key ctl-x-map "\C-s" 'save-buffer)
3144(define-key ctl-x-map "s" 'save-some-buffers)
3145(define-key ctl-x-map "\C-w" 'write-file)
3146(define-key ctl-x-map "i" 'insert-file)
3147(define-key esc-map "~" 'not-modified)
3148(define-key ctl-x-map "\C-d" 'list-directory)
3149(define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
3150
3151(define-key ctl-x-4-map "f" 'find-file-other-window)
3152(define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
3153(define-key ctl-x-4-map "\C-f" 'find-file-other-window)
3154(define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
924f0a24 3155(define-key ctl-x-4-map "\C-o" 'display-buffer)
5bbbceb1 3156
f98955ea
JB
3157(define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
3158(define-key ctl-x-5-map "f" 'find-file-other-frame)
3159(define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
3160(define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
c0274f38
ER
3161
3162;;; files.el ends here