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