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