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