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