*** empty log message ***
[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
a8d002d2
GM
1072
1073 ;; Check if a formerly read-only file has become
1074 ;; writable and vice versa.
1075 (let ((read-only (not (file-writable-p buffer-file-name))))
1076 (unless (eq read-only buffer-read-only)
1077 (when (or nowarn
1078 (let ((question
1079 (format "File %s is %s on disk. Change buffer mode? "
1080 buffer-file-name
1081 (if read-only "read-only" "writable"))))
1082 (y-or-n-p question)))
1083 (setq buffer-read-only read-only))))
1084
5de148a2
RS
1085 (when (not (eq (not (null rawfile))
1086 (not (null find-file-literally))))
1087 (if (buffer-modified-p)
ddd64da9 1088 (if (y-or-n-p (if rawfile
5de148a2
RS
1089 "Save file and revisit literally? "
1090 "Save file and revisit non-literally? "))
1091 (progn
1092 (save-buffer)
1093 (find-file-noselect-1 buf filename nowarn
1094 rawfile truename number))
1095 (if (y-or-n-p (if rawfile
1096 "Discard your edits and revisit file literally? "
1097 "Discard your edits and revisit file non-literally? "))
1098 (find-file-noselect-1 buf filename nowarn
1099 rawfile truename number)
1100 (error (if rawfile "File already visited non-literally"
1101 "File already visited literally"))))
1102 (if (y-or-n-p (if rawfile
1103 "Revisit file literally? "
1104 "Revisit file non-literally? "))
1105 (find-file-noselect-1 buf filename nowarn
1106 rawfile truename number)
1107 (error (if rawfile "File already visited non-literally"
1108 "File already visited literally"))))))
1109 ;; Return the buffer we are using.
1110 buf)
1111 ;; Create a new buffer.
1112 (setq buf (create-file-buffer filename))
1113 (set-buffer-major-mode buf)
1114 ;; find-file-noselect-1 may use a different buffer.
1115 (find-file-noselect-1 buf filename nowarn
1116 rawfile truename number))))))
ddd64da9
RS
1117
1118(defun find-file-noselect-1 (buf filename nowarn rawfile truename number)
666c1d8b
RS
1119 (let ((inhibit-read-only t)
1120 error)
ddd64da9
RS
1121 (with-current-buffer buf
1122 (kill-local-variable 'find-file-literally)
b296cbd4
RS
1123 ;; Needed in case we are re-visiting the file with a different
1124 ;; text representation.
e73ec04b 1125 (kill-local-variable 'buffer-file-coding-system)
ddd64da9
RS
1126 (erase-buffer)
1127 (and (default-value 'enable-multibyte-characters)
1128 (not rawfile)
1129 (set-buffer-multibyte t))
1130 (if rawfile
1131 (condition-case ()
1132 (insert-file-contents-literally filename t)
1133 (file-error
1134 (when (and (file-exists-p filename)
1135 (not (file-readable-p filename)))
1136 (kill-buffer buf)
1137 (signal 'file-error (list "File is not readable"
1138 filename)))
1139 ;; Unconditionally set error
1140 (setq error t)))
1141 (condition-case ()
1142 (insert-file-contents filename t)
1143 (file-error
1144 (when (and (file-exists-p filename)
1145 (not (file-readable-p filename)))
1146 (kill-buffer buf)
1147 (signal 'file-error (list "File is not readable"
1148 filename)))
1149 ;; Run find-file-not-found-hooks until one returns non-nil.
1150 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
1151 ;; If they fail too, set error.
1152 (setq error t)))))
b120e713
KH
1153 ;; Record the file's truename, and maybe use that as visited name.
1154 (if (equal filename buffer-file-name)
1155 (setq buffer-file-truename truename)
9ab19105
DL
1156 (setq buffer-file-truename
1157 (abbreviate-file-name (file-truename buffer-file-name))))
ddd64da9
RS
1158 (setq buffer-file-number number)
1159 ;; On VMS, we may want to remember which directory in a search list
1160 ;; the file was found in.
1161 (and (eq system-type 'vax-vms)
1162 (let (logical)
1163 (if (string-match ":" (file-name-directory filename))
1164 (setq logical (substring (file-name-directory filename)
1165 0 (match-beginning 0))))
1166 (not (member logical find-file-not-true-dirname-list)))
1167 (setq buffer-file-name buffer-file-truename))
1168 (if find-file-visit-truename
1169 (setq buffer-file-name
1170 (setq filename
1171 (expand-file-name buffer-file-truename))))
1172 ;; Set buffer's default directory to that of the file.
b120e713 1173 (setq default-directory (file-name-directory buffer-file-name))
ddd64da9
RS
1174 ;; Turn off backup files for certain file names. Since
1175 ;; this is a permanent local, the major mode won't eliminate it.
1176 (and (not (funcall backup-enable-predicate buffer-file-name))
1177 (progn
1178 (make-local-variable 'backup-inhibited)
1179 (setq backup-inhibited t)))
1180 (if rawfile
1181 (progn
1182 (set-buffer-multibyte nil)
1183 (setq buffer-file-coding-system 'no-conversion)
1184 (make-local-variable 'find-file-literally)
1185 (setq find-file-literally t))
b296cbd4
RS
1186 (after-find-file error (not nowarn)))
1187 (current-buffer))))
9b8ef27d
RS
1188\f
1189(defun insert-file-contents-literally (filename &optional visit beg end replace)
1190 "Like `insert-file-contents', but only reads in the file literally.
1191A buffer may be modified in several ways after reading into the buffer,
1192to Emacs features such as format decoding, character code
d5798fa7 1193conversion, `find-file-hooks', automatic uncompression, etc.
9b8ef27d
RS
1194
1195This function ensures that none of these modifications will take place."
1196 (let ((format-alist nil)
1197 (after-insert-file-functions nil)
1198 (coding-system-for-read 'no-conversion)
1199 (coding-system-for-write 'no-conversion)
9b8ef27d
RS
1200 (find-buffer-file-type-function
1201 (if (fboundp 'find-buffer-file-type)
1202 (symbol-function 'find-buffer-file-type)
7e365285
DL
1203 nil))
1204 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
1205 (inhibit-file-name-operation 'insert-file-contents))
9b8ef27d
RS
1206 (unwind-protect
1207 (progn
1208 (fset 'find-buffer-file-type (lambda (filename) t))
1209 (insert-file-contents filename visit beg end replace))
1210 (if find-buffer-file-type-function
1211 (fset 'find-buffer-file-type find-buffer-file-type-function)
1212 (fmakunbound 'find-buffer-file-type)))))
1213
1214(defun insert-file-literally (filename)
1215 "Insert contents of file FILENAME into buffer after point with no conversion.
1216
1217This function is meant for the user to run interactively.
1218Don't call it from programs! Use `insert-file-contents-literally' instead.
1219\(Its calling sequence is different; see its documentation)."
1220 (interactive "*fInsert file literally: ")
1221 (if (file-directory-p filename)
1222 (signal 'file-error (list "Opening input file" "file is a directory"
1223 filename)))
1224 (let ((tem (insert-file-contents-literally filename)))
1225 (push-mark (+ (point) (car (cdr tem))))))
1226
1227(defvar find-file-literally nil
1228 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
1229This is a permanent local.")
1230(put 'find-file-literally 'permanent-local t)
5fc196af 1231
ffc0e1ca 1232(defun find-file-literally (filename)
5fc196af
RS
1233 "Visit file FILENAME with no conversion of any kind.
1234Format conversion and character code conversion are both disabled,
1235and multibyte characters are disabled in the resulting buffer.
e65db7b8
RS
1236The major mode used is Fundamental mode regardless of the file name,
1237and local variable specifications in the file are ignored.
407b4328
GM
1238Automatic uncompression and adding a newline at the end of the
1239file due to `require-final-newline' is also disabled.
9b8ef27d
RS
1240
1241You cannot absolutely rely on this function to result in
b9aa9537 1242visiting the file literally. If Emacs already has a buffer
9b8ef27d
RS
1243which is visiting the file, you get the existing buffer,
1244regardless of whether it was created literally or not.
1245
1246In a Lisp program, if you want to be sure of accessing a file's
1247contents literally, you should create a temporary buffer and then read
1248the file contents into it using `insert-file-contents-literally'."
5fc196af 1249 (interactive "FFind file literally: ")
9b8ef27d 1250 (switch-to-buffer (find-file-noselect filename nil t)))
b4da00e9 1251\f
f7d786d0
RS
1252(defvar after-find-file-from-revert-buffer nil)
1253
e0ab8879 1254(defun after-find-file (&optional error warn noauto
9a30563f
RS
1255 after-find-file-from-revert-buffer
1256 nomodes)
b4da00e9
RM
1257 "Called after finding a file and by the default revert function.
1258Sets buffer mode, parses local variables.
8cfb9d46 1259Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
b4da00e9
RM
1260error in reading the file. WARN non-nil means warn if there
1261exists an auto-save file more recent than the visited file.
8cfb9d46 1262NOAUTO means don't mess with auto-save mode.
e0ab8879
RS
1263Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1264 means this call was from `revert-buffer'.
9a30563f
RS
1265Fifth arg NOMODES non-nil means don't alter the file's modes.
1266Finishes by calling the functions in `find-file-hooks'
1267unless NOMODES is non-nil."
b4da00e9
RM
1268 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1269 (if noninteractive
1270 nil
1271 (let* (not-serious
1272 (msg
fe50b6ab
GM
1273 (cond
1274 ((not warn) nil)
1275 ((and error (file-attributes buffer-file-name))
1276 (setq buffer-read-only t)
1277 "File exists, but cannot be read")
1278 ((not buffer-read-only)
1279 (if (and warn
1280 ;; No need to warn if buffer is auto-saved
1281 ;; under the name of the visited file.
1282 (not (and buffer-file-name
1283 auto-save-visited-file-name))
1284 (file-newer-than-file-p (or buffer-auto-save-file-name
1285 (make-auto-save-file-name))
1286 buffer-file-name))
1287 (format "%s has auto save data; consider M-x recover-file"
1288 (file-name-nondirectory buffer-file-name))
1289 (setq not-serious t)
1290 (if error "(New file)" nil)))
1291 ((not error)
1292 (setq not-serious t)
1293 "Note: file is write protected")
1294 ((file-attributes (directory-file-name default-directory))
1295 "File not found and directory write-protected")
1296 ((file-exists-p (file-name-directory buffer-file-name))
1297 (setq buffer-read-only nil))
1298 (t
1299 (setq buffer-read-only nil)
1300 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
1301 "Use M-x make-directory RET RET to create the directory"
1302 "Use C-u M-x make-directory RET RET to create directory and its parents")))))
1303 (when msg
1304 (message msg)
1305 (or not-serious (sit-for 1 nil t))))
1306 (when (and auto-save-default (not noauto))
1307 (auto-save-mode t)))
ffc0e1ca
AS
1308 ;; Make people do a little extra work (C-x C-q)
1309 ;; before altering a backup file.
fe50b6ab
GM
1310 (when (backup-file-name-p buffer-file-name)
1311 (setq buffer-read-only t))
1312 (unless nomodes
1313 (when (and view-read-only view-mode)
1314 (view-mode-disable))
9a30563f 1315 (normal-mode t)
fe50b6ab
GM
1316 (when (and buffer-read-only
1317 view-read-only
1318 (not (eq (get major-mode 'mode-class) 'special)))
1319 (view-mode-enter))
9a30563f 1320 (run-hooks 'find-file-hooks)))
b4da00e9
RM
1321
1322(defun normal-mode (&optional find-file)
1323 "Choose the major mode for this buffer automatically.
1324Also sets up any specified local variables of the file.
1325Uses the visited file name, the -*- line, and the local variables spec.
1326
1327This function is called automatically from `find-file'. In that case,
aa5fcebf
KH
1328we may set up the file-specified mode and local variables,
1329depending on the value of `enable-local-variables': if it is t, we do;
1330if it is nil, we don't; otherwise, we query.
1331In addition, if `local-enable-local-variables' is nil, we do
1332not set local variables (though we do notice a mode specified with -*-.)
1333
1334`enable-local-variables' is ignored if you run `normal-mode' interactively,
1335or from Lisp without specifying the optional argument FIND-FILE;
1336in that case, this function acts as if `enable-local-variables' were t."
b4da00e9
RM
1337 (interactive)
1338 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1339 (condition-case err
1340 (set-auto-mode)
1341 (error (message "File mode specification error: %s"
1342 (prin1-to-string err))))
1343 (condition-case err
7b3f3dc2
JB
1344 (let ((enable-local-variables (or (not find-file)
1345 enable-local-variables)))
1346 (hack-local-variables))
b4da00e9
RM
1347 (error (message "File local-variables error: %s"
1348 (prin1-to-string err)))))
1349
f76e0cd0 1350(defvar auto-mode-alist
ffc0e1ca
AS
1351 (mapc
1352 (lambda (elt)
1353 (cons (purecopy (car elt)) (cdr elt)))
1354 '(("\\.te?xt\\'" . text-mode)
1355 ("\\.c\\'" . c-mode)
1356 ("\\.h\\'" . c-mode)
1357 ("\\.tex\\'" . tex-mode)
1358 ("\\.ltx\\'" . latex-mode)
1359 ("\\.el\\'" . emacs-lisp-mode)
1360 ("\\.scm\\'" . scheme-mode)
1361 ("\\.l\\'" . lisp-mode)
1362 ("\\.lisp\\'" . lisp-mode)
1363 ("\\.f\\'" . fortran-mode)
1364 ("\\.F\\'" . fortran-mode)
1365 ("\\.for\\'" . fortran-mode)
1366 ("\\.p\\'" . pascal-mode)
1367 ("\\.pas\\'" . pascal-mode)
1368 ("\\.ad[abs]\\'" . ada-mode)
5c6d31a4 1369 ("\\.\\([pP]\\([Llm]\\|erl\\)\\|al\\)\\'" . perl-mode)
ffc0e1ca
AS
1370 ("\\.s?html?\\'" . html-mode)
1371 ("\\.cc\\'" . c++-mode)
1372 ("\\.hh\\'" . c++-mode)
1373 ("\\.hpp\\'" . c++-mode)
1374 ("\\.C\\'" . c++-mode)
1375 ("\\.H\\'" . c++-mode)
1376 ("\\.cpp\\'" . c++-mode)
1377 ("\\.cxx\\'" . c++-mode)
1378 ("\\.hxx\\'" . c++-mode)
1379 ("\\.c\\+\\+\\'" . c++-mode)
1380 ("\\.h\\+\\+\\'" . c++-mode)
1381 ("\\.m\\'" . objc-mode)
1382 ("\\.java\\'" . java-mode)
1383 ("\\.mk\\'" . makefile-mode)
1384 ("\\(M\\|m\\|GNUm\\)akefile\\(\\.in\\)?\\'" . makefile-mode)
1385 ("\\.am\\'" . makefile-mode) ;For Automake.
5c6d31a4
SM
1386 ;; Less common extensions come here
1387 ;; so more common ones above are found faster.
ffc0e1ca
AS
1388 ("\\.texinfo\\'" . texinfo-mode)
1389 ("\\.te?xi\\'" . texinfo-mode)
1390 ("\\.s\\'" . asm-mode)
1391 ("\\.S\\'" . asm-mode)
1392 ("\\.asm\\'" . asm-mode)
1393 ("ChangeLog\\'" . change-log-mode)
1394 ("change\\.log\\'" . change-log-mode)
1395 ("changelo\\'" . change-log-mode)
1396 ("ChangeLog\\.[0-9]+\\'" . change-log-mode)
1397 ;; for MSDOS and MS-Windows (which are case-insensitive)
1398 ("changelog\\'" . change-log-mode)
1399 ("changelog\\.[0-9]+\\'" . change-log-mode)
1400 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
1401 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
1402 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
1403 ("\\(/\\|\\`\\)\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
1404 ("\\(/\\|\\`\\)\\.\\(bash_logout\\|shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
1405 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
d5798fa7 1406 ("\\.m?spec\\'" . sh-mode)
ffc0e1ca
AS
1407 ("\\.mm\\'" . nroff-mode)
1408 ("\\.me\\'" . nroff-mode)
1409 ("\\.ms\\'" . nroff-mode)
1410 ("\\.man\\'" . nroff-mode)
1411 ("\\.\\(u?lpc\\|pike\\|pmod\\)\\'" . pike-mode)
ffc0e1ca
AS
1412 ("\\.TeX\\'" . tex-mode)
1413 ("\\.sty\\'" . latex-mode)
1414 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
1415 ("\\.clo\\'" . latex-mode) ;LaTeX 2e class option
1416 ("\\.bbl\\'" . latex-mode)
1417 ("\\.bib\\'" . bibtex-mode)
1418 ("\\.sql\\'" . sql-mode)
1419 ("\\.m4\\'" . m4-mode)
1420 ("\\.mc\\'" . m4-mode)
1421 ("\\.mf\\'" . metafont-mode)
1422 ("\\.mp\\'" . metapost-mode)
1423 ("\\.vhdl?\\'" . vhdl-mode)
1424 ("\\.article\\'" . text-mode)
1425 ("\\.letter\\'" . text-mode)
1426 ("\\.tcl\\'" . tcl-mode)
1427 ("\\.exp\\'" . tcl-mode)
1428 ("\\.itcl\\'" . tcl-mode)
1429 ("\\.itk\\'" . tcl-mode)
1430 ("\\.icn\\'" . icon-mode)
1431 ("\\.sim\\'" . simula-mode)
1432 ("\\.mss\\'" . scribe-mode)
1433 ("\\.f90\\'" . f90-mode)
1434 ("\\.pro\\'" . idlwave-mode)
1435 ("\\.lsp\\'" . lisp-mode)
1436 ("\\.awk\\'" . awk-mode)
1437 ("\\.prolog\\'" . prolog-mode)
1438 ("\\.tar\\'" . tar-mode)
1439 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\|jar\\)\\'" . archive-mode)
1440 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\|JAR\\)\\'" . archive-mode)
1441 ;; Mailer puts message to be edited in
1442 ;; /tmp/Re.... or Message
1443 ("\\`/tmp/Re" . text-mode)
1444 ("/Message[0-9]*\\'" . text-mode)
1445 ("/drafts/[0-9]+\\'" . mh-letter-mode)
1446 ("\\.zone\\'" . zone-mode)
1447 ;; some news reader is reported to use this
1448 ("\\`/tmp/fol/" . text-mode)
1449 ("\\.y\\'" . c-mode)
1450 ("\\.lex\\'" . c-mode)
1451 ("\\.oak\\'" . scheme-mode)
1452 ("\\.sgml?\\'" . sgml-mode)
1453 ("\\.xml\\'" . sgml-mode)
1454 ("\\.dtd\\'" . sgml-mode)
1455 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
1456 ("\\.idl\\'" . idl-mode)
1457 ;; .emacs following a directory delimiter
1458 ;; in Unix, MSDOG or VMS syntax.
1459 ("[]>:/\\]\\..*emacs\\'" . emacs-lisp-mode)
1460 ("\\`\\..*emacs\\'" . emacs-lisp-mode)
1461 ;; _emacs following a directory delimiter
1462 ;; in MsDos syntax
1463 ("[:/]_emacs\\'" . emacs-lisp-mode)
1464 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode)
1465 ("\\.ml\\'" . lisp-mode)
d5798fa7
SM
1466 ("\\.\\(asn\\|mib\\|smi\\)\\'" . snmp-mode)
1467 ("\\.\\(as\\|mi\\|sm\\)2\\'" . snmpv2-mode)
ffc0e1ca 1468 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode)
e854cc22 1469 ("\\.\\(dif\\|pat\\)\\'" . diff-mode) ; for MSDOG
d5798fa7 1470 ("\\.[eE]?[pP][sS]\\'" . ps-mode)
e55c4863 1471 ("configure\\.\\(ac\\|in\\)\\'" . autoconf-mode)
ffc0e1ca
AS
1472 ("BROWSE\\'" . ebrowse-tree-mode)
1473 ("\\.ebrowse\\'" . ebrowse-tree-mode)
9ee45b2c
SM
1474 ("#\\*mail\\*" . mail-mode)
1475 ;; Get rid of any trailing .n.m and try again.
1476 ;; This is for files saved by cvs-merge that look like .#<file>.<rev>
5c6d31a4
SM
1477 ;; or .#<file>.<rev>-<rev> or VC's <file>.~<rev>~.
1478 ;; Using mode nil rather than `ignore' would let the search continue
1479 ;; through this list (with the shortened name) rather than start over.
1480 ("\\.~?[0-9]+\\.[0-9][-.0-9]*~?\\'" ignore t)
1481 ;; The following should come after the ChangeLog pattern
1482 ;; for the sake of ChangeLog.1, etc.
1483 ;; and after the .scm.[0-9] and CVS' <file>.<rev> patterns too.
e043664a 1484 ("\\.[1-9]\\'" . nroff-mode)
7423978d 1485 ("\\.g\\'" . antlr-mode)))
ffc0e1ca 1486 "Alist of filename patterns vs corresponding major mode functions.
116987ba
RS
1487Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1488\(NON-NIL stands for anything that is not nil; the value does not matter.)
1489Visiting a file whose name matches REGEXP specifies FUNCTION as the
1490mode function to use. FUNCTION will be called, unless it is nil.
1491
1492If the element has the form (REGEXP FUNCTION NON-NIL), then after
1493calling FUNCTION (if it's not nil), we delete the suffix that matched
1494REGEXP and search the list again for another match.")
7b3f3dc2 1495
e13322a0 1496
d7fa5aa2 1497(defvar interpreter-mode-alist
ffc0e1ca
AS
1498 (mapc
1499 (lambda (l)
1500 (cons (purecopy (car l)) (cdr l)))
1501 '(("perl" . perl-mode)
1502 ("perl5" . perl-mode)
1503 ("miniperl" . perl-mode)
1504 ("wish" . tcl-mode)
1505 ("wishx" . tcl-mode)
1506 ("tcl" . tcl-mode)
1507 ("tclsh" . tcl-mode)
1508 ("awk" . awk-mode)
1509 ("mawk" . awk-mode)
1510 ("nawk" . awk-mode)
1511 ("gawk" . awk-mode)
1512 ("scm" . scheme-mode)
1513 ("ash" . sh-mode)
1514 ("bash" . sh-mode)
1515 ("bash2" . sh-mode)
1516 ("csh" . sh-mode)
1517 ("dtksh" . sh-mode)
1518 ("es" . sh-mode)
1519 ("itcsh" . sh-mode)
1520 ("jsh" . sh-mode)
1521 ("ksh" . sh-mode)
1522 ("oash" . sh-mode)
1523 ("pdksh" . sh-mode)
1524 ("rc" . sh-mode)
1525 ("rpm" . sh-mode)
1526 ("sh" . sh-mode)
1527 ("sh5" . sh-mode)
1528 ("tcsh" . sh-mode)
1529 ("wksh" . sh-mode)
1530 ("wsh" . sh-mode)
1531 ("zsh" . sh-mode)
1532 ("tail" . text-mode)
1533 ("more" . text-mode)
1534 ("less" . text-mode)
1535 ("pg" . text-mode)
1536 ("make" . makefile-mode) ; Debian uses this
1537 ("guile" . scheme-mode)
1538 ("clisp" . lisp-mode)))
c907d156
RS
1539 "Alist mapping interpreter names to major modes.
1540This alist applies to files whose first line starts with `#!'.
1541Each element looks like (INTERPRETER . MODE).
1542The car of each element is compared with
1543the name of the interpreter specified in the first line.
1544If it matches, mode MODE is selected.")
1545
d7fa5aa2 1546(defvar inhibit-first-line-modes-regexps '("\\.tar\\'" "\\.tgz\\'")
45fb3bb8 1547 "List of regexps; if one matches a file name, don't look for `-*-'.")
a0c9f21b 1548
d7fa5aa2 1549(defvar inhibit-first-line-modes-suffixes nil
b20ff6d0
RS
1550 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1551When checking `inhibit-first-line-modes-regexps', we first discard
1552from the end of the file name anything that matches one of these regexps.")
1553
ffc0e1ca
AS
1554(defvar auto-mode-interpreter-regexp
1555 "#![ \t]?\\([^ \t\n]*\
1556/bin/env[ \t]\\)?\\([^ \t\n]+\\)"
1557 "Regular expression matching interpreters, for file mode determination.
1558This regular expression is matched against the first line of a file
1559to determine the file's mode in `set-auto-mode' when Emacs can't deduce
1560a mode from the file's name. If it matches, the file is assumed to
1561be interpreted by the interpreter matched by the second group of the
1562regular expression. The mode is then determined as the mode associated
1563with that interpreter in `interpreter-mode-alist'.")
0720b68b 1564
9de9b6a2 1565(defun set-auto-mode (&optional just-from-file-name)
b4da00e9 1566 "Select major mode appropriate for current buffer.
e3998da1
RS
1567This checks for a -*- mode tag in the buffer's text,
1568compares the filename against the entries in `auto-mode-alist',
1569or checks the interpreter that runs this file against
1570`interpreter-mode-alist'.
1571
1572It does not check for the `mode:' local variable in the
1573Local Variables section of the file; for that, use `hack-local-variables'.
7b3f3dc2 1574
f3e23606 1575If `enable-local-variables' is nil, this function does not check for a
9de9b6a2
RS
1576-*- mode tag.
1577
1578If the optional argument JUST-FROM-FILE-NAME is non-nil,
1579then we do not set anything but the major mode,
1580and we don't even do that unless it would come from the file name."
b4da00e9 1581 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
d0fc03ef 1582 (let (beg end done modes)
b4da00e9
RM
1583 (save-excursion
1584 (goto-char (point-min))
1585 (skip-chars-forward " \t\n")
9fa7bfe5
RS
1586 (and enable-local-variables
1587 ;; Don't look for -*- if this file name matches any
45fb3bb8 1588 ;; of the regexps in inhibit-first-line-modes-regexps.
cae111fa 1589 (let ((temp inhibit-first-line-modes-regexps)
4bc3d240
RS
1590 (name (if buffer-file-name
1591 (file-name-sans-versions buffer-file-name)
1592 (buffer-name))))
38832b4c
KH
1593 (while (let ((sufs inhibit-first-line-modes-suffixes))
1594 (while (and sufs (not (string-match (car sufs) name)))
1595 (setq sufs (cdr sufs)))
1596 sufs)
1597 (setq name (substring name 0 (match-beginning 0))))
9fa7bfe5 1598 (while (and temp
b20ff6d0 1599 (not (string-match (car temp) name)))
9fa7bfe5
RS
1600 (setq temp (cdr temp)))
1601 (not temp))
1602 (search-forward "-*-" (save-excursion
1603 ;; If the file begins with "#!"
1604 ;; (exec interpreter magic), look
1605 ;; for mode frobs in the first two
1606 ;; lines. You cannot necessarily
1607 ;; put them in the first line of
1608 ;; such a file without screwing up
1609 ;; the interpreter invocation.
1610 (end-of-line (and (looking-at "^#!") 2))
1611 (point)) t)
1612 (progn
1613 (skip-chars-forward " \t")
1614 (setq beg (point))
1615 (search-forward "-*-"
1616 (save-excursion (end-of-line) (point))
1617 t))
1618 (progn
1619 (forward-char -3)
1620 (skip-chars-backward " \t")
1621 (setq end (point))
1622 (goto-char beg)
1623 (if (save-excursion (search-forward ":" end t))
1624 ;; Find all specifications for the `mode:' variable
57a0155c 1625 ;; and execute them left to right.
9fa7bfe5 1626 (while (let ((case-fold-search t))
6054fcc6
KH
1627 (or (and (looking-at "mode:")
1628 (goto-char (match-end 0)))
1629 (re-search-forward "[ \t;]mode:" end t)))
9fa7bfe5
RS
1630 (skip-chars-forward " \t")
1631 (setq beg (point))
1632 (if (search-forward ";" end t)
1633 (forward-char -1)
1634 (goto-char end))
1635 (skip-chars-backward " \t")
9ee45b2c
SM
1636 (push (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1637 modes))
9fa7bfe5 1638 ;; Simple -*-MODE-*- case.
9ee45b2c
SM
1639 (push (intern (concat (downcase (buffer-substring beg end))
1640 "-mode"))
1641 modes)))))
d0fc03ef
RS
1642 ;; If we found modes to use, invoke them now,
1643 ;; outside the save-excursion.
9ee45b2c
SM
1644 (unless just-from-file-name
1645 (dolist (mode (nreverse modes))
1646 (if (not (functionp mode))
1647 (message "Ignoring unknown mode `%s'" mode)
1648 (setq done t)
1649 (funcall mode))))
d0fc03ef
RS
1650 ;; If we didn't find a mode from a -*- line, try using the file name.
1651 (if (and (not done) buffer-file-name)
1652 (let ((name buffer-file-name)
1653 (keep-going t))
1654 ;; Remove backup-suffixes from file name.
1655 (setq name (file-name-sans-versions name))
1656 (while keep-going
1657 (setq keep-going nil)
1658 (let ((alist auto-mode-alist)
1659 (mode nil))
1660 ;; Find first matching alist entry.
76d5492b 1661 (let ((case-fold-search
d0fc03ef
RS
1662 (memq system-type '(vax-vms windows-nt))))
1663 (while (and (not mode) alist)
1664 (if (string-match (car (car alist)) name)
1665 (if (and (consp (cdr (car alist)))
1666 (nth 2 (car alist)))
ffc0e1ca
AS
1667 (setq mode (car (cdr (car alist)))
1668 name (substring name 0 (match-beginning 0))
1669 keep-going t)
d0fc03ef
RS
1670 (setq mode (cdr (car alist))
1671 keep-going nil)))
1672 (setq alist (cdr alist))))
1673 (if mode
3b9ffb77
RS
1674 ;; When JUST-FROM-FILE-NAME is set,
1675 ;; we are working on behalf of set-visited-file-name.
1676 ;; In that case, if the major mode specified is the
1677 ;; same one we already have, don't actually reset it.
1678 ;; We don't want to lose minor modes such as Font Lock.
1679 (unless (and just-from-file-name (eq mode major-mode))
1680 (funcall mode))
d0fc03ef
RS
1681 ;; If we can't deduce a mode from the file name,
1682 ;; look for an interpreter specified in the first line.
1540e4e9
KH
1683 ;; As a special case, allow for things like "#!/bin/env perl",
1684 ;; which finds the interpreter anywhere in $PATH.
d0fc03ef
RS
1685 (let ((interpreter
1686 (save-excursion
1687 (goto-char (point-min))
ffc0e1ca
AS
1688 (if (looking-at auto-mode-interpreter-regexp)
1689 (match-string 2)
d0fc03ef
RS
1690 "")))
1691 elt)
1692 ;; Map interpreter name to a mode.
1693 (setq elt (assoc (file-name-nondirectory interpreter)
1694 interpreter-mode-alist))
9de9b6a2
RS
1695 (unless just-from-file-name
1696 (if elt
1697 (funcall (cdr elt))))))))))))
b4da00e9 1698
f3e23606 1699(defun hack-local-variables-prop-line ()
ffc0e1ca
AS
1700 "Set local variables specified in the -*- line.
1701Ignore any specification for `mode:' and `coding:';
1702`set-auto-mode' should already have handled `mode:',
1703`set-auto-coding' should already have handled `coding:'."
f3e23606
RS
1704 (save-excursion
1705 (goto-char (point-min))
13a66180 1706 (let ((result nil)
aa5fcebf
KH
1707 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point)))
1708 (enable-local-variables
1709 (and local-enable-local-variables enable-local-variables)))
f3e23606
RS
1710 ;; Parse the -*- line into the `result' alist.
1711 (cond ((not (search-forward "-*-" end t))
1712 ;; doesn't have one.
1713 nil)
1714 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
13a66180
KH
1715 ;; Simple form: "-*- MODENAME -*-". Already handled.
1716 nil)
f3e23606
RS
1717 (t
1718 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1719 ;; (last ";" is optional).
1720 (save-excursion
1721 (if (search-forward "-*-" end t)
1722 (setq end (- (point) 3))
1723 (error "-*- not terminated before end of line")))
1724 (while (< (point) end)
1725 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
ffc0e1ca 1726 (error "Malformed -*- line"))
f3e23606 1727 (goto-char (match-end 0))
1c26a6f3
KH
1728 ;; There used to be a downcase here,
1729 ;; but the manual didn't say so,
1730 ;; and people want to set var names that aren't all lc.
1731 (let ((key (intern (buffer-substring
1732 (match-beginning 1)
1733 (match-end 1))))
f3e23606
RS
1734 (val (save-restriction
1735 (narrow-to-region (point) end)
1736 (read (current-buffer)))))
93a2702d
RS
1737 ;; It is traditional to ignore
1738 ;; case when checking for `mode' in set-auto-mode,
1739 ;; so we must do that here as well.
1740 ;; That is inconsistent, but we're stuck with it.
3fa0a9aa 1741 ;; The same can be said for `coding' in set-auto-coding.
93a2702d 1742 (or (equal (downcase (symbol-name key)) "mode")
3fa0a9aa 1743 (equal (downcase (symbol-name key)) "coding")
13a66180 1744 (setq result (cons (cons key val) result)))
f3e23606
RS
1745 (skip-chars-forward " \t;")))
1746 (setq result (nreverse result))))
76d5492b 1747
f3e23606
RS
1748 (if (and result
1749 (or (eq enable-local-variables t)
1750 (and enable-local-variables
1751 (save-window-excursion
6f931919
RS
1752 (condition-case nil
1753 (switch-to-buffer (current-buffer))
1754 (error
1755 ;; If we fail to switch in the selected window,
1756 ;; it is probably a minibuffer.
1757 ;; So try another window.
1758 (condition-case nil
1759 (switch-to-buffer-other-window (current-buffer))
1760 (error
1761 (switch-to-buffer-other-frame (current-buffer))))))
f3e23606
RS
1762 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1763 (file-name-nondirectory buffer-file-name)))))))
2837b9df
RS
1764 (let ((enable-local-eval enable-local-eval))
1765 (while result
1766 (hack-one-local-variable (car (car result)) (cdr (car result)))
1767 (setq result (cdr result))))))))
f3e23606 1768
1d517019
RS
1769(defvar hack-local-variables-hook nil
1770 "Normal hook run after processing a file's local variables specs.
1771Major modes can use this to examine user-specified local variables
1772in order to initialize other data structure based on them.")
1773
9de9b6a2
RS
1774(defun hack-local-variables (&optional mode-only)
1775 "Parse and put into effect this buffer's local variables spec.
1776If MODE-ONLY is non-nil, all we do is check whether the major mode
1777is specified, returning t if it is specified."
1778 (unless mode-only
1779 (hack-local-variables-prop-line))
b4da00e9 1780 ;; Look for "Local variables:" line in last page.
aa5fcebf
KH
1781 (let (mode-specified
1782 (enable-local-variables
1783 (and local-enable-local-variables enable-local-variables)))
9de9b6a2
RS
1784 (save-excursion
1785 (goto-char (point-max))
1786 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1787 (if (let ((case-fold-search t))
1788 (and (search-forward "Local Variables:" nil t)
1789 (or (eq enable-local-variables t)
1790 mode-only
1791 (and enable-local-variables
1792 (save-window-excursion
1793 (switch-to-buffer (current-buffer))
1794 (save-excursion
1795 (beginning-of-line)
1796 (set-window-start (selected-window) (point)))
1797 (y-or-n-p (format "Set local variables as specified at end of %s? "
1798 (if buffer-file-name
1799 (file-name-nondirectory
1800 buffer-file-name)
1801 (concat "buffer "
1802 (buffer-name))))))))))
1803 (let ((continue t)
1804 prefix prefixlen suffix beg
1805 mode-specified
1806 (enable-local-eval enable-local-eval))
1807 ;; The prefix is what comes before "local variables:" in its line.
1808 ;; The suffix is what comes after "local variables:" in its line.
b4da00e9 1809 (skip-chars-forward " \t")
9de9b6a2
RS
1810 (or (eolp)
1811 (setq suffix (buffer-substring (point)
1812 (progn (end-of-line) (point)))))
1813 (goto-char (match-beginning 0))
1814 (or (bolp)
1815 (setq prefix
1816 (buffer-substring (point)
1817 (progn (beginning-of-line) (point)))))
1818
1819 (if prefix (setq prefixlen (length prefix)
1820 prefix (regexp-quote prefix)))
1821 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1822 (while continue
1823 ;; Look at next local variable spec.
1824 (if selective-display (re-search-forward "[\n\C-m]")
1825 (forward-line 1))
1826 ;; Skip the prefix, if any.
1827 (if prefix
1828 (if (looking-at prefix)
1829 (forward-char prefixlen)
1830 (error "Local variables entry is missing the prefix")))
1831 ;; Find the variable name; strip whitespace.
1832 (skip-chars-forward " \t")
1833 (setq beg (point))
1834 (skip-chars-forward "^:\n")
1835 (if (eolp) (error "Missing colon in local variables entry"))
1836 (skip-chars-backward " \t")
1837 (let* ((str (buffer-substring beg (point)))
1838 (var (read str))
1839 val)
1840 ;; Setting variable named "end" means end of list.
1841 (if (string-equal (downcase str) "end")
1842 (setq continue nil)
1843 ;; Otherwise read the variable value.
1844 (skip-chars-forward "^:")
1845 (forward-char 1)
1846 (setq val (read (current-buffer)))
1847 (skip-chars-backward "\n")
1848 (skip-chars-forward " \t")
1849 (or (if suffix (looking-at suffix) (eolp))
1850 (error "Local variables entry is terminated incorrectly"))
1851 (if mode-only
1852 (if (eq var 'mode)
1853 (setq mode-specified t))
1854 ;; Set the variable. "Variables" mode and eval are funny.
1855 (hack-one-local-variable var val))))))))
1856 (unless mode-only
1857 (run-hooks 'hack-local-variables-hook))
1858 mode-specified))
f3e23606 1859
d7fa5aa2 1860(defvar ignored-local-variables
f3e23606
RS
1861 '(enable-local-eval)
1862 "Variables to be ignored in a file's local variable spec.")
1863
be0218a8 1864;; Get confirmation before setting these variables as locals in a file.
05ef1cda 1865(put 'debugger 'risky-local-variable t)
f6fa3ee3 1866(put 'enable-local-eval 'risky-local-variable t)
fce47eea 1867(put 'ignored-local-variables 'risky-local-variable t)
be0218a8
RS
1868(put 'eval 'risky-local-variable t)
1869(put 'file-name-handler-alist 'risky-local-variable t)
1870(put 'minor-mode-map-alist 'risky-local-variable t)
1871(put 'after-load-alist 'risky-local-variable t)
f6fa3ee3
RS
1872(put 'buffer-file-name 'risky-local-variable t)
1873(put 'buffer-auto-save-file-name 'risky-local-variable t)
1874(put 'buffer-file-truename 'risky-local-variable t)
b0ffcc0d
RS
1875(put 'exec-path 'risky-local-variable t)
1876(put 'load-path 'risky-local-variable t)
1877(put 'exec-directory 'risky-local-variable t)
1878(put 'process-environment 'risky-local-variable t)
eba1c87a
RS
1879(put 'dabbrev-case-fold-search 'risky-local-variable t)
1880(put 'dabbrev-case-replace 'risky-local-variable t)
9afa8bf7
RS
1881;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1882(put 'outline-level 'risky-local-variable t)
d98b741d 1883(put 'rmail-output-file-alist 'risky-local-variable t)
f6fa3ee3 1884
6672c42b
RS
1885;; This one is safe because the user gets to check it before it is used.
1886(put 'compile-command 'safe-local-variable t)
1887
d0bd3513
RS
1888(defun hack-one-local-variable-quotep (exp)
1889 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1890
f3e23606 1891(defun hack-one-local-variable (var val)
ffc0e1ca
AS
1892 "\"Set\" one variable in a local variables spec.
1893A few variable names are treated specially."
f3e23606
RS
1894 (cond ((eq var 'mode)
1895 (funcall (intern (concat (downcase (symbol-name val))
1896 "-mode"))))
3fa0a9aa
KH
1897 ((eq var 'coding)
1898 ;; We have already handled coding: tag in set-auto-coding.
1899 nil)
f3e23606
RS
1900 ((memq var ignored-local-variables)
1901 nil)
1902 ;; "Setting" eval means either eval it or do nothing.
7d3221d7 1903 ;; Likewise for setting hook variables.
be0218a8 1904 ((or (get var 'risky-local-variable)
6672c42b 1905 (and
04d807e6 1906 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$\\|-predicate$"
6672c42b
RS
1907 (symbol-name var))
1908 (not (get var 'safe-local-variable))))
0225ae5e 1909 ;; Permit evalling a put of a harmless property.
d0bd3513
RS
1910 ;; if the args do nothing tricky.
1911 (if (or (and (eq var 'eval)
1912 (consp val)
1913 (eq (car val) 'put)
1914 (hack-one-local-variable-quotep (nth 1 val))
1915 (hack-one-local-variable-quotep (nth 2 val))
1916 ;; Only allow safe values of lisp-indent-hook;
1917 ;; not functions.
1918 (or (numberp (nth 3 val))
dc417415 1919 (equal (nth 3 val) ''defun))
d0bd3513
RS
1920 (memq (nth 1 (nth 2 val))
1921 '(lisp-indent-hook)))
1922 ;; Permit eval if not root and user says ok.
c7e62660 1923 (and (not (zerop (user-uid)))
d0bd3513
RS
1924 (or (eq enable-local-eval t)
1925 (and enable-local-eval
1926 (save-window-excursion
1927 (switch-to-buffer (current-buffer))
1928 (save-excursion
1929 (beginning-of-line)
1930 (set-window-start (selected-window) (point)))
1931 (setq enable-local-eval
abf16d5e
RS
1932 (y-or-n-p (format "Process `eval' or hook local variables in %s? "
1933 (if buffer-file-name
1934 (concat "file " (file-name-nondirectory buffer-file-name))
1935 (concat "buffer " (buffer-name)))))))))))
7d3221d7
RS
1936 (if (eq var 'eval)
1937 (save-excursion (eval val))
1938 (make-local-variable var)
1939 (set var val))
abf16d5e 1940 (message "Ignoring `eval:' in the local variables list")))
f3e23606
RS
1941 ;; Ordinary variable, really set it.
1942 (t (make-local-variable var)
1943 (set var val))))
1944
b4da00e9 1945\f
21540597 1946(defcustom change-major-mode-with-file-name t
9de9b6a2
RS
1947 "*Non-nil means \\[write-file] should set the major mode from the file name.
1948However, the mode will not be changed if
1949\(1) a local variables list or the `-*-' line specifies a major mode, or
1950\(2) the current major mode is a \"special\" mode,
8609911b 1951\ not suitable for ordinary files, or
21540597
RS
1952\(3) the new file name does not particularly specify any mode."
1953 :type 'boolean
1954 :group 'editing-basics)
9de9b6a2 1955
f36012a6 1956(defun set-visited-file-name (filename &optional no-query along-with-file)
b4da00e9
RM
1957 "Change name of file visited in current buffer to FILENAME.
1958The next time the buffer is saved it will go in the newly specified file.
1959nil or empty string as argument means make buffer not be visiting any file.
1960Remember to delete the initial contents of the minibuffer
6a6b62f8
RS
1961if you wish to pass an empty string as the argument.
1962
1963The optional second argument NO-QUERY, if non-nil, inhibits asking for
f36012a6
RS
1964confirmation in the case where another buffer is already visiting FILENAME.
1965
1966The optional third argument ALONG-WITH-FILE, if non-nil, means that
1967the old visited file has been renamed to the new name FILENAME."
b4da00e9 1968 (interactive "FSet visited file name: ")
c11a94fe
RS
1969 (if (buffer-base-buffer)
1970 (error "An indirect buffer cannot visit a file"))
a522e5bf
RS
1971 (let (truename)
1972 (if filename
1973 (setq filename
1974 (if (string-equal filename "")
1975 nil
1976 (expand-file-name filename))))
1977 (if filename
1978 (progn
1979 (setq truename (file-truename filename))
1980 (if find-file-visit-truename
a522e5bf 1981 (setq filename truename))))
11e314fa 1982 (let ((buffer (and filename (find-buffer-visiting filename))))
7b89d38e 1983 (and buffer (not (eq buffer (current-buffer)))
6a6b62f8 1984 (not no-query)
7b89d38e
RS
1985 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1986 filename)))
1987 (error "Aborted")))
a522e5bf
RS
1988 (or (equal filename buffer-file-name)
1989 (progn
1990 (and filename (lock-buffer filename))
1991 (unlock-buffer)))
1992 (setq buffer-file-name filename)
1993 (if filename ; make buffer name reflect filename.
1994 (let ((new-name (file-name-nondirectory buffer-file-name)))
1995 (if (string= new-name "")
1996 (error "Empty file name"))
1997 (if (eq system-type 'vax-vms)
1998 (setq new-name (downcase new-name)))
1999 (setq default-directory (file-name-directory buffer-file-name))
2000 (or (string= new-name (buffer-name))
2001 (rename-buffer new-name t))))
2002 (setq buffer-backed-up nil)
f36012a6
RS
2003 (or along-with-file
2004 (clear-visited-file-modtime))
8ccdc29e 2005 ;; Abbreviate the file names of the buffer.
4826e97f 2006 (if truename
8ccdc29e
RS
2007 (progn
2008 (setq buffer-file-truename (abbreviate-file-name truename))
2009 (if find-file-visit-truename
2010 (setq buffer-file-name buffer-file-truename))))
a522e5bf
RS
2011 (setq buffer-file-number
2012 (if filename
2a47b4f5 2013 (nthcdr 10 (file-attributes buffer-file-name))
a522e5bf 2014 nil)))
b4da00e9
RM
2015 ;; write-file-hooks is normally used for things like ftp-find-file
2016 ;; that visit things that are not local files as if they were files.
2017 ;; Changing to visit an ordinary local file instead should flush the hook.
2018 (kill-local-variable 'write-file-hooks)
c9dca4e0 2019 (kill-local-variable 'local-write-file-hooks)
b4da00e9
RM
2020 (kill-local-variable 'revert-buffer-function)
2021 (kill-local-variable 'backup-inhibited)
ee81c959
RS
2022 ;; If buffer was read-only because of version control,
2023 ;; that reason is gone now, so make it writable.
2024 (if vc-mode
2025 (setq buffer-read-only nil))
2026 (kill-local-variable 'vc-mode)
b4da00e9
RM
2027 ;; Turn off backup files for certain file names.
2028 ;; Since this is a permanent local, the major mode won't eliminate it.
4d49551a
KH
2029 (and buffer-file-name
2030 (not (funcall backup-enable-predicate buffer-file-name))
b4da00e9
RM
2031 (progn
2032 (make-local-variable 'backup-inhibited)
2033 (setq backup-inhibited t)))
c77a81cf
RS
2034 (let ((oauto buffer-auto-save-file-name))
2035 ;; If auto-save was not already on, turn it on if appropriate.
2036 (if (not buffer-auto-save-file-name)
2037 (and buffer-file-name auto-save-default
2038 (auto-save-mode t))
2039 ;; If auto save is on, start using a new name.
2040 ;; We deliberately don't rename or delete the old auto save
2041 ;; for the old visited file name. This is because perhaps
2042 ;; the user wants to save the new state and then compare with the
2043 ;; previous state from the auto save file.
2044 (setq buffer-auto-save-file-name
2045 (make-auto-save-file-name)))
2046 ;; Rename the old auto save file if any.
2047 (and oauto buffer-auto-save-file-name
e6f0e76c 2048 (file-exists-p oauto)
c77a81cf 2049 (rename-file oauto buffer-auto-save-file-name t)))
f36012a6
RS
2050 (and buffer-file-name
2051 (not along-with-file)
9de9b6a2
RS
2052 (set-buffer-modified-p t))
2053 ;; Update the major mode, if the file name determines it.
2054 (condition-case nil
2055 ;; Don't change the mode if it is special.
2056 (or (not change-major-mode-with-file-name)
2057 (get major-mode 'mode-class)
2058 ;; Don't change the mode if the local variable list specifies it.
2059 (hack-local-variables t)
2060 (set-auto-mode t))
2061 (error nil)))
b4da00e9 2062
912192d1 2063(defun write-file (filename &optional confirm)
b4da00e9 2064 "Write current buffer into file FILENAME.
7f99999a 2065This makes the buffer visit that file, and marks it as not modified.
7458cc35 2066
7f99999a
KH
2067If you specify just a directory name as FILENAME, that means to use
2068the default file name but in that directory. You can also yank
2069the default file name into the minibuffer to edit it, using M-n.
2070
2071If the buffer is not already visiting a file, the default file name
2072for the output file is the buffer name.
2073
2074If optional second arg CONFIRM is non-nil, this function
2075asks for confirmation before overwriting an existing file.
912192d1 2076Interactively, confirmation is required unless you supply a prefix argument."
b4da00e9
RM
2077;; (interactive "FWrite file: ")
2078 (interactive
2079 (list (if buffer-file-name
2080 (read-file-name "Write file: "
2081 nil nil nil nil)
7f99999a
KH
2082 (read-file-name "Write file: " default-directory
2083 (expand-file-name
2084 (file-name-nondirectory (buffer-name))
2085 default-directory)
2086 nil nil))
912192d1 2087 (not current-prefix-arg)))
b4da00e9 2088 (or (null filename) (string-equal filename "")
41f48cb1
RS
2089 (progn
2090 ;; If arg is just a directory,
7f99999a
KH
2091 ;; use the default file name, but in that directory.
2092 (if (file-directory-p filename)
41f48cb1 2093 (setq filename (concat (file-name-as-directory filename)
7f99999a
KH
2094 (file-name-nondirectory
2095 (or buffer-file-name (buffer-name))))))
c2fb8488
RS
2096 (and confirm
2097 (file-exists-p filename)
2098 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
2099 (error "Canceled")))
5f65549e 2100 (set-visited-file-name filename (not confirm))))
b4da00e9 2101 (set-buffer-modified-p t)
6492b55d
KH
2102 ;; Make buffer writable if file is writable.
2103 (and buffer-file-name
2104 (file-writable-p buffer-file-name)
2105 (setq buffer-read-only nil))
912192d1 2106 (save-buffer))
b4da00e9
RM
2107\f
2108(defun backup-buffer ()
2109 "Make a backup of the disk file visited by the current buffer, if appropriate.
2110This is normally done before saving the buffer the first time.
2111If the value is non-nil, it is the result of `file-modes' on the original
2112file; this means that the caller, after saving the buffer, should change
27ab6944
KH
2113the modes of the new file to agree with the old modes.
2114
2115A backup may be done by renaming or by copying; see documentation of
2116variable `make-backup-files'. If it's done by renaming, then the file is
2117no longer accessible under its old name."
b4da00e9
RM
2118 (if (and make-backup-files (not backup-inhibited)
2119 (not buffer-backed-up)
2120 (file-exists-p buffer-file-name)
2121 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
2122 '(?- ?l)))
2123 (let ((real-file-name buffer-file-name)
2124 backup-info backupname targets setmodes)
2125 ;; If specified name is a symbolic link, chase it to the target.
2126 ;; Thus we make the backups in the directory where the real file is.
5dadeb29 2127 (setq real-file-name (file-chase-links real-file-name))
b4da00e9
RM
2128 (setq backup-info (find-backup-file-name real-file-name)
2129 backupname (car backup-info)
2130 targets (cdr backup-info))
5c6d31a4
SM
2131 ;; (if (file-directory-p buffer-file-name)
2132 ;; (error "Cannot save buffer in directory %s" buffer-file-name))
eb650569
RS
2133 (if backup-info
2134 (condition-case ()
2135 (let ((delete-old-versions
2136 ;; If have old versions to maybe delete,
2137 ;; ask the user to confirm now, before doing anything.
2138 ;; But don't actually delete til later.
2139 (and targets
2140 (or (eq delete-old-versions t) (eq delete-old-versions nil))
2141 (or delete-old-versions
2142 (y-or-n-p (format "Delete excess backup versions of %s? "
2143 real-file-name))))))
2144 ;; Actually write the back up file.
2145 (condition-case ()
2146 (if (or file-precious-flag
ffc0e1ca 2147 ; (file-symlink-p buffer-file-name)
eb650569
RS
2148 backup-by-copying
2149 (and backup-by-copying-when-linked
2150 (> (file-nlinks real-file-name) 1))
ffc0e1ca
AS
2151 (and (or backup-by-copying-when-mismatch
2152 (integerp backup-by-copying-when-privileged-mismatch))
eb650569 2153 (let ((attr (file-attributes real-file-name)))
ffc0e1ca
AS
2154 (and (or backup-by-copying-when-mismatch
2155 (and (integerp (nth 2 attr))
2156 (integerp backup-by-copying-when-privileged-mismatch)
2157 (<= (nth 2 attr) backup-by-copying-when-privileged-mismatch)))
2158 (or (nth 9 attr)
2159 (not (file-ownership-preserved-p real-file-name)))))))
eb650569
RS
2160 (condition-case ()
2161 (copy-file real-file-name backupname t t)
2162 (file-error
2163 ;; If copying fails because file BACKUPNAME
2164 ;; is not writable, delete that file and try again.
2165 (if (and (file-exists-p backupname)
2166 (not (file-writable-p backupname)))
2167 (delete-file backupname))
2168 (copy-file real-file-name backupname t t)))
2169 ;; rename-file should delete old backup.
2170 (rename-file real-file-name backupname t)
2171 (setq setmodes (file-modes backupname)))
2172 (file-error
2173 ;; If trouble writing the backup, write it in ~.
567c1ca9
RS
2174 (setq backupname (expand-file-name
2175 (convert-standard-filename
2176 "~/%backup%~")))
2177 (message "Cannot write backup file; backing up in %s"
2178 (file-name-nondirectory backupname))
eb650569
RS
2179 (sleep-for 1)
2180 (condition-case ()
2181 (copy-file real-file-name backupname t t)
2182 (file-error
2183 ;; If copying fails because file BACKUPNAME
2184 ;; is not writable, delete that file and try again.
2185 (if (and (file-exists-p backupname)
2186 (not (file-writable-p backupname)))
2187 (delete-file backupname))
2188 (copy-file real-file-name backupname t t)))))
2189 (setq buffer-backed-up t)
2190 ;; Now delete the old versions, if desired.
2191 (if delete-old-versions
2192 (while targets
2193 (condition-case ()
2194 (delete-file (car targets))
2195 (file-error nil))
2196 (setq targets (cdr targets))))
2197 setmodes)
2198 (file-error nil))))))
b4da00e9 2199
c3554e95 2200(defun file-name-sans-versions (name &optional keep-backup-version)
ffc0e1ca 2201 "Return file NAME sans backup versions or strings.
b4da00e9 2202This is a separate procedure so your site-init or startup file can
c3554e95
RS
2203redefine it.
2204If the optional argument KEEP-BACKUP-VERSION is non-nil,
2205we do not remove backup version numbers, only true file version numbers."
6eaebaa2 2206 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
c3554e95
RS
2207 (if handler
2208 (funcall handler 'file-name-sans-versions name keep-backup-version)
2209 (substring name 0
2210 (if (eq system-type 'vax-vms)
2211 ;; VMS version number is (a) semicolon, optional
2212 ;; sign, zero or more digits or (b) period, option
2213 ;; sign, zero or more digits, provided this is the
2214 ;; second period encountered outside of the
2215 ;; device/directory part of the file name.
26add1bf
KH
2216 (or (string-match ";[-+]?[0-9]*\\'" name)
2217 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
c3554e95
RS
2218 name)
2219 (match-beginning 1))
2220 (length name))
2221 (if keep-backup-version
2222 (length name)
dbb12f2c 2223 (or (string-match "\\.~[0-9.]+~\\'" name)
c3554e95
RS
2224 (string-match "~\\'" name)
2225 (length name))))))))
b4da00e9 2226
cb0cd911 2227(defun file-ownership-preserved-p (file)
ffc0e1ca 2228 "Return t if deleting FILE and rewriting it would preserve the owner."
cb0cd911
RS
2229 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
2230 (if handler
2231 (funcall handler 'file-ownership-preserved-p file)
ec5533be 2232 (let ((attributes (file-attributes file)))
306faa42
RS
2233 ;; Return t if the file doesn't exist, since it's true that no
2234 ;; information would be lost by an (attempted) delete and create.
2235 (or (null attributes)
2236 (= (nth 2 attributes) (user-uid)))))))
cb0cd911 2237
20b5d24c
RS
2238(defun file-name-sans-extension (filename)
2239 "Return FILENAME sans final \"extension\".
2240The extension, in a file name, is the part that follows the last `.'."
2241 (save-match-data
2242 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
2243 directory)
2244 (if (string-match "\\.[^.]*\\'" file)
2245 (if (setq directory (file-name-directory filename))
2246 (expand-file-name (substring file 0 (match-beginning 0))
2247 directory)
2248 (substring file 0 (match-beginning 0)))
2249 filename))))
2250
93a2702d
RS
2251(defun file-name-extension (filename &optional period)
2252 "Return FILENAME's final \"extension\".
2253The extension, in a file name, is the part that follows the last `.'.
2254Return nil for extensionless file names such as `foo'.
2255Return the empty string for file names such as `foo.'.
2256
2257If PERIOD is non-nil, then the returned value includes the period
2258that delimits the extension, and if FILENAME has no extension,
2259the value is \"\"."
2260 (save-match-data
2261 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
2262 (if (string-match "\\.[^.]*\\'" file)
2263 (substring file (+ (match-beginning 0) (if period 0 1)))
2264 (if period
2265 "")))))
2266
ffc0e1ca
AS
2267(defcustom make-backup-file-name-function nil
2268 "A function to use instead of the default `make-backup-file-name'.
2269A value of nil gives the default `make-backup-file-name' behaviour.
2270
d5798fa7 2271This could be buffer-local to do something special for specific
ffc0e1ca
AS
2272files. If you define it, you may need to change `backup-file-name-p'
2273and `file-name-sans-versions' too.
2274
2275See also `backup-directory-alist'."
2276 :group 'backup
2277 :type '(choice (const :tag "Default" nil)
2278 (function :tag "Your function")))
2279
2280(defcustom backup-directory-alist nil
2281 "Alist of filename patterns and backup directory names.
2282Each element looks like (REGEXP . DIRECTORY). Backups of files with
2283names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
2284relative or absolute. If it is absolute, so that all matching files
2285are backed up into the same directory, the file names in this
2286directory will be the full name of the file backed up with all
2287directory separators changed to `!' to prevent clashes. This will not
2288work correctly if your filesystem truncates the resulting name.
2289
2290For the common case of all backups going into one directory, the alist
2291should contain a single element pairing \".\" with the appropriate
2292directory name.
2293
2294If this variable is nil, or it fails to match a filename, the backup
2295is made in the original file's directory.
2296
2297On MS-DOS filesystems without long names this variable is always
2298ignored."
2299 :group 'backup
dca5e71d 2300 :type '(repeat (cons (regexp :tag "Regexp matching filename")
ffc0e1ca
AS
2301 (directory :tag "Backup directory name"))))
2302
b4da00e9
RM
2303(defun make-backup-file-name (file)
2304 "Create the non-numeric backup file name for FILE.
ffc0e1ca
AS
2305Normally this will just be the file's name with `~' appended.
2306Customization hooks are provided as follows.
2307
2308If the variable `make-backup-file-name-function' is non-nil, its value
2309should be a function which will be called with FILE as its argument;
2310the resulting name is used.
2311
2312Otherwise a match for FILE is sought in `backup-directory-alist'; see
2313the documentation of that variable. If the directory for the backup
2314doesn't exist, it is created."
2315 (if make-backup-file-name-function
2316 (funcall make-backup-file-name-function file)
2317 (if (and (eq system-type 'ms-dos)
2318 (not (msdos-long-file-names)))
2319 (let ((fn (file-name-nondirectory file)))
2320 (concat (file-name-directory file)
2321 (or (and (string-match "\\`[^.]+\\'" fn)
2322 (concat (match-string 0 fn) ".~"))
2323 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
2324 (concat (match-string 0 fn) "~")))))
2325 (concat (make-backup-file-name-1 file) "~"))))
2326
2327(defun make-backup-file-name-1 (file)
2328 "Subroutine of `make-backup-file-name' and `find-backup-file-name'."
2329 (let ((alist backup-directory-alist)
2330 elt backup-directory dir-sep-string)
2331 (while alist
2332 (setq elt (pop alist))
2333 (if (string-match (car elt) file)
2334 (setq backup-directory (cdr elt)
2335 alist nil)))
2336 (if (null backup-directory)
2337 file
2338 (unless (file-exists-p backup-directory)
2339 (condition-case nil
2340 (make-directory backup-directory 'parents)
2341 (file-error file)))
2342 (if (file-name-absolute-p backup-directory)
2343 (progn
2344 (when (memq system-type '(windows-nt ms-dos))
2345 ;; Normalize DOSish file names: convert all slashes to
2346 ;; directory-sep-char, downcase the drive letter, if any,
2347 ;; and replace the leading "x:" with "/drive_x".
2348 (or (file-name-absolute-p file)
2349 (setq file (expand-file-name file))) ; make defaults explicit
2350 ;; Replace any invalid file-name characters (for the
2351 ;; case of backing up remote files).
446c097e 2352 (setq file (expand-file-name (convert-standard-filename file)))
ffc0e1ca 2353 (setq dir-sep-string (char-to-string directory-sep-char))
ffc0e1ca
AS
2354 (if (eq (aref file 1) ?:)
2355 (setq file (concat dir-sep-string
2356 "drive_"
2357 (char-to-string (downcase (aref file 0)))
2358 (if (eq (aref file 2) directory-sep-char)
2359 ""
2360 dir-sep-string)
2361 (substring file 2)))))
2362 ;; Make the name unique by substituting directory
2363 ;; separators. It may not really be worth bothering about
2364 ;; doubling `!'s in the original name...
2365 (expand-file-name
2366 (subst-char-in-string
2367 directory-sep-char ?!
2368 (replace-regexp-in-string "!" "!!" file))
2369 backup-directory))
2370 (expand-file-name (file-name-nondirectory file)
2371 (file-name-as-directory
2372 (expand-file-name backup-directory
2373 (file-name-directory file))))))))
b4da00e9
RM
2374
2375(defun backup-file-name-p (file)
2376 "Return non-nil if FILE is a backup file name (numeric or not).
2377This is a separate function so you can redefine it for customization.
2378You may need to redefine `file-name-sans-versions' as well."
066327ae 2379 (string-match "~\\'" file))
b4da00e9 2380
e2b30772
RS
2381(defvar backup-extract-version-start)
2382
2d051399 2383;; This is used in various files.
a7aa942a
KH
2384;; The usage of backup-extract-version-start is not very clean,
2385;; but I can't see a good alternative, so as of now I am leaving it alone.
2d051399 2386(defun backup-extract-version (fn)
ffc0e1ca 2387 "Given the name of a numeric backup file, FN, return the backup number.
e2b30772 2388Uses the free variable `backup-extract-version-start', whose value should be
2d051399 2389the index in the name where the version number begins."
e2b30772
RS
2390 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start)
2391 (= (match-beginning 0) backup-extract-version-start))
2392 (string-to-int (substring fn backup-extract-version-start -1))
2d051399
RS
2393 0))
2394
b4da00e9
RM
2395;; I believe there is no need to alter this behavior for VMS;
2396;; since backup files are not made on VMS, it should not get called.
2397(defun find-backup-file-name (fn)
ffc0e1ca 2398 "Find a file name for a backup file FN, and suggestions for deletions.
b4da00e9 2399Value is a list whose car is the name for the backup file
ffc0e1ca
AS
2400and whose cdr is a list of old versions to consider deleting now.
2401If the value is nil, don't make a backup.
2402Uses `backup-directory-alist' in the same way as does
2403`make-backup-file-name'."
eb650569
RS
2404 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
2405 ;; Run a handler for this function so that ange-ftp can refuse to do it.
2406 (if handler
2407 (funcall handler 'find-backup-file-name fn)
f26d858e
EZ
2408 (if (or (eq version-control 'never)
2409 ;; We don't support numbered backups on plain MS-DOS
2410 ;; when long file names are unavailable.
2411 (and (eq system-type 'ms-dos)
2412 (not (msdos-long-file-names))))
b4da00e9 2413 (list (make-backup-file-name fn))
ffc0e1ca
AS
2414 (let* ((basic-name (make-backup-file-name-1 fn))
2415 (base-versions (concat (file-name-nondirectory basic-name)
2416 ".~"))
e2b30772 2417 (backup-extract-version-start (length base-versions))
eb650569 2418 (high-water-mark 0)
ffc0e1ca
AS
2419 (number-to-delete 0)
2420 possibilities deserve-versions-p versions)
eb650569
RS
2421 (condition-case ()
2422 (setq possibilities (file-name-all-completions
2423 base-versions
ffc0e1ca
AS
2424 (file-name-directory basic-name))
2425 versions (sort (mapcar #'backup-extract-version
2426 possibilities)
2427 #'<)
eb650569
RS
2428 high-water-mark (apply 'max 0 versions)
2429 deserve-versions-p (or version-control
2430 (> high-water-mark 0))
2431 number-to-delete (- (length versions)
ffc0e1ca
AS
2432 kept-old-versions
2433 kept-new-versions
2434 -1))
2435 (file-error (setq possibilities nil)))
eb650569 2436 (if (not deserve-versions-p)
ffc0e1ca
AS
2437 (list (concat basic-name "~"))
2438 (cons (format "%s.~%d~" basic-name (1+ high-water-mark))
eb650569
RS
2439 (if (and (> number-to-delete 0)
2440 ;; Delete nothing if there is overflow
2441 ;; in the number of versions to keep.
2442 (>= (+ kept-new-versions kept-old-versions -1) 0))
ffc0e1ca
AS
2443 (mapcar (lambda (n)
2444 (format "%s.~%d~" basic-name n))
eb650569
RS
2445 (let ((v (nthcdr kept-old-versions versions)))
2446 (rplacd (nthcdr (1- number-to-delete) v) ())
2447 v))))))))))
b4da00e9 2448
b4da00e9
RM
2449(defun file-nlinks (filename)
2450 "Return number of names file FILENAME has."
2451 (car (cdr (file-attributes filename))))
6c636af9
RM
2452
2453(defun file-relative-name (filename &optional directory)
ffc0e1ca 2454 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
2d6562a5
RS
2455This function returns a relative file name which is equivalent to FILENAME
2456when used with that default directory as the default.
2457If this is impossible (which can happen on MSDOS and Windows
2458when the file name and directory use different drive names)
2459then it returns FILENAME."
96c188b0 2460 (save-match-data
e2b30772
RS
2461 (let ((fname (expand-file-name filename)))
2462 (setq directory (file-name-as-directory
2463 (expand-file-name (or directory default-directory))))
2464 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2465 ;; drive names, they can't be relative, so return the absolute name.
2466 (if (and (or (eq system-type 'ms-dos)
2467 (eq system-type 'windows-nt))
2468 (not (string-equal (substring fname 0 2)
2469 (substring directory 0 2))))
2470 filename
9695aac6
RS
2471 (let ((ancestor ".")
2472 (fname-dir (file-name-as-directory fname)))
2473 (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
2474 (not (string-match (concat "^" (regexp-quote directory)) fname)))
e2b30772 2475 (setq directory (file-name-directory (substring directory 0 -1))
9695aac6
RS
2476 ancestor (if (equal ancestor ".")
2477 ".."
2478 (concat "../" ancestor))))
2479 ;; Now ancestor is empty, or .., or ../.., etc.
2480 (if (string-match (concat "^" (regexp-quote directory)) fname)
2481 ;; We matched within FNAME's directory part.
2482 ;; Add the rest of FNAME onto ANCESTOR.
2483 (let ((rest (substring fname (match-end 0))))
2484 (if (and (equal ancestor ".")
2485 (not (equal rest "")))
2486 ;; But don't bother with ANCESTOR if it would give us `./'.
2487 rest
2488 (concat (file-name-as-directory ancestor) rest)))
2489 ;; We matched FNAME's directory equivalent.
2490 ancestor))))))
b4da00e9
RM
2491\f
2492(defun save-buffer (&optional args)
2493 "Save current buffer in visited file if modified. Versions described below.
2494By default, makes the previous version into a backup file
2495 if previously requested or if this is the first save.
ac9650be 2496With 1 \\[universal-argument], marks this version
b4da00e9 2497 to become a backup when the next save is done.
ac9650be 2498With 2 \\[universal-argument]'s,
b4da00e9 2499 unconditionally makes the previous version into a backup file.
ac9650be
RS
2500With 3 \\[universal-argument]'s, marks this version
2501 to become a backup when the next save is done,
2502 and unconditionally makes the previous version into a backup file.
2503
749d2ee6 2504With argument of 0, never make the previous version into a backup file.
b4da00e9
RM
2505
2506If a file's name is FOO, the names of its numbered backup versions are
2507 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2508Numeric backups (rather than FOO~) will be made if value of
2509 `version-control' is not the atom `never' and either there are already
2510 numeric versions of the file being backed up, or `version-control' is
2511 non-nil.
2512We don't want excessive versions piling up, so there are variables
2513 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2514 and `kept-new-versions', which tells how many newest versions to keep.
2515 Defaults are 2 old versions and 2 new.
2516`dired-kept-versions' controls dired's clean-directory (.) command.
de7d5e1b 2517If `delete-old-versions' is nil, system will query user
e73ec04b
RS
2518 before trimming versions. Otherwise it does it silently.
2519
749d2ee6
RS
2520If `vc-make-backup-files' is nil, which is the default,
2521 no backup files are made for files managed by version control.
2522 (This is because the version control system itself records previous versions.)
2523
e73ec04b 2524See the subroutine `basic-save-buffer' for more information."
b4da00e9
RM
2525 (interactive "p")
2526 (let ((modp (buffer-modified-p))
2527 (large (> (buffer-size) 50000))
b5a8e0fc
RS
2528 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2529 (memq args '(16 64)))))
b4da00e9 2530 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
b4990dde
GM
2531 (if (and modp large (buffer-file-name))
2532 (message "Saving file %s..." (buffer-file-name)))
b4da00e9
RM
2533 (basic-save-buffer)
2534 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2535
2536(defun delete-auto-save-file-if-necessary (&optional force)
2537 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2538Normally delete only if the file was written by this Emacs since
2539the last real save, but optional arg FORCE non-nil means delete anyway."
2540 (and buffer-auto-save-file-name delete-auto-save-files
2541 (not (string= buffer-file-name buffer-auto-save-file-name))
2542 (or force (recent-auto-save-p))
2543 (progn
2544 (condition-case ()
2545 (delete-file buffer-auto-save-file-name)
2546 (file-error nil))
2547 (set-buffer-auto-saved))))
2548
481f215b
KH
2549(defvar auto-save-hook nil
2550 "Normal hook run just before auto-saving.")
2551
ffc0e1ca
AS
2552(defcustom after-save-hook nil
2553 "Normal hook that is run after a buffer is saved to its file."
2554 :options '(executable-make-buffer-file-executable-if-script-p)
2555 :type 'hook
2556 :group 'files)
1cc852cc 2557
0516edee
RS
2558(defvar save-buffer-coding-system nil
2559 "If non-nil, use this coding system for saving the buffer.
2560More precisely, use this coding system in place of the
2561value of `buffer-file-coding-system', when saving the buffer.
2562Calling `write-region' for any purpose other than saving the buffer
2563will still use `buffer-file-coding-system'; this variable has no effect
2564in such cases.")
2565
d5fe94cc
RS
2566(make-variable-buffer-local 'save-buffer-coding-system)
2567(put 'save-buffer-coding-system 'permanent-local t)
2568
b4da00e9 2569(defun basic-save-buffer ()
1cc852cc 2570 "Save the current buffer in its visited file, if it has been modified.
e73ec04b
RS
2571The hooks `write-contents-hooks', `local-write-file-hooks' and
2572`write-file-hooks' get a chance to do the job of saving; if they do not,
2573then the buffer is saved in the visited file file in the usual way.
2574After saving the buffer, this function runs `after-save-hook'."
b4da00e9 2575 (interactive)
19618231 2576 (save-current-buffer
c11a94fe
RS
2577 ;; In an indirect buffer, save its base buffer instead.
2578 (if (buffer-base-buffer)
2579 (set-buffer (buffer-base-buffer)))
2580 (if (buffer-modified-p)
2581 (let ((recent-save (recent-auto-save-p))
2582 setmodes tempsetmodes)
2583 ;; On VMS, rename file and buffer to get rid of version number.
2584 (if (and (eq system-type 'vax-vms)
2585 (not (string= buffer-file-name
2586 (file-name-sans-versions buffer-file-name))))
2587 (let (buffer-new-name)
2588 ;; Strip VMS version number before save.
2589 (setq buffer-file-name
2590 (file-name-sans-versions buffer-file-name))
2591 ;; Construct a (unique) buffer name to correspond.
2592 (let ((buf (create-file-buffer (downcase buffer-file-name))))
2593 (setq buffer-new-name (buffer-name buf))
2594 (kill-buffer buf))
2595 (rename-buffer buffer-new-name)))
2596 ;; If buffer has no file name, ask user for one.
2597 (or buffer-file-name
182891ef
RS
2598 (let ((filename
2599 (expand-file-name
2600 (read-file-name "File to save in: ") nil)))
2601 (and (file-exists-p filename)
2602 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2603 filename))
2604 (error "Canceled")))
2605 (set-visited-file-name filename)))
c11a94fe
RS
2606 (or (verify-visited-file-modtime (current-buffer))
2607 (not (file-exists-p buffer-file-name))
2608 (yes-or-no-p
2609 (format "%s has changed since visited or saved. Save anyway? "
2610 (file-name-nondirectory buffer-file-name)))
2611 (error "Save not confirmed"))
2612 (save-restriction
2613 (widen)
19618231
RS
2614 (save-excursion
2615 (and (> (point-max) 1)
407b4328 2616 (not find-file-literally)
19618231
RS
2617 (/= (char-after (1- (point-max))) ?\n)
2618 (not (and (eq selective-display t)
2619 (= (char-after (1- (point-max))) ?\r)))
2620 (or (eq require-final-newline t)
2621 (and require-final-newline
2622 (y-or-n-p
2623 (format "Buffer %s does not end in newline. Add one? "
2624 (buffer-name)))))
2625 (save-excursion
2626 (goto-char (point-max))
2627 (insert ?\n))))
fa5867f6
AS
2628 ;; Support VC version backups.
2629 (vc-before-save)
c11a94fe
RS
2630 (or (run-hook-with-args-until-success 'write-contents-hooks)
2631 (run-hook-with-args-until-success 'local-write-file-hooks)
2632 (run-hook-with-args-until-success 'write-file-hooks)
2633 ;; If a hook returned t, file is already "written".
2634 ;; Otherwise, write it the usual way now.
2635 (setq setmodes (basic-save-buffer-1)))
d6e8ea6f
KH
2636 ;; Now we have saved the current buffer. Let's make sure
2637 ;; that buffer-file-coding-system is fixed to what
2638 ;; actually used for saving by binding it locally.
0516edee
RS
2639 (if save-buffer-coding-system
2640 (setq save-buffer-coding-system last-coding-system-used)
2641 (setq buffer-file-coding-system last-coding-system-used))
2a47b4f5
RS
2642 (setq buffer-file-number
2643 (nthcdr 10 (file-attributes buffer-file-name)))
c11a94fe
RS
2644 (if setmodes
2645 (condition-case ()
2646 (set-file-modes buffer-file-name setmodes)
2647 (error nil))))
2648 ;; If the auto-save file was recent before this command,
2649 ;; delete it now.
2650 (delete-auto-save-file-if-necessary recent-save)
49530862
RS
2651 ;; Support VC `implicit' locking.
2652 (vc-after-save)
c11a94fe
RS
2653 (run-hooks 'after-save-hook))
2654 (message "(No changes need to be saved)"))))
b4da00e9 2655
87d26afc
RS
2656;; This does the "real job" of writing a buffer into its visited file
2657;; and making a backup file. This is what is normally done
2658;; but inhibited if one of write-file-hooks returns non-nil.
2659;; It returns a value to store in setmodes.
2660(defun basic-save-buffer-1 ()
d5fe94cc
RS
2661 (if save-buffer-coding-system
2662 (let ((coding-system-for-write save-buffer-coding-system))
2663 (basic-save-buffer-2))
2664 (basic-save-buffer-2)))
2665
2666(defun basic-save-buffer-2 ()
2667 (let (tempsetmodes setmodes)
87d26afc
RS
2668 (if (not (file-writable-p buffer-file-name))
2669 (let ((dir (file-name-directory buffer-file-name)))
2670 (if (not (file-directory-p dir))
83c6f446
RS
2671 (if (file-exists-p dir)
2672 (error "%s is not a directory" dir)
cb2fdcfa 2673 (error "%s: no such directory" buffer-file-name))
87d26afc
RS
2674 (if (not (file-exists-p buffer-file-name))
2675 (error "Directory %s write-protected" dir)
2676 (if (yes-or-no-p
2677 (format "File %s is write-protected; try to save anyway? "
2678 (file-name-nondirectory
2679 buffer-file-name)))
2680 (setq tempsetmodes t)
2681 (error "Attempt to save to a file which you aren't allowed to write"))))))
2682 (or buffer-backed-up
2683 (setq setmodes (backup-buffer)))
76d5492b 2684 (let ((dir (file-name-directory buffer-file-name)))
f4a0f59b
RS
2685 (if (and file-precious-flag
2686 (file-writable-p dir))
2687 ;; If file is precious, write temp name, then rename it.
2688 ;; This requires write access to the containing dir,
2689 ;; which is why we don't try it if we don't have that access.
2690 (let ((realname buffer-file-name)
6782610c
RS
2691 tempname temp nogood i succeed
2692 (old-modtime (visited-file-modtime)))
f4a0f59b
RS
2693 (setq i 0)
2694 (setq nogood t)
2695 ;; Find the temporary name to write under.
2696 (while nogood
567c1ca9 2697 (setq tempname (format
28ee503c
KH
2698 (if (and (eq system-type 'ms-dos)
2699 (not (msdos-long-file-names)))
567c1ca9 2700 "%s#%d.tm#" ; MSDOS limits files to 8+3
ffc0e1ca
AS
2701 (if (memq system-type '(vax-vms axp-vms))
2702 "%s$tmp$%d"
2703 "%s#tmp#%d"))
567c1ca9 2704 dir i))
f4a0f59b
RS
2705 (setq nogood (file-exists-p tempname))
2706 (setq i (1+ i)))
2707 (unwind-protect
2708 (progn (clear-visited-file-modtime)
2709 (write-region (point-min) (point-max)
89095962
RS
2710 tempname nil realname
2711 buffer-file-truename)
f4a0f59b
RS
2712 (setq succeed t))
2713 ;; If writing the temp file fails,
2714 ;; delete the temp file.
76d5492b 2715 (or succeed
6782610c
RS
2716 (progn
2717 (delete-file tempname)
2718 (set-visited-file-modtime old-modtime))))
f4a0f59b
RS
2719 ;; Since we have created an entirely new file
2720 ;; and renamed it, make sure it gets the
2721 ;; right permission bits set.
2722 (setq setmodes (file-modes buffer-file-name))
2723 ;; We succeeded in writing the temp file,
2724 ;; so rename it.
2725 (rename-file tempname buffer-file-name t))
2726 ;; If file not writable, see if we can make it writable
2727 ;; temporarily while we write it.
2728 ;; But no need to do so if we have just backed it up
2729 ;; (setmodes is set) because that says we're superseding.
2730 (cond ((and tempsetmodes (not setmodes))
2731 ;; Change the mode back, after writing.
2732 (setq setmodes (file-modes buffer-file-name))
ffc0e1ca 2733 (set-file-modes buffer-file-name (logior setmodes 128))))
f4a0f59b 2734 (write-region (point-min) (point-max)
89095962 2735 buffer-file-name nil t buffer-file-truename)))
87d26afc
RS
2736 setmodes))
2737
ffc0e1ca 2738(defun save-some-buffers (&optional arg pred)
b4da00e9 2739 "Save some modified file-visiting buffers. Asks user about each one.
5bbbceb1 2740Optional argument (the prefix) non-nil means save all with no questions.
ffc0e1ca
AS
2741Optional second argument PRED determines which buffers are considered:
2742If PRED is nil, all the file-visiting buffers are considered.
2743If PRED is t, then certain non-file buffers will also be considered.
2744If PRED is a zero-argument function, it indicates for each buffer whether
2745to consider it or not when called with that buffer current."
b4da00e9 2746 (interactive "P")
907482b9 2747 (save-window-excursion
76d5492b
RM
2748 (let* ((queried nil)
2749 (files-done
2750 (map-y-or-n-p
2751 (function
2752 (lambda (buffer)
2753 (and (buffer-modified-p buffer)
2754 (not (buffer-base-buffer buffer))
2755 (or
2756 (buffer-file-name buffer)
ffc0e1ca 2757 (and pred
76d5492b
RM
2758 (progn
2759 (set-buffer buffer)
2760 (and buffer-offer-save (> (buffer-size) 0)))))
ffc0e1ca
AS
2761 (or (not (functionp pred))
2762 (with-current-buffer buffer (funcall pred)))
76d5492b
RM
2763 (if arg
2764 t
2765 (setq queried t)
2766 (if (buffer-file-name buffer)
2767 (format "Save file %s? "
2768 (buffer-file-name buffer))
2769 (format "Save buffer %s? "
2770 (buffer-name buffer)))))))
2771 (function
2772 (lambda (buffer)
2773 (set-buffer buffer)
2774 (save-buffer)))
2775 (buffer-list)
2776 '("buffer" "buffers" "save")
2777 (list (list ?\C-r (lambda (buf)
2a9fe1e2
RS
2778 (view-buffer buf
2779 (function
2780 (lambda (ignore)
2781 (exit-recursive-edit))))
76d5492b
RM
2782 (recursive-edit)
2783 ;; Return nil to ask about BUF again.
2784 nil)
2785 "display the current buffer"))))
2786 (abbrevs-done
2787 (and save-abbrevs abbrevs-changed
2788 (progn
2789 (if (or arg
2790 (y-or-n-p (format "Save abbrevs in %s? "
2791 abbrev-file-name)))
2792 (write-abbrev-file nil))
2793 ;; Don't keep bothering user if he says no.
2794 (setq abbrevs-changed nil)
2795 t))))
2796 (or queried (> files-done 0) abbrevs-done
5625c2fc 2797 (message "(No files need saving)")))))
b4da00e9
RM
2798\f
2799(defun not-modified (&optional arg)
2800 "Mark current buffer as unmodified, not needing to be saved.
a641f9a1
RM
2801With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2802
2803It is not a good idea to use this function in Lisp programs, because it
2804prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
b4da00e9
RM
2805 (interactive "P")
2806 (message (if arg "Modification-flag set"
2807 "Modification-flag cleared"))
2808 (set-buffer-modified-p arg))
2809
2810(defun toggle-read-only (&optional arg)
2811 "Change whether this buffer is visiting its file read-only.
2a9fe1e2
RS
2812With arg, set read-only iff arg is positive.
2813If visiting file read-only and `view-read-only' is non-nil, enter view mode."
b4da00e9 2814 (interactive "P")
2a9fe1e2
RS
2815 (cond
2816 ((and arg (if (> (prefix-numeric-value arg) 0) buffer-read-only
2817 (not buffer-read-only))) ; If buffer-read-only is set correctly,
2818 nil) ; do nothing.
2819 ;; Toggle.
2820 ((and buffer-read-only view-mode)
ca597f41
KH
2821 (View-exit-and-edit)
2822 (make-local-variable 'view-read-only)
2823 (setq view-read-only t)) ; Must leave view mode.
2a9fe1e2
RS
2824 ((and (not buffer-read-only) view-read-only
2825 (not (eq (get major-mode 'mode-class) 'special)))
2826 (view-mode-enter))
2827 (t (setq buffer-read-only (not buffer-read-only))
2828 (force-mode-line-update))))
b4da00e9 2829
912192d1 2830(defun insert-file (filename)
b4da00e9
RM
2831 "Insert contents of file FILENAME into buffer after point.
2832Set mark after the inserted text.
2833
2834This function is meant for the user to run interactively.
2835Don't call it from programs! Use `insert-file-contents' instead.
2836\(Its calling sequence is different; see its documentation)."
912192d1 2837 (interactive "*fInsert file: ")
3be6243a
RS
2838 (if (file-directory-p filename)
2839 (signal 'file-error (list "Opening input file" "file is a directory"
2840 filename)))
912192d1 2841 (let ((tem (insert-file-contents filename)))
b4da00e9
RM
2842 (push-mark (+ (point) (car (cdr tem))))))
2843
912192d1 2844(defun append-to-file (start end filename)
b4da00e9
RM
2845 "Append the contents of the region to the end of file FILENAME.
2846When called from a function, expects three arguments,
2847START, END and FILENAME. START and END are buffer positions
da30bf98 2848saying what text to write."
912192d1
KH
2849 (interactive "r\nFAppend to file: ")
2850 (write-region start end filename t))
b4da00e9
RM
2851
2852(defun file-newest-backup (filename)
2853 "Return most recent backup file for FILENAME or nil if no backups exist."
ffc0e1ca
AS
2854 ;; `make-backup-file-name' will get us the right directory for
2855 ;; ordinary or numeric backups. It might create a directory for
2856 ;; backups as a side-effect, according to `backup-directory-alist'.
2857 (let* ((filename (file-name-sans-versions
2858 (make-backup-file-name filename)))
b4da00e9
RM
2859 (file (file-name-nondirectory filename))
2860 (dir (file-name-directory filename))
2861 (comp (file-name-all-completions file dir))
cf7e94a0
RS
2862 (newest nil)
2863 tem)
b4da00e9 2864 (while comp
ffc0e1ca 2865 (setq tem (pop comp))
cf7e94a0
RS
2866 (cond ((and (backup-file-name-p tem)
2867 (string= (file-name-sans-versions tem) file))
2868 (setq tem (concat dir tem))
2869 (if (or (null newest)
2870 (file-newer-than-file-p tem newest))
2871 (setq newest tem)))))
b4da00e9
RM
2872 newest))
2873
2874(defun rename-uniquely ()
2875 "Rename current buffer to a similar name not already taken.
2876This function is useful for creating multiple shell process buffers
2877or multiple mail buffers, etc."
2878 (interactive)
40eb8038 2879 (save-match-data
e0df3aef
KH
2880 (let ((base-name (buffer-name)))
2881 (and (string-match "<[0-9]+>\\'" base-name)
2882 (not (and buffer-file-name
2883 (string= base-name
2884 (file-name-nondirectory buffer-file-name))))
2885 ;; If the existing buffer name has a <NNN>,
2886 ;; which isn't part of the file name (if any),
2887 ;; then get rid of that.
2888 (setq base-name (substring base-name 0 (match-beginning 0))))
2889 (rename-buffer (generate-new-buffer-name base-name))
3941fe2c 2890 (force-mode-line-update))))
5bbbceb1 2891
4e43240a 2892(defun make-directory (dir &optional parents)
5ce8bb89
RS
2893 "Create the directory DIR and any nonexistent parent dirs.
2894Interactively, the default choice of directory to create
2895is the current default directory for file names.
0225ae5e 2896That is useful when you have visited a file in a nonexistent directory.
5ce8bb89
RS
2897
2898Noninteractively, the second (optional) argument PARENTS says whether
2899to create parent directories if they don't exist."
2900 (interactive
2901 (list (read-file-name "Make directory: " default-directory default-directory
2902 nil nil)
2903 t))
6eaebaa2 2904 (let ((handler (find-file-name-handler dir 'make-directory)))
4e43240a
RS
2905 (if handler
2906 (funcall handler 'make-directory dir parents)
2907 (if (not parents)
2908 (make-directory-internal dir)
2909 (let ((dir (directory-file-name (expand-file-name dir)))
2910 create-list)
2911 (while (not (file-exists-p dir))
76d5492b 2912 (setq create-list (cons dir create-list)
4e43240a
RS
2913 dir (directory-file-name (file-name-directory dir))))
2914 (while create-list
2915 (make-directory-internal (car create-list))
2916 (setq create-list (cdr create-list))))))))
b4da00e9
RM
2917\f
2918(put 'revert-buffer-function 'permanent-local t)
2919(defvar revert-buffer-function nil
0973d78b
RS
2920 "Function to use to revert this buffer, or nil to do the default.
2921The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2922which are the arguments that `revert-buffer' received.")
b4da00e9
RM
2923
2924(put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2925(defvar revert-buffer-insert-file-contents-function nil
2926 "Function to use to insert contents when reverting this buffer.
2927Gets two args, first the nominal file name to use,
2df32500
RS
2928and second, t if reading the auto-save file.
2929
2930The function you specify is responsible for updating (or preserving) point.")
b4da00e9 2931
5f76e7d4
KH
2932(defvar before-revert-hook nil
2933 "Normal hook for `revert-buffer' to run before reverting.
2934If `revert-buffer-function' is used to override the normal revert
2935mechanism, this hook is not used.")
2936
2937(defvar after-revert-hook nil
2938 "Normal hook for `revert-buffer' to run after reverting.
2939Note that the hook value that it runs is the value that was in effect
2940before reverting; that makes a difference if you have buffer-local
2941hook functions.
2942
2943If `revert-buffer-function' is used to override the normal revert
2944mechanism, this hook is not used.")
2945
1554c03b
RS
2946(defvar revert-buffer-internal-hook)
2947
9a30563f 2948(defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
7e7c9c4e 2949 "Replace current buffer text with the text of the visited file on disk.
b4da00e9 2950This undoes all changes since the file was visited or saved.
8c0e7b73
JB
2951With a prefix argument, offer to revert from latest auto-save file, if
2952that is more recent than the visited file.
1ab31687 2953
7e7c9c4e
RS
2954This command also works for special buffers that contain text which
2955doesn't come from a file, but reflects some other data base instead:
2956for example, Dired buffers and buffer-list buffers. In these cases,
2957it reconstructs the buffer contents from the appropriate data base.
2958
65ee6096 2959When called from Lisp, the first argument is IGNORE-AUTO; only offer
1ab31687
JB
2960to revert from the auto-save file when this is nil. Note that the
2961sense of this argument is the reverse of the prefix argument, for the
2962sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2963to nil.
2964
2965Optional second argument NOCONFIRM means don't ask for confirmation at
ffc0e1ca 2966all. (The local variable `revert-without-query', if non-nil, prevents
d1f04130 2967confirmation.)
b4da00e9 2968
5b2b26d5
RS
2969Optional third argument PRESERVE-MODES non-nil means don't alter
2970the files modes. Normally we reinitialize them using `normal-mode'.
2971
8c0e7b73 2972If the value of `revert-buffer-function' is non-nil, it is called to
7e7c9c4e
RS
2973do all the work for this command. Otherwise, the hooks
2974`before-revert-hook' and `after-revert-hook' are run at the beginning
2975and the end, and if `revert-buffer-insert-file-contents-function' is
2976non-nil, it is called instead of rereading visited file contents."
fb6208a6 2977
1ab31687
JB
2978 ;; I admit it's odd to reverse the sense of the prefix argument, but
2979 ;; there is a lot of code out there which assumes that the first
2980 ;; argument should be t to avoid consulting the auto-save file, and
2981 ;; there's no straightforward way to encourage authors to notice a
2982 ;; reversal of the argument sense. So I'm just changing the user
2983 ;; interface, but leaving the programmatic interface the same.
e0867e99 2984 (interactive (list (not current-prefix-arg)))
b4da00e9 2985 (if revert-buffer-function
1ab31687 2986 (funcall revert-buffer-function ignore-auto noconfirm)
2df32500 2987 (let* ((auto-save-p (and (not ignore-auto)
1ab31687 2988 (recent-auto-save-p)
b4da00e9
RM
2989 buffer-auto-save-file-name
2990 (file-readable-p buffer-auto-save-file-name)
2991 (y-or-n-p
2992 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2993 (file-name (if auto-save-p
2994 buffer-auto-save-file-name
2995 buffer-file-name)))
2996 (cond ((null file-name)
2997 (error "Buffer does not seem to be associated with any file"))
2998 ((or noconfirm
db8c4866
RS
2999 (and (not (buffer-modified-p))
3000 (let ((tail revert-without-query)
3001 (found nil))
3002 (while tail
3003 (if (string-match (car tail) file-name)
3004 (setq found t))
3005 (setq tail (cdr tail)))
3006 found))
b4da00e9
RM
3007 (yes-or-no-p (format "Revert buffer from file %s? "
3008 file-name)))
4fbf62ee 3009 (run-hooks 'before-revert-hook)
b4da00e9
RM
3010 ;; If file was backed up but has changed since,
3011 ;; we shd make another backup.
3012 (and (not auto-save-p)
5bbbceb1 3013 (not (verify-visited-file-modtime (current-buffer)))
b4da00e9
RM
3014 (setq buffer-backed-up nil))
3015 ;; Get rid of all undo records for this buffer.
3016 (or (eq buffer-undo-list t)
3017 (setq buffer-undo-list nil))
ba5c8c93
KH
3018 ;; Effectively copy the after-revert-hook status,
3019 ;; since after-find-file will clobber it.
3020 (let ((global-hook (default-value 'after-revert-hook))
3021 (local-hook-p (local-variable-p 'after-revert-hook))
3022 (local-hook (and (local-variable-p 'after-revert-hook)
3023 after-revert-hook)))
3024 (let (buffer-read-only
3025 ;; Don't make undo records for the reversion.
3026 (buffer-undo-list t))
3027 (if revert-buffer-insert-file-contents-function
3028 (funcall revert-buffer-insert-file-contents-function
3029 file-name auto-save-p)
3030 (if (not (file-exists-p file-name))
3031 (error "File %s no longer exists!" file-name))
3032 ;; Bind buffer-file-name to nil
3033 ;; so that we don't try to lock the file.
3034 (let ((buffer-file-name nil))
3035 (or auto-save-p
3036 (unlock-buffer)))
3037 (widen)
b77d8211
KH
3038 (let ((coding-system-for-read
3039 ;; Auto-saved file shoule be read without
3040 ;; any code conversion.
68875f0e 3041 (if auto-save-p 'emacs-mule-unix
b77d8211 3042 coding-system-for-read)))
2df32500 3043 ;; Note that this preserves point in an intelligent way.
b77d8211
KH
3044 (insert-file-contents file-name (not auto-save-p)
3045 nil nil t))))
ba5c8c93
KH
3046 ;; Recompute the truename in case changes in symlinks
3047 ;; have changed the truename.
3048 (setq buffer-file-truename
3049 (abbreviate-file-name (file-truename buffer-file-name)))
9a30563f 3050 (after-find-file nil nil t t preserve-modes)
ba5c8c93
KH
3051 ;; Run after-revert-hook as it was before we reverted.
3052 (setq-default revert-buffer-internal-hook global-hook)
3053 (if local-hook-p
3054 (progn
3055 (make-local-variable 'revert-buffer-internal-hook)
3056 (setq revert-buffer-internal-hook local-hook))
3057 (kill-local-variable 'revert-buffer-internal-hook))
3058 (run-hooks 'revert-buffer-internal-hook))
4fbf62ee 3059 t)))))
b4da00e9
RM
3060
3061(defun recover-file (file)
3062 "Visit file FILE, but get contents from its last auto-save file."
10f7c7fc
RS
3063 ;; Actually putting the file name in the minibuffer should be used
3064 ;; only rarely.
3065 ;; Not just because users often use the default.
e1dadc17 3066 (interactive "FRecover file: ")
b4da00e9 3067 (setq file (expand-file-name file))
f7da6740
RS
3068 (if (auto-save-file-name-p (file-name-nondirectory file))
3069 (error "%s is an auto-save file" file))
b4da00e9
RM
3070 (let ((file-name (let ((buffer-file-name file))
3071 (make-auto-save-file-name))))
945e1965
RS
3072 (cond ((if (file-exists-p file)
3073 (not (file-newer-than-file-p file-name file))
3074 (not (file-exists-p file-name)))
b4da00e9
RM
3075 (error "Auto-save file %s not current" file-name))
3076 ((save-window-excursion
ffc0e1ca
AS
3077 (with-output-to-temp-buffer "*Directory*"
3078 (buffer-disable-undo standard-output)
3079 (save-excursion
3080 (let ((switches dired-listing-switches))
3081 (if (file-symlink-p file)
3082 (setq switches (concat switches "L")))
3083 (set-buffer standard-output)
bc22fd18
EZ
3084 ;; Use insert-directory-safely, not insert-directory,
3085 ;; because these files might not exist. In particular,
3086 ;; FILE might not exist if the auto-save file was for
3087 ;; a buffer that didn't visit a file, such as "*mail*".
3088 ;; The code in v20.x called `ls' directly, so we need
3089 ;; to emulate what `ls' did in that case.
3090 (insert-directory-safely file switches)
3091 (insert-directory-safely file-name switches))))
b4da00e9
RM
3092 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3093 (switch-to-buffer (find-file-noselect file t))
82d0954a 3094 (let ((buffer-read-only nil)
1e87edf5
KH
3095 ;; Keep the current buffer-file-coding-system.
3096 (coding-system buffer-file-coding-system)
82d0954a 3097 ;; Auto-saved file shoule be read without any code conversion.
68875f0e 3098 (coding-system-for-read 'emacs-mule-unix))
b4da00e9 3099 (erase-buffer)
1e87edf5
KH
3100 (insert-file-contents file-name nil)
3101 (set-buffer-file-coding-system coding-system))
8cfb9d46 3102 (after-find-file nil nil t))
ffa7ab70 3103 (t (error "Recover-file cancelled")))))
b4da00e9 3104
6598027d 3105(defun recover-session ()
9aee5392
RS
3106 "Recover auto save files from a previous Emacs session.
3107This command first displays a Dired buffer showing you the
3108previous sessions that you could recover from.
3109To choose one, move point to the proper line and then type C-c C-c.
3110Then you'll be asked about a number of files to recover."
3111 (interactive)
363a5030
RS
3112 (if (null auto-save-list-file-prefix)
3113 (error "You set `auto-save-list-file-prefix' to disable making session files"))
ffc0e1ca
AS
3114 (let ((dir (file-name-directory auto-save-list-file-prefix)))
3115 (unless (file-directory-p dir)
3116 (make-directory dir t)))
6f4983e6 3117 (let ((ls-lisp-support-shell-wildcards t))
7b3478a5
RS
3118 (dired (concat auto-save-list-file-prefix "*")
3119 (concat dired-listing-switches "t")))
05e076c7
AS
3120 (save-excursion
3121 (goto-char (point-min))
3122 (or (looking-at " Move to the session you want to recover,")
3123 (let ((inhibit-read-only t))
3124 ;; Each line starts with a space
3125 ;; so that Font Lock mode won't highlight the first character.
3126 (insert " Move to the session you want to recover,\n"
3127 " then type C-c C-c to select it.\n\n"
3128 " You can also delete some of these files;\n"
3129 " type d on a line to mark that file for deletion.\n\n"))))
9aee5392 3130 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
80280bb7 3131 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
9aee5392 3132
80280bb7 3133(defun recover-session-finish ()
9aee5392
RS
3134 "Choose one saved session to recover auto-save files from.
3135This command is used in the special Dired buffer created by
80280bb7 3136\\[recover-session]."
9aee5392
RS
3137 (interactive)
3138 ;; Get the name of the session file to recover from.
3139 (let ((file (dired-get-filename))
953a03b2 3140 files
9aee5392 3141 (buffer (get-buffer-create " *recover*")))
c11032b9 3142 (dired-unmark 1)
033ef863 3143 (dired-do-flagged-delete t)
9aee5392
RS
3144 (unwind-protect
3145 (save-excursion
3146 ;; Read in the auto-save-list file.
3147 (set-buffer buffer)
3148 (erase-buffer)
3149 (insert-file-contents file)
953a03b2
RS
3150 ;; Loop thru the text of that file
3151 ;; and get out the names of the files to recover.
3152 (while (not (eobp))
3153 (let (thisfile autofile)
3154 (if (eolp)
3155 ;; This is a pair of lines for a non-file-visiting buffer.
3156 ;; Get the auto-save file name and manufacture
3157 ;; a "visited file name" from that.
3158 (progn
3159 (forward-line 1)
3160 (setq autofile
3161 (buffer-substring-no-properties
3162 (point)
3163 (save-excursion
3164 (end-of-line)
3165 (point))))
3166 (setq thisfile
3167 (expand-file-name
3168 (substring
3169 (file-name-nondirectory autofile)
3170 1 -1)
3171 (file-name-directory autofile)))
3172 (forward-line 1))
3173 ;; This pair of lines is a file-visiting
3174 ;; buffer. Use the visited file name.
3175 (progn
3176 (setq thisfile
3177 (buffer-substring-no-properties
3178 (point) (progn (end-of-line) (point))))
3179 (forward-line 1)
3180 (setq autofile
3181 (buffer-substring-no-properties
3182 (point) (progn (end-of-line) (point))))
3183 (forward-line 1)))
3184 ;; Ignore a file if its auto-save file does not exist now.
3185 (if (file-exists-p autofile)
3186 (setq files (cons thisfile files)))))
3187 (setq files (nreverse files))
945e1965
RS
3188 ;; The file contains a pair of line for each auto-saved buffer.
3189 ;; The first line of the pair contains the visited file name
3190 ;; or is empty if the buffer was not visiting a file.
3191 ;; The second line is the auto-save file name.
953a03b2
RS
3192 (if files
3193 (map-y-or-n-p "Recover %s? "
3194 (lambda (file)
3195 (condition-case nil
3196 (save-excursion (recover-file file))
76d5492b 3197 (error
953a03b2
RS
3198 "Failed to recover `%s'" file)))
3199 files
3200 '("file" "files" "recover"))
3201 (message "No files can be recovered from this session now")))
9aee5392
RS
3202 (kill-buffer buffer))))
3203
73ba610a
RS
3204(defun kill-some-buffers (&optional list)
3205 "For each buffer in LIST, ask whether to kill it.
3206LIST defaults to all existing live buffers."
b4da00e9 3207 (interactive)
73ba610a
RS
3208 (if (null list)
3209 (setq list (buffer-list)))
3210 (while list
3211 (let* ((buffer (car list))
3212 (name (buffer-name buffer)))
3213 (and (not (string-equal name ""))
3214 (/= (aref name 0) ? )
3215 (yes-or-no-p
3216 (format "Buffer %s %s. Kill? "
3217 name
3218 (if (buffer-modified-p buffer)
3219 "HAS BEEN EDITED" "is unmodified")))
3220 (kill-buffer buffer)))
3221 (setq list (cdr list))))
b4da00e9
RM
3222\f
3223(defun auto-save-mode (arg)
3224 "Toggle auto-saving of contents of current buffer.
f3e23606 3225With prefix argument ARG, turn auto-saving on if positive, else off."
b4da00e9
RM
3226 (interactive "P")
3227 (setq buffer-auto-save-file-name
3228 (and (if (null arg)
74b9c2af 3229 (or (not buffer-auto-save-file-name)
4e0c8650 3230 ;; If auto-save is off because buffer has shrunk,
74b9c2af
RS
3231 ;; then toggling should turn it on.
3232 (< buffer-saved-size 0))
b4da00e9
RM
3233 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
3234 (if (and buffer-file-name auto-save-visited-file-name
3235 (not buffer-read-only))
3236 buffer-file-name
3237 (make-auto-save-file-name))))
0b7f1ef2
RS
3238 ;; If -1 was stored here, to temporarily turn off saving,
3239 ;; turn it back on.
3240 (and (< buffer-saved-size 0)
3241 (setq buffer-saved-size 0))
b4da00e9
RM
3242 (if (interactive-p)
3243 (message "Auto-save %s (in this buffer)"
3244 (if buffer-auto-save-file-name "on" "off")))
3245 buffer-auto-save-file-name)
3246
3247(defun rename-auto-save-file ()
3248 "Adjust current buffer's auto save file name for current conditions.
3249Also rename any existing auto save file, if it was made in this session."
3250 (let ((osave buffer-auto-save-file-name))
3251 (setq buffer-auto-save-file-name
3252 (make-auto-save-file-name))
3253 (if (and osave buffer-auto-save-file-name
3254 (not (string= buffer-auto-save-file-name buffer-file-name))
3255 (not (string= buffer-auto-save-file-name osave))
3256 (file-exists-p osave)
3257 (recent-auto-save-p))
3258 (rename-file osave buffer-auto-save-file-name t))))
3259
3260(defun make-auto-save-file-name ()
3261 "Return file name to use for auto-saves of current buffer.
3262Does not consider `auto-save-visited-file-name' as that variable is checked
3263before calling this function. You can redefine this for customization.
3264See also `auto-save-file-name-p'."
3265 (if buffer-file-name
ffc0e1ca
AS
3266 (let ((list auto-save-file-name-transforms)
3267 (filename buffer-file-name)
3268 result)
3269 ;; Apply user-specified translations
3270 ;; to the file name.
3271 (while (and list (not result))
3272 (if (string-match (car (car list)) filename)
3273 (setq result (replace-match (cadr (car list)) t nil
3274 filename)))
3275 (setq list (cdr list)))
3276 (if result (setq filename result))
3277
3278 (if (and (eq system-type 'ms-dos)
3279 (not (msdos-long-file-names)))
15233548
EZ
3280 ;; We truncate the file name to DOS 8+3 limits before
3281 ;; doing anything else, because the regexp passed to
3282 ;; string-match below cannot handle extensions longer than
3283 ;; 3 characters, multiple dots, and other atrocities.
3284 (let ((fn (dos-8+3-filename
3285 (file-name-nondirectory buffer-file-name))))
ffc0e1ca
AS
3286 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
3287 (concat (file-name-directory buffer-file-name)
3288 "#" (match-string 1 fn)
3289 "." (match-string 3 fn) "#"))
3290 (concat (file-name-directory filename)
3291 "#"
3292 (file-name-nondirectory filename)
3293 "#")))
0a1763b4
RS
3294
3295 ;; Deal with buffers that don't have any associated files. (Mail
3296 ;; mode tends to create a good number of these.)
3297
7d483e8c 3298 (let ((buffer-name (buffer-name))
0a1763b4 3299 (limit 0))
c3348e10
RS
3300 ;; Eliminate all slashes and backslashes by
3301 ;; replacing them with sequences that start with %.
3302 ;; Quote % also, to keep distinct names distinct.
3303 (while (string-match "[/\\%]" buffer-name limit)
3304 (let* ((character (aref buffer-name (match-beginning 0)))
3305 (replacement
3306 (cond ((eq character ?%) "%%")
3307 ((eq character ?/) "%+")
3308 ((eq character ?\\) "%-"))))
3309 (setq buffer-name (replace-match replacement t t buffer-name))
3310 (setq limit (1+ (match-end 0)))))
a8abaf83
RS
3311 ;; Generate the file name.
3312 (expand-file-name
3313 (format "#%s#%s#" buffer-name (make-temp-name ""))
3314 ;; Try a few alternative directories, to get one we can write it.
3315 (cond
3316 ((file-writable-p default-directory) default-directory)
3317 ((file-writable-p "/var/tmp/") "/var/tmp/")
3318 ("~/"))))))
b4da00e9
RM
3319
3320(defun auto-save-file-name-p (filename)
3321 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
3322FILENAME should lack slashes. You can redefine this for customization."
3323 (string-match "^#.*#$" filename))
3324\f
6f4983e6
RS
3325(defun wildcard-to-regexp (wildcard)
3326 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
3327The generated regexp will match a filename iff the filename
3328matches that wildcard according to shell rules. Only wildcards known
3329by `sh' are supported."
3330 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
3331 ;; Copy the initial run of non-special characters.
3332 (result (substring wildcard 0 i))
3333 (len (length wildcard)))
3334 ;; If no special characters, we're almost done.
3335 (if i
3336 (while (< i len)
3337 (let ((ch (aref wildcard i))
3338 j)
3339 (setq
3340 result
3341 (concat result
3342 (cond
7e7c9c4e
RS
3343 ((and (eq ch ?\[)
3344 (< (1+ i) len)
3345 (eq (aref wildcard (1+ i)) ?\]))
3346 "\\[")
6f4983e6
RS
3347 ((eq ch ?\[) ; [...] maps to regexp char class
3348 (progn
3349 (setq i (1+ i))
3350 (concat
3351 (cond
3352 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
3353 (progn
3354 (setq i (1+ i))
3355 (if (eq (aref wildcard i) ?\])
3356 (progn
3357 (setq i (1+ i))
3358 "[^]")
3359 "[^")))
3360 ((eq (aref wildcard i) ?^)
3361 ;; Found "[^". Insert a `\0' character
3362 ;; (which cannot happen in a filename)
3363 ;; into the character class, so that `^'
3364 ;; is not the first character after `[',
3365 ;; and thus non-special in a regexp.
3366 (progn
3367 (setq i (1+ i))
3368 "[\000^"))
3369 ((eq (aref wildcard i) ?\])
3370 ;; I don't think `]' can appear in a
3371 ;; character class in a wildcard, but
3372 ;; let's be general here.
3373 (progn
3374 (setq i (1+ i))
3375 "[]"))
3376 (t "["))
3377 (prog1 ; copy everything upto next `]'.
3378 (substring wildcard
3379 i
3380 (setq j (string-match
3381 "]" wildcard i)))
3382 (setq i (if j (1- j) (1- len)))))))
3383 ((eq ch ?.) "\\.")
3384 ((eq ch ?*) "[^\000]*")
3385 ((eq ch ?+) "\\+")
3386 ((eq ch ?^) "\\^")
3387 ((eq ch ?$) "\\$")
3388 ((eq ch ?\\) "\\\\") ; probably cannot happen...
3389 ((eq ch ??) "[^\000]")
3390 (t (char-to-string ch)))))
3391 (setq i (1+ i)))))
3392 ;; Shell wildcards should match the entire filename,
3393 ;; not its part. Make the regexp say so.
3394 (concat "\\`" result "\\'")))
3395\f
21540597 3396(defcustom list-directory-brief-switches
b4da00e9 3397 (if (eq system-type 'vax-vms) "" "-CF")
ffc0e1ca 3398 "*Switches for `list-directory' to pass to `ls' for brief listing."
21540597
RS
3399 :type 'string
3400 :group 'dired)
b4da00e9 3401
21540597 3402(defcustom list-directory-verbose-switches
b4da00e9
RM
3403 (if (eq system-type 'vax-vms)
3404 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
3405 "-l")
ffc0e1ca 3406 "*Switches for `list-directory' to pass to `ls' for verbose listing."
21540597
RS
3407 :type 'string
3408 :group 'dired)
b4da00e9 3409
5de148a2
RS
3410(defun file-expand-wildcards (pattern &optional full)
3411 "Expand wildcard pattern PATTERN.
4db2a7de
RS
3412This returns a list of file names which match the pattern.
3413
3414If PATTERN is written as an absolute relative file name,
3415the values are absolute also.
3416
3417If PATTERN is written as a relative file name, it is interpreted
3418relative to the current default directory, `default-directory'.
3419The file names returned are normally also relative to the current
3420default directory. However, if FULL is non-nil, they are absolute."
3421 (let* ((nondir (file-name-nondirectory pattern))
3422 (dirpart (file-name-directory pattern))
3423 ;; A list of all dirs that DIRPART specifies.
3424 ;; This can be more than one dir
3425 ;; if DIRPART contains wildcards.
18b0f8cf 3426 (dirs (if (and dirpart (string-match "[[*?]" dirpart))
4db2a7de
RS
3427 (mapcar 'file-name-as-directory
3428 (file-expand-wildcards (directory-file-name dirpart)))
3429 (list dirpart)))
3430 contents)
3431 (while dirs
3432 (when (or (null (car dirs)) ; Possible if DIRPART is not wild.
3433 (file-directory-p (directory-file-name (car dirs))))
3434 (let ((this-dir-contents
18b0f8cf
AS
3435 ;; Filter out "." and ".."
3436 (delq nil
3437 (mapcar #'(lambda (name)
3438 (unless (string-match "\\`\\.\\.?\\'"
3439 (file-name-nondirectory name))
3440 name))
3441 (directory-files (or (car dirs) ".") full
3442 (wildcard-to-regexp nondir))))))
4db2a7de
RS
3443 (setq contents
3444 (nconc
3445 (if (and (car dirs) (not full))
3446 (mapcar (function (lambda (name) (concat (car dirs) name)))
3447 this-dir-contents)
3448 this-dir-contents)
3449 contents))))
3450 (setq dirs (cdr dirs)))
3451 contents))
5de148a2 3452
b4da00e9
RM
3453(defun list-directory (dirname &optional verbose)
3454 "Display a list of files in or matching DIRNAME, a la `ls'.
3455DIRNAME is globbed by the shell if necessary.
3456Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
3457Actions controlled by variables `list-directory-brief-switches'
3458and `list-directory-verbose-switches'."
3459 (interactive (let ((pfx current-prefix-arg))
3460 (list (read-file-name (if pfx "List directory (verbose): "
3461 "List directory (brief): ")
3462 nil default-directory nil)
3463 pfx)))
3464 (let ((switches (if verbose list-directory-verbose-switches
3465 list-directory-brief-switches)))
3466 (or dirname (setq dirname default-directory))
3467 (setq dirname (expand-file-name dirname))
3468 (with-output-to-temp-buffer "*Directory*"
3469 (buffer-disable-undo standard-output)
3470 (princ "Directory ")
3471 (princ dirname)
3472 (terpri)
c3554e95
RS
3473 (save-excursion
3474 (set-buffer "*Directory*")
5a8a160e
RS
3475 (setq default-directory
3476 (if (file-directory-p dirname)
3477 (file-name-as-directory dirname)
3478 (file-name-directory dirname)))
c3554e95
RS
3479 (let ((wildcard (not (file-directory-p dirname))))
3480 (insert-directory dirname switches wildcard (not wildcard)))))))
3481
ffc0e1ca
AS
3482(defun shell-quote-wildcard-pattern (pattern)
3483 "Quote characters special to the shell in PATTERN, leave wildcards alone.
3484
3485PATTERN is assumed to represent a file-name wildcard suitable for the
3486underlying filesystem. For Unix and GNU/Linux, the characters from the
3487set [ \\t\\n;<>&|()#$] are quoted with a backslash; for DOS/Windows, all
3488the parts of the pattern which don't include wildcard characters are
3489quoted with double quotes.
3490Existing quote characters in PATTERN are left alone, so you can pass
3491PATTERN that already quotes some of the special characters."
3492 (save-match-data
3493 (cond
3494 ((memq system-type '(ms-dos windows-nt))
3495 ;; DOS/Windows don't allow `"' in file names. So if the
3496 ;; argument has quotes, we can safely assume it is already
3497 ;; quoted by the caller.
3498 (if (or (string-match "[\"]" pattern)
3499 ;; We quote [&()#$'] in case their shell is a port of a
3500 ;; Unixy shell. We quote [,=+] because stock DOS and
3501 ;; Windows shells require that in some cases, such as
3502 ;; passing arguments to batch files that use positional
3503 ;; arguments like %1.
3504 (not (string-match "[ \t;&()#$',=+]" pattern)))
3505 pattern
3506 (let ((result "\"")
3507 (beg 0)
3508 end)
3509 (while (string-match "[*?]+" pattern beg)
3510 (setq end (match-beginning 0)
3511 result (concat result (substring pattern beg end)
3512 "\""
3513 (substring pattern end (match-end 0))
3514 "\"")
3515 beg (match-end 0)))
3516 (concat result (substring pattern beg) "\""))))
3517 (t
3518 (let ((beg 0))
3519 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
3520 (setq pattern
3521 (concat (substring pattern 0 (match-beginning 0))
3522 "\\"
3523 (substring pattern (match-beginning 0)))
3524 beg (1+ (match-end 0)))))
3525 pattern))))
3526
3527
c3554e95
RS
3528(defvar insert-directory-program "ls"
3529 "Absolute or relative name of the `ls' program used by `insert-directory'.")
3530
3531;; insert-directory
3532;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
3533;; FULL-DIRECTORY-P is nil.
3534;; The single line of output must display FILE's name as it was
3535;; given, namely, an absolute path name.
3536;; - must insert exactly one line for each file if WILDCARD or
3537;; FULL-DIRECTORY-P is t, plus one optional "total" line
3538;; before the file lines, plus optional text after the file lines.
3539;; Lines are delimited by "\n", so filenames containing "\n" are not
3540;; allowed.
3541;; File lines should display the basename.
3542;; - must be consistent with
3543;; - functions dired-move-to-filename, (these two define what a file line is)
3544;; dired-move-to-end-of-filename,
3545;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
3546;; dired-insert-headerline
3547;; dired-after-subdir-garbage (defines what a "total" line is)
3548;; - variable dired-subdir-regexp
3549(defun insert-directory (file switches &optional wildcard full-directory-p)
a18b7c81 3550 "Insert directory listing for FILE, formatted according to SWITCHES.
c3554e95 3551Leaves point after the inserted text.
727d277d 3552SWITCHES may be a string of options, or a list of strings.
c3554e95
RS
3553Optional third arg WILDCARD means treat FILE as shell wildcard.
3554Optional fourth arg FULL-DIRECTORY-P means file is a directory and
3555switches do not contain `d', so that a full listing is expected.
3556
3557This works by running a directory listing program
406e12d9 3558whose name is in the variable `insert-directory-program'.
c3554e95 3559If WILDCARD, it also runs the shell specified by `shell-file-name'."
c870ab8e 3560 ;; We need the directory in order to find the right handler.
d2473540
AS
3561 (let ((handler (find-file-name-handler (expand-file-name file)
3562 'insert-directory)))
ffc0e1ca 3563 (if handler
c3554e95
RS
3564 (funcall handler 'insert-directory file switches
3565 wildcard full-directory-p)
b4da00e9 3566 (if (eq system-type 'vax-vms)
c3554e95 3567 (vms-read-directory file switches (current-buffer))
73ba53dc
KH
3568 (let* ((coding-system-for-read
3569 (and enable-multibyte-characters
3570 (or file-name-coding-system
3571 default-file-name-coding-system)))
6a97049b 3572 ;; This is to control encoding the arguments in call-process.
a9173359 3573 (coding-system-for-write coding-system-for-read)
73ba53dc
KH
3574 (result
3575 (if wildcard
ffc0e1ca 3576 ;; Run ls in the directory of the file pattern we asked for
d2473540
AS
3577 (let ((default-directory
3578 (if (file-name-absolute-p file)
3579 (file-name-directory file)
3580 (file-name-directory (expand-file-name file))))
ffc0e1ca
AS
3581 (pattern (file-name-nondirectory file)))
3582 (call-process
3583 shell-file-name nil t nil
3584 "-c" (concat (if (memq system-type '(ms-dos windows-nt))
3585 ""
3586 "\\") ; Disregard Unix shell aliases!
3587 insert-directory-program
3588 " -d "
3589 (if (stringp switches)
3590 switches
3591 (mapconcat 'identity switches " "))
3592 " -- "
3593 ;; Quote some characters that have
3594 ;; special meanings in shells; but
3595 ;; don't quote the wildcards--we
3596 ;; want them to be special. We
3597 ;; also currently don't quote the
3598 ;; quoting characters in case
3599 ;; people want to use them
3600 ;; explicitly to quote wildcard
3601 ;; characters.
3602 (shell-quote-wildcard-pattern pattern))))
73ba53dc
KH
3603 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
3604 ;; directory if FILE is a symbolic link.
3605 (apply 'call-process
ffc0e1ca
AS
3606 insert-directory-program nil t nil
3607 (append
3608 (if (listp switches) switches
3609 (unless (equal switches "")
3610 ;; Split the switches at any spaces so we can
3611 ;; pass separate options as separate args.
3612 (split-string switches)))
3613 ;; Avoid lossage if FILE starts with `-'.
3614 '("--")
3615 (progn
3616 (if (string-match "\\`~" file)
3617 (setq file (expand-file-name file)))
3618 (list
3619 (if full-directory-p
3620 (concat (file-name-as-directory file) ".")
3621 file))))))))
73ba53dc 3622 (if (/= result 0)
ffc0e1ca
AS
3623 ;; We get here if `insert-directory-program' failed.
3624 ;; On non-Posix systems, we cannot open a directory, so
3625 ;; don't even try, because that will always result in
3626 ;; the ubiquitous "Access denied". Instead, show them
3627 ;; the `ls' command line and let them guess what went
3628 ;; wrong.
3629 (if (and (file-directory-p file)
3630 (memq system-type '(ms-dos windows-nt)))
3631 (error
3632 "Reading directory: \"%s %s -- %s\" exited with status %s"
3633 insert-directory-program
3634 (if (listp switches) (concat switches) switches)
3635 file result)
3636 ;; Unix. Access the file to get a suitable error.
3637 (access-file file "Reading directory"))
3638 ;; Replace "total" with "used", to avoid confusion.
3639 ;; Add in the amount of free space.
3640 (save-excursion
3641 (goto-char (point-min))
3642 (when (re-search-forward "^total" nil t)
3643 (replace-match "used")
3644 (end-of-line)
3645 (let (available)
3646 (with-temp-buffer
3647 (call-process "df" nil t nil ".")
3648 (goto-char (point-min))
3649 (forward-line 1)
3650 (skip-chars-forward "^ \t")
3651 (forward-word 3)
3652 (let ((end (point)))
3653 (forward-word -1)
3654 (setq available (buffer-substring (point) end))))
3655 (insert " available " available))))))))))
34342a07 3656
bc22fd18
EZ
3657(defun insert-directory-safely (file switches
3658 &optional wildcard full-directory-p)
3659 "Insert directory listing for FILE, formatted according to SWITCHES.
3660
3661Like `insert-directory', but if FILE does not exist, it inserts a
3662message to that effect instead of signaling an error."
3663 (if (file-exists-p file)
3664 (insert-directory file switches wildcard full-directory-p)
3665 ;; Simulate the message printed by `ls'.
3666 (insert (format "%s: No such file or directory\n" file))))
3667
88902b35 3668(defvar kill-emacs-query-functions nil
65d5c6de 3669 "Functions to call with no arguments to query about killing Emacs.
78c793d1
RS
3670If any of these functions returns nil, killing Emacs is cancelled.
3671`save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
3672but `kill-emacs', the low level primitive, does not.
3673See also `kill-emacs-hook'.")
88902b35 3674
11f15305 3675(defcustom confirm-kill-emacs nil
9c2ba08f
EZ
3676 "How to ask for confirmation when leaving Emacs.
3677If nil, the default, don't ask at all. If the value is non-nil, it should
3678be a predicate function such as `yes-or-no-p'."
11f15305
GM
3679 :type '(choice (const :tag "Ask with yes-or-no-p" yes-or-no-p)
3680 (const :tag "Ask with y-or-n-p" y-or-n-p)
3681 (const :tag "Don't confirm" nil))
3682 :group 'emacs
3683 :version "21.1")
3684
b4da00e9
RM
3685(defun save-buffers-kill-emacs (&optional arg)
3686 "Offer to save each buffer, then kill this Emacs process.
3687With prefix arg, silently save all file-visiting buffers, then kill."
3688 (interactive "P")
3689 (save-some-buffers arg t)
3690 (and (or (not (memq t (mapcar (function
3691 (lambda (buf) (and (buffer-file-name buf)
3692 (buffer-modified-p buf))))
3693 (buffer-list))))
3694 (yes-or-no-p "Modified buffers exist; exit anyway? "))
3695 (or (not (fboundp 'process-list))
3696 ;; process-list is not defined on VMS.
3697 (let ((processes (process-list))
3698 active)
3699 (while processes
528415e7 3700 (and (memq (process-status (car processes)) '(run stop open))
b4da00e9
RM
3701 (let ((val (process-kill-without-query (car processes))))
3702 (process-kill-without-query (car processes) val)
3703 val)
3704 (setq active t))
3705 (setq processes (cdr processes)))
3706 (or (not active)
71a3bb4b 3707 (list-processes)
b4da00e9 3708 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
88902b35 3709 ;; Query the user for other things, perhaps.
fb15c113 3710 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
11f15305
GM
3711 (or (null confirm-kill-emacs)
3712 (funcall confirm-kill-emacs "Really exit Emacs? "))
b4da00e9
RM
3713 (kill-emacs)))
3714\f
ffc0e1ca 3715;; We use /: as a prefix to "quote" a file name
47afc068
RS
3716;; so that magic file name handlers will not apply to it.
3717
3718(setq file-name-handler-alist
3719 (cons '("\\`/:" . file-name-non-special)
3720 file-name-handler-alist))
3721
3722;; We depend on being the last handler on the list,
3723;; so that anything else which does need handling
3724;; has been handled already.
3725;; So it is safe for us to inhibit *all* magic file name handlers.
3726
3727(defun file-name-non-special (operation &rest arguments)
3728 (let ((file-name-handler-alist nil)
5cb1f728
KH
3729 (default-directory
3730 (if (eq operation 'insert-directory)
3731 (directory-file-name
ffc0e1ca 3732 (expand-file-name
5cb1f728
KH
3733 (unhandled-file-name-directory default-directory)))
3734 default-directory))
47afc068
RS
3735 ;; Get a list of the indices of the args which are file names.
3736 (file-arg-indices
3737 (cdr (or (assq operation
3738 ;; The first four are special because they
3739 ;; return a file name. We want to include the /:
3740 ;; in the return value.
3741 ;; So just avoid stripping it in the first place.
3742 '((expand-file-name . nil)
18b9dced
RS
3743 ;; `identity' means just return the first arg
3744 ;; as stripped of its quoting.
3745 (substitute-in-file-name . identity)
47afc068
RS
3746 (file-name-directory . nil)
3747 (file-name-as-directory . nil)
3748 (directory-file-name . nil)
feaec97d
RS
3749 (file-name-completion 0 1)
3750 (file-name-all-completions 0 1)
47afc068
RS
3751 (rename-file 0 1)
3752 (copy-file 0 1)
3753 (make-symbolic-link 0 1)
3754 (add-name-to-file 0 1)))
3755 ;; For all other operations, treat the first argument only
3756 ;; as the file name.
3757 '(nil 0))))
3758 ;; Copy ARGUMENTS so we can replace elements in it.
3759 (arguments (copy-sequence arguments)))
3760 ;; Strip off the /: from the file names that have this handler.
3761 (save-match-data
18b9dced 3762 (while (consp file-arg-indices)
fe4d9852
KH
3763 (let ((pair (nthcdr (car file-arg-indices) arguments)))
3764 (and (car pair)
3765 (string-match "\\`/:" (car pair))
3766 (setcar pair
3767 (if (= (length (car pair)) 2)
3768 "/"
3769 (substring (car pair) 2)))))
47afc068 3770 (setq file-arg-indices (cdr file-arg-indices))))
18b9dced
RS
3771 (if (eq file-arg-indices 'identity)
3772 (car arguments)
3773 (apply operation arguments))))
47afc068 3774\f
b4da00e9 3775(define-key ctl-x-map "\C-f" 'find-file)
b4da00e9
RM
3776(define-key ctl-x-map "\C-r" 'find-file-read-only)
3777(define-key ctl-x-map "\C-v" 'find-alternate-file)
3778(define-key ctl-x-map "\C-s" 'save-buffer)
3779(define-key ctl-x-map "s" 'save-some-buffers)
3780(define-key ctl-x-map "\C-w" 'write-file)
3781(define-key ctl-x-map "i" 'insert-file)
3782(define-key esc-map "~" 'not-modified)
3783(define-key ctl-x-map "\C-d" 'list-directory)
3784(define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
3785
3786(define-key ctl-x-4-map "f" 'find-file-other-window)
3787(define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
3788(define-key ctl-x-4-map "\C-f" 'find-file-other-window)
3789(define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
924f0a24 3790(define-key ctl-x-4-map "\C-o" 'display-buffer)
5bbbceb1 3791
f98955ea
JB
3792(define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
3793(define-key ctl-x-5-map "f" 'find-file-other-frame)
3794(define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
3795(define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
c0274f38
ER
3796
3797;;; files.el ends here