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