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