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