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