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