(dired-collect-file-versions):
[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
21540597 149(defcustom find-file-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,
154then `find-file' 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
RS
368(defvar path-separator ":"
369 "Character used to separate concatenated paths.")
370
231c4e10
ER
371(defun parse-colon-path (cd-path)
372 "Explode a colon-separated list of paths into a string list."
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))
882 (let ((tail find-file-revert-without-query)
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
2d051399
RS
1907;; This is used in various files.
1908;; The usage of bv-length is not very clean,
1909;; but I can't see a good alternative,
1910;; so as of now I am leaving it alone.
1911(defun backup-extract-version (fn)
1912 "Given the name of a numeric backup file, return the backup number.
1913Uses the free variable `bv-length', whose value should be
1914the index in the name where the version number begins."
1915 (if (and (string-match "[0-9]+~$" fn bv-length)
1916 (= (match-beginning 0) bv-length))
1917 (string-to-int (substring fn bv-length -1))
1918 0))
1919
b4da00e9
RM
1920;; I believe there is no need to alter this behavior for VMS;
1921;; since backup files are not made on VMS, it should not get called.
1922(defun find-backup-file-name (fn)
1923 "Find a file name for a backup file, and suggestions for deletions.
1924Value is a list whose car is the name for the backup file
eb650569
RS
1925 and whose cdr is a list of old versions to consider deleting now.
1926If the value is nil, don't make a backup."
1927 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
1928 ;; Run a handler for this function so that ange-ftp can refuse to do it.
1929 (if handler
1930 (funcall handler 'find-backup-file-name fn)
1931 (if (eq version-control 'never)
b4da00e9 1932 (list (make-backup-file-name fn))
eb650569
RS
1933 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1934 (bv-length (length base-versions))
1935 possibilities
1936 (versions nil)
1937 (high-water-mark 0)
1938 (deserve-versions-p nil)
1939 (number-to-delete 0))
1940 (condition-case ()
1941 (setq possibilities (file-name-all-completions
1942 base-versions
1943 (file-name-directory fn))
1944 versions (sort (mapcar
1945 (function backup-extract-version)
1946 possibilities)
1947 '<)
1948 high-water-mark (apply 'max 0 versions)
1949 deserve-versions-p (or version-control
1950 (> high-water-mark 0))
1951 number-to-delete (- (length versions)
1952 kept-old-versions kept-new-versions -1))
1953 (file-error
1954 (setq possibilities nil)))
1955 (if (not deserve-versions-p)
1956 (list (make-backup-file-name fn))
1957 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
1958 (if (and (> number-to-delete 0)
1959 ;; Delete nothing if there is overflow
1960 ;; in the number of versions to keep.
1961 (>= (+ kept-new-versions kept-old-versions -1) 0))
1962 (mapcar (function (lambda (n)
1963 (concat fn ".~" (int-to-string n) "~")))
1964 (let ((v (nthcdr kept-old-versions versions)))
1965 (rplacd (nthcdr (1- number-to-delete) v) ())
1966 v))))))))))
b4da00e9 1967
b4da00e9
RM
1968(defun file-nlinks (filename)
1969 "Return number of names file FILENAME has."
1970 (car (cdr (file-attributes filename))))
6c636af9
RM
1971
1972(defun file-relative-name (filename &optional directory)
2d6562a5
RS
1973 "Convert FILENAME to be relative to DIRECTORY (default: default-directory).
1974This function returns a relative file name which is equivalent to FILENAME
1975when used with that default directory as the default.
1976If this is impossible (which can happen on MSDOS and Windows
1977when the file name and directory use different drive names)
1978then it returns FILENAME."
96c188b0 1979 (save-match-data
2d6562a5
RS
1980 (setq fname (expand-file-name filename)
1981 directory (file-name-as-directory
1982 (expand-file-name (or directory default-directory))))
1983 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
1984 ;; drive names, they can't be relative, so return the absolute name.
1985 (if (and (or (eq system-type 'ms-dos)
1986 (eq system-type 'windows-nt))
1987 (not (string-equal (substring fname 0 2)
1988 (substring directory 0 2))))
1989 filename
1990 (let ((ancestor ""))
1991 (while (not (string-match (concat "^" (regexp-quote directory)) fname))
1992 (setq directory (file-name-directory (substring directory 0 -1))
1993 ancestor (concat "../" ancestor)))
1994 (concat ancestor (substring fname (match-end 0)))))))
b4da00e9
RM
1995\f
1996(defun save-buffer (&optional args)
1997 "Save current buffer in visited file if modified. Versions described below.
1998By default, makes the previous version into a backup file
1999 if previously requested or if this is the first save.
ac9650be 2000With 1 \\[universal-argument], marks this version
b4da00e9 2001 to become a backup when the next save is done.
ac9650be 2002With 2 \\[universal-argument]'s,
b4da00e9 2003 unconditionally makes the previous version into a backup file.
ac9650be
RS
2004With 3 \\[universal-argument]'s, marks this version
2005 to become a backup when the next save is done,
2006 and unconditionally makes the previous version into a backup file.
2007
b4da00e9
RM
2008With argument of 0, never makes the previous version into a backup file.
2009
2010If a file's name is FOO, the names of its numbered backup versions are
2011 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2012Numeric backups (rather than FOO~) will be made if value of
2013 `version-control' is not the atom `never' and either there are already
2014 numeric versions of the file being backed up, or `version-control' is
2015 non-nil.
2016We don't want excessive versions piling up, so there are variables
2017 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2018 and `kept-new-versions', which tells how many newest versions to keep.
2019 Defaults are 2 old versions and 2 new.
2020`dired-kept-versions' controls dired's clean-directory (.) command.
de7d5e1b 2021If `delete-old-versions' is nil, system will query user
b4da00e9
RM
2022 before trimming versions. Otherwise it does it silently."
2023 (interactive "p")
2024 (let ((modp (buffer-modified-p))
2025 (large (> (buffer-size) 50000))
b5a8e0fc
RS
2026 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2027 (memq args '(16 64)))))
b4da00e9
RM
2028 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2029 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
2030 (basic-save-buffer)
2031 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2032
2033(defun delete-auto-save-file-if-necessary (&optional force)
2034 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2035Normally delete only if the file was written by this Emacs since
2036the last real save, but optional arg FORCE non-nil means delete anyway."
2037 (and buffer-auto-save-file-name delete-auto-save-files
2038 (not (string= buffer-file-name buffer-auto-save-file-name))
2039 (or force (recent-auto-save-p))
2040 (progn
2041 (condition-case ()
2042 (delete-file buffer-auto-save-file-name)
2043 (file-error nil))
2044 (set-buffer-auto-saved))))
2045
1cc852cc
RS
2046(defvar after-save-hook nil
2047 "Normal hook that is run after a buffer is saved to its file.")
2048
b4da00e9 2049(defun basic-save-buffer ()
1cc852cc
RS
2050 "Save the current buffer in its visited file, if it has been modified.
2051After saving the buffer, run `after-save-hook'."
b4da00e9 2052 (interactive)
c11a94fe
RS
2053 (save-excursion
2054 ;; In an indirect buffer, save its base buffer instead.
2055 (if (buffer-base-buffer)
2056 (set-buffer (buffer-base-buffer)))
2057 (if (buffer-modified-p)
2058 (let ((recent-save (recent-auto-save-p))
2059 setmodes tempsetmodes)
2060 ;; On VMS, rename file and buffer to get rid of version number.
2061 (if (and (eq system-type 'vax-vms)
2062 (not (string= buffer-file-name
2063 (file-name-sans-versions buffer-file-name))))
2064 (let (buffer-new-name)
2065 ;; Strip VMS version number before save.
2066 (setq buffer-file-name
2067 (file-name-sans-versions buffer-file-name))
2068 ;; Construct a (unique) buffer name to correspond.
2069 (let ((buf (create-file-buffer (downcase buffer-file-name))))
2070 (setq buffer-new-name (buffer-name buf))
2071 (kill-buffer buf))
2072 (rename-buffer buffer-new-name)))
2073 ;; If buffer has no file name, ask user for one.
2074 (or buffer-file-name
182891ef
RS
2075 (let ((filename
2076 (expand-file-name
2077 (read-file-name "File to save in: ") nil)))
2078 (and (file-exists-p filename)
2079 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2080 filename))
2081 (error "Canceled")))
2082 (set-visited-file-name filename)))
c11a94fe
RS
2083 (or (verify-visited-file-modtime (current-buffer))
2084 (not (file-exists-p buffer-file-name))
2085 (yes-or-no-p
2086 (format "%s has changed since visited or saved. Save anyway? "
2087 (file-name-nondirectory buffer-file-name)))
2088 (error "Save not confirmed"))
2089 (save-restriction
2090 (widen)
2091 (and (> (point-max) 1)
2092 (/= (char-after (1- (point-max))) ?\n)
2093 (not (and (eq selective-display t)
2094 (= (char-after (1- (point-max))) ?\r)))
2095 (or (eq require-final-newline t)
2096 (and require-final-newline
2097 (y-or-n-p
2098 (format "Buffer %s does not end in newline. Add one? "
2099 (buffer-name)))))
2100 (save-excursion
2101 (goto-char (point-max))
2102 (insert ?\n)))
2103 (or (run-hook-with-args-until-success 'write-contents-hooks)
2104 (run-hook-with-args-until-success 'local-write-file-hooks)
2105 (run-hook-with-args-until-success 'write-file-hooks)
2106 ;; If a hook returned t, file is already "written".
2107 ;; Otherwise, write it the usual way now.
2108 (setq setmodes (basic-save-buffer-1)))
2a47b4f5
RS
2109 (setq buffer-file-number
2110 (nthcdr 10 (file-attributes buffer-file-name)))
c11a94fe
RS
2111 (if setmodes
2112 (condition-case ()
2113 (set-file-modes buffer-file-name setmodes)
2114 (error nil))))
2115 ;; If the auto-save file was recent before this command,
2116 ;; delete it now.
2117 (delete-auto-save-file-if-necessary recent-save)
49530862
RS
2118 ;; Support VC `implicit' locking.
2119 (vc-after-save)
c11a94fe
RS
2120 (run-hooks 'after-save-hook))
2121 (message "(No changes need to be saved)"))))
b4da00e9 2122
87d26afc
RS
2123;; This does the "real job" of writing a buffer into its visited file
2124;; and making a backup file. This is what is normally done
2125;; but inhibited if one of write-file-hooks returns non-nil.
2126;; It returns a value to store in setmodes.
2127(defun basic-save-buffer-1 ()
2128 (let (tempsetmodes setmodes)
2129 (if (not (file-writable-p buffer-file-name))
2130 (let ((dir (file-name-directory buffer-file-name)))
2131 (if (not (file-directory-p dir))
2132 (error "%s is not a directory" dir)
2133 (if (not (file-exists-p buffer-file-name))
2134 (error "Directory %s write-protected" dir)
2135 (if (yes-or-no-p
2136 (format "File %s is write-protected; try to save anyway? "
2137 (file-name-nondirectory
2138 buffer-file-name)))
2139 (setq tempsetmodes t)
2140 (error "Attempt to save to a file which you aren't allowed to write"))))))
2141 (or buffer-backed-up
2142 (setq setmodes (backup-buffer)))
76d5492b 2143 (let ((dir (file-name-directory buffer-file-name)))
f4a0f59b
RS
2144 (if (and file-precious-flag
2145 (file-writable-p dir))
2146 ;; If file is precious, write temp name, then rename it.
2147 ;; This requires write access to the containing dir,
2148 ;; which is why we don't try it if we don't have that access.
2149 (let ((realname buffer-file-name)
6782610c
RS
2150 tempname temp nogood i succeed
2151 (old-modtime (visited-file-modtime)))
f4a0f59b
RS
2152 (setq i 0)
2153 (setq nogood t)
2154 ;; Find the temporary name to write under.
2155 (while nogood
567c1ca9 2156 (setq tempname (format
28ee503c
KH
2157 (if (and (eq system-type 'ms-dos)
2158 (not (msdos-long-file-names)))
567c1ca9
RS
2159 "%s#%d.tm#" ; MSDOS limits files to 8+3
2160 "%s#tmp#%d")
2161 dir i))
f4a0f59b
RS
2162 (setq nogood (file-exists-p tempname))
2163 (setq i (1+ i)))
2164 (unwind-protect
2165 (progn (clear-visited-file-modtime)
2166 (write-region (point-min) (point-max)
89095962
RS
2167 tempname nil realname
2168 buffer-file-truename)
f4a0f59b
RS
2169 (setq succeed t))
2170 ;; If writing the temp file fails,
2171 ;; delete the temp file.
76d5492b 2172 (or succeed
6782610c
RS
2173 (progn
2174 (delete-file tempname)
2175 (set-visited-file-modtime old-modtime))))
f4a0f59b
RS
2176 ;; Since we have created an entirely new file
2177 ;; and renamed it, make sure it gets the
2178 ;; right permission bits set.
2179 (setq setmodes (file-modes buffer-file-name))
2180 ;; We succeeded in writing the temp file,
2181 ;; so rename it.
2182 (rename-file tempname buffer-file-name t))
2183 ;; If file not writable, see if we can make it writable
2184 ;; temporarily while we write it.
2185 ;; But no need to do so if we have just backed it up
2186 ;; (setmodes is set) because that says we're superseding.
2187 (cond ((and tempsetmodes (not setmodes))
2188 ;; Change the mode back, after writing.
2189 (setq setmodes (file-modes buffer-file-name))
2190 (set-file-modes buffer-file-name 511)))
2191 (write-region (point-min) (point-max)
89095962 2192 buffer-file-name nil t buffer-file-truename)))
87d26afc
RS
2193 setmodes))
2194
b4da00e9
RM
2195(defun save-some-buffers (&optional arg exiting)
2196 "Save some modified file-visiting buffers. Asks user about each one.
5bbbceb1
JB
2197Optional argument (the prefix) non-nil means save all with no questions.
2198Optional second argument EXITING means ask about certain non-file buffers
2199 as well as about file buffers."
b4da00e9 2200 (interactive "P")
907482b9 2201 (save-window-excursion
76d5492b
RM
2202 (let* ((queried nil)
2203 (files-done
2204 (map-y-or-n-p
2205 (function
2206 (lambda (buffer)
2207 (and (buffer-modified-p buffer)
2208 (not (buffer-base-buffer buffer))
2209 (or
2210 (buffer-file-name buffer)
2211 (and exiting
2212 (progn
2213 (set-buffer buffer)
2214 (and buffer-offer-save (> (buffer-size) 0)))))
2215 (if arg
2216 t
2217 (setq queried t)
2218 (if (buffer-file-name buffer)
2219 (format "Save file %s? "
2220 (buffer-file-name buffer))
2221 (format "Save buffer %s? "
2222 (buffer-name buffer)))))))
2223 (function
2224 (lambda (buffer)
2225 (set-buffer buffer)
2226 (save-buffer)))
2227 (buffer-list)
2228 '("buffer" "buffers" "save")
2229 (list (list ?\C-r (lambda (buf)
2230 (view-buffer buf)
2231 (setq view-exit-action
2232 '(lambda (ignore)
2233 (exit-recursive-edit)))
2234 (recursive-edit)
2235 ;; Return nil to ask about BUF again.
2236 nil)
2237 "display the current buffer"))))
2238 (abbrevs-done
2239 (and save-abbrevs abbrevs-changed
2240 (progn
2241 (if (or arg
2242 (y-or-n-p (format "Save abbrevs in %s? "
2243 abbrev-file-name)))
2244 (write-abbrev-file nil))
2245 ;; Don't keep bothering user if he says no.
2246 (setq abbrevs-changed nil)
2247 t))))
2248 (or queried (> files-done 0) abbrevs-done
5625c2fc 2249 (message "(No files need saving)")))))
b4da00e9
RM
2250\f
2251(defun not-modified (&optional arg)
2252 "Mark current buffer as unmodified, not needing to be saved.
a641f9a1
RM
2253With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2254
2255It is not a good idea to use this function in Lisp programs, because it
2256prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
b4da00e9
RM
2257 (interactive "P")
2258 (message (if arg "Modification-flag set"
2259 "Modification-flag cleared"))
2260 (set-buffer-modified-p arg))
2261
2262(defun toggle-read-only (&optional arg)
2263 "Change whether this buffer is visiting its file read-only.
2264With arg, set read-only iff arg is positive."
2265 (interactive "P")
2266 (setq buffer-read-only
2267 (if (null arg)
2268 (not buffer-read-only)
2269 (> (prefix-numeric-value arg) 0)))
3941fe2c 2270 (force-mode-line-update))
b4da00e9 2271
82d0954a 2272(defun insert-file (filename &optional coding-system)
b4da00e9
RM
2273 "Insert contents of file FILENAME into buffer after point.
2274Set mark after the inserted text.
82d0954a 2275A prefix argument enables user to specify the coding-system interactively.
b4da00e9
RM
2276
2277This function is meant for the user to run interactively.
2278Don't call it from programs! Use `insert-file-contents' instead.
2279\(Its calling sequence is different; see its documentation)."
82d0954a 2280 (interactive "*fInsert file: \nZCoding-system: ")
3be6243a
RS
2281 (if (file-directory-p filename)
2282 (signal 'file-error (list "Opening input file" "file is a directory"
2283 filename)))
82d0954a
KH
2284 (let ((tem
2285 (if coding-system
2286 (let ((coding-system-for-read coding-system))
2287 (insert-file-contents filename))
2288 (insert-file-contents filename))))
b4da00e9
RM
2289 (push-mark (+ (point) (car (cdr tem))))))
2290
82d0954a 2291(defun append-to-file (start end filename &optional coding-system)
b4da00e9
RM
2292 "Append the contents of the region to the end of file FILENAME.
2293When called from a function, expects three arguments,
2294START, END and FILENAME. START and END are buffer positions
82d0954a
KH
2295saying what text to write.
2296A prefix argument enables user to specify the coding-system interactively."
2297 (interactive "r\nFAppend to file: \nZCoding-system: ")
2298 (if coding-system
2299 (let ((coding-system-for-write coding-system))
2300 (write-region start end filename t))
2301 (write-region start end filename t)))
b4da00e9
RM
2302
2303(defun file-newest-backup (filename)
2304 "Return most recent backup file for FILENAME or nil if no backups exist."
2305 (let* ((filename (expand-file-name filename))
2306 (file (file-name-nondirectory filename))
2307 (dir (file-name-directory filename))
2308 (comp (file-name-all-completions file dir))
cf7e94a0
RS
2309 (newest nil)
2310 tem)
b4da00e9 2311 (while comp
cf7e94a0 2312 (setq tem (car comp)
b4da00e9 2313 comp (cdr comp))
cf7e94a0
RS
2314 (cond ((and (backup-file-name-p tem)
2315 (string= (file-name-sans-versions tem) file))
2316 (setq tem (concat dir tem))
2317 (if (or (null newest)
2318 (file-newer-than-file-p tem newest))
2319 (setq newest tem)))))
b4da00e9
RM
2320 newest))
2321
2322(defun rename-uniquely ()
2323 "Rename current buffer to a similar name not already taken.
2324This function is useful for creating multiple shell process buffers
2325or multiple mail buffers, etc."
2326 (interactive)
40eb8038 2327 (save-match-data
ed34f320
RS
2328 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2329 (not (and buffer-file-name
2330 (string= (buffer-name)
2331 (file-name-nondirectory
2332 buffer-file-name)))))
2333 ;; If the existing buffer name has a <NNN>,
2334 ;; which isn't part of the file name (if any),
2335 ;; then get rid of that.
40eb8038
RS
2336 (substring (buffer-name) 0 (match-beginning 0))
2337 (buffer-name)))
2338 (new-buf (generate-new-buffer base-name))
2339 (name (buffer-name new-buf)))
2340 (kill-buffer new-buf)
2341 (rename-buffer name)
3941fe2c 2342 (force-mode-line-update))))
5bbbceb1 2343
4e43240a 2344(defun make-directory (dir &optional parents)
5ce8bb89
RS
2345 "Create the directory DIR and any nonexistent parent dirs.
2346Interactively, the default choice of directory to create
2347is the current default directory for file names.
0225ae5e 2348That is useful when you have visited a file in a nonexistent directory.
5ce8bb89
RS
2349
2350Noninteractively, the second (optional) argument PARENTS says whether
2351to create parent directories if they don't exist."
2352 (interactive
2353 (list (read-file-name "Make directory: " default-directory default-directory
2354 nil nil)
2355 t))
6eaebaa2 2356 (let ((handler (find-file-name-handler dir 'make-directory)))
4e43240a
RS
2357 (if handler
2358 (funcall handler 'make-directory dir parents)
2359 (if (not parents)
2360 (make-directory-internal dir)
2361 (let ((dir (directory-file-name (expand-file-name dir)))
2362 create-list)
2363 (while (not (file-exists-p dir))
76d5492b 2364 (setq create-list (cons dir create-list)
4e43240a
RS
2365 dir (directory-file-name (file-name-directory dir))))
2366 (while create-list
2367 (make-directory-internal (car create-list))
2368 (setq create-list (cdr create-list))))))))
b4da00e9
RM
2369\f
2370(put 'revert-buffer-function 'permanent-local t)
2371(defvar revert-buffer-function nil
0973d78b
RS
2372 "Function to use to revert this buffer, or nil to do the default.
2373The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2374which are the arguments that `revert-buffer' received.")
b4da00e9
RM
2375
2376(put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2377(defvar revert-buffer-insert-file-contents-function nil
2378 "Function to use to insert contents when reverting this buffer.
2379Gets two args, first the nominal file name to use,
2380and second, t if reading the auto-save file.")
2381
5f76e7d4
KH
2382(defvar before-revert-hook nil
2383 "Normal hook for `revert-buffer' to run before reverting.
2384If `revert-buffer-function' is used to override the normal revert
2385mechanism, this hook is not used.")
2386
2387(defvar after-revert-hook nil
2388 "Normal hook for `revert-buffer' to run after reverting.
2389Note that the hook value that it runs is the value that was in effect
2390before reverting; that makes a difference if you have buffer-local
2391hook functions.
2392
2393If `revert-buffer-function' is used to override the normal revert
2394mechanism, this hook is not used.")
2395
9a30563f 2396(defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
7e7c9c4e 2397 "Replace current buffer text with the text of the visited file on disk.
b4da00e9 2398This undoes all changes since the file was visited or saved.
8c0e7b73
JB
2399With a prefix argument, offer to revert from latest auto-save file, if
2400that is more recent than the visited file.
1ab31687 2401
7e7c9c4e
RS
2402This command also works for special buffers that contain text which
2403doesn't come from a file, but reflects some other data base instead:
2404for example, Dired buffers and buffer-list buffers. In these cases,
2405it reconstructs the buffer contents from the appropriate data base.
2406
65ee6096 2407When called from Lisp, the first argument is IGNORE-AUTO; only offer
1ab31687
JB
2408to revert from the auto-save file when this is nil. Note that the
2409sense of this argument is the reverse of the prefix argument, for the
2410sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2411to nil.
2412
2413Optional second argument NOCONFIRM means don't ask for confirmation at
2414all.
b4da00e9 2415
5b2b26d5
RS
2416Optional third argument PRESERVE-MODES non-nil means don't alter
2417the files modes. Normally we reinitialize them using `normal-mode'.
2418
8c0e7b73 2419If the value of `revert-buffer-function' is non-nil, it is called to
7e7c9c4e
RS
2420do all the work for this command. Otherwise, the hooks
2421`before-revert-hook' and `after-revert-hook' are run at the beginning
2422and the end, and if `revert-buffer-insert-file-contents-function' is
2423non-nil, it is called instead of rereading visited file contents."
fb6208a6 2424
1ab31687
JB
2425 ;; I admit it's odd to reverse the sense of the prefix argument, but
2426 ;; there is a lot of code out there which assumes that the first
2427 ;; argument should be t to avoid consulting the auto-save file, and
2428 ;; there's no straightforward way to encourage authors to notice a
2429 ;; reversal of the argument sense. So I'm just changing the user
2430 ;; interface, but leaving the programmatic interface the same.
e0867e99 2431 (interactive (list (not current-prefix-arg)))
b4da00e9 2432 (if revert-buffer-function
1ab31687 2433 (funcall revert-buffer-function ignore-auto noconfirm)
b4da00e9 2434 (let* ((opoint (point))
1ab31687
JB
2435 (auto-save-p (and (not ignore-auto)
2436 (recent-auto-save-p)
b4da00e9
RM
2437 buffer-auto-save-file-name
2438 (file-readable-p buffer-auto-save-file-name)
2439 (y-or-n-p
2440 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2441 (file-name (if auto-save-p
2442 buffer-auto-save-file-name
2443 buffer-file-name)))
2444 (cond ((null file-name)
2445 (error "Buffer does not seem to be associated with any file"))
2446 ((or noconfirm
2447 (yes-or-no-p (format "Revert buffer from file %s? "
2448 file-name)))
4fbf62ee 2449 (run-hooks 'before-revert-hook)
b4da00e9
RM
2450 ;; If file was backed up but has changed since,
2451 ;; we shd make another backup.
2452 (and (not auto-save-p)
5bbbceb1 2453 (not (verify-visited-file-modtime (current-buffer)))
b4da00e9
RM
2454 (setq buffer-backed-up nil))
2455 ;; Get rid of all undo records for this buffer.
2456 (or (eq buffer-undo-list t)
2457 (setq buffer-undo-list nil))
ba5c8c93
KH
2458 ;; Effectively copy the after-revert-hook status,
2459 ;; since after-find-file will clobber it.
2460 (let ((global-hook (default-value 'after-revert-hook))
2461 (local-hook-p (local-variable-p 'after-revert-hook))
2462 (local-hook (and (local-variable-p 'after-revert-hook)
2463 after-revert-hook)))
2464 (let (buffer-read-only
2465 ;; Don't make undo records for the reversion.
2466 (buffer-undo-list t))
2467 (if revert-buffer-insert-file-contents-function
2468 (funcall revert-buffer-insert-file-contents-function
2469 file-name auto-save-p)
2470 (if (not (file-exists-p file-name))
2471 (error "File %s no longer exists!" file-name))
2472 ;; Bind buffer-file-name to nil
2473 ;; so that we don't try to lock the file.
2474 (let ((buffer-file-name nil))
2475 (or auto-save-p
2476 (unlock-buffer)))
2477 (widen)
2478 (insert-file-contents file-name (not auto-save-p)
2479 nil nil t)))
2480 (goto-char (min opoint (point-max)))
2481 ;; Recompute the truename in case changes in symlinks
2482 ;; have changed the truename.
2483 (setq buffer-file-truename
2484 (abbreviate-file-name (file-truename buffer-file-name)))
9a30563f 2485 (after-find-file nil nil t t preserve-modes)
ba5c8c93
KH
2486 ;; Run after-revert-hook as it was before we reverted.
2487 (setq-default revert-buffer-internal-hook global-hook)
2488 (if local-hook-p
2489 (progn
2490 (make-local-variable 'revert-buffer-internal-hook)
2491 (setq revert-buffer-internal-hook local-hook))
2492 (kill-local-variable 'revert-buffer-internal-hook))
2493 (run-hooks 'revert-buffer-internal-hook))
4fbf62ee 2494 t)))))
b4da00e9
RM
2495
2496(defun recover-file (file)
2497 "Visit file FILE, but get contents from its last auto-save file."
10f7c7fc
RS
2498 ;; Actually putting the file name in the minibuffer should be used
2499 ;; only rarely.
2500 ;; Not just because users often use the default.
e1dadc17 2501 (interactive "FRecover file: ")
b4da00e9 2502 (setq file (expand-file-name file))
f7da6740
RS
2503 (if (auto-save-file-name-p (file-name-nondirectory file))
2504 (error "%s is an auto-save file" file))
b4da00e9
RM
2505 (let ((file-name (let ((buffer-file-name file))
2506 (make-auto-save-file-name))))
945e1965
RS
2507 (cond ((if (file-exists-p file)
2508 (not (file-newer-than-file-p file-name file))
2509 (not (file-exists-p file-name)))
b4da00e9
RM
2510 (error "Auto-save file %s not current" file-name))
2511 ((save-window-excursion
2512 (if (not (eq system-type 'vax-vms))
2513 (with-output-to-temp-buffer "*Directory*"
2514 (buffer-disable-undo standard-output)
2515 (call-process "ls" nil standard-output nil
2dc2b736
RS
2516 (if (file-symlink-p file) "-lL" "-l")
2517 file file-name)))
b4da00e9
RM
2518 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2519 (switch-to-buffer (find-file-noselect file t))
82d0954a
KH
2520 (let ((buffer-read-only nil)
2521 ;; Auto-saved file shoule be read without any code conversion.
2522 (coding-system-for-read 'no-conversion))
b4da00e9
RM
2523 (erase-buffer)
2524 (insert-file-contents file-name nil))
8cfb9d46 2525 (after-find-file nil nil t))
ffa7ab70 2526 (t (error "Recover-file cancelled")))))
b4da00e9 2527
6598027d 2528(defun recover-session ()
9aee5392
RS
2529 "Recover auto save files from a previous Emacs session.
2530This command first displays a Dired buffer showing you the
2531previous sessions that you could recover from.
2532To choose one, move point to the proper line and then type C-c C-c.
2533Then you'll be asked about a number of files to recover."
2534 (interactive)
363a5030
RS
2535 (if (null auto-save-list-file-prefix)
2536 (error "You set `auto-save-list-file-prefix' to disable making session files"))
6f4983e6 2537 (let ((ls-lisp-support-shell-wildcards t))
7b3478a5
RS
2538 (dired (concat auto-save-list-file-prefix "*")
2539 (concat dired-listing-switches "t")))
9aee5392
RS
2540 (goto-char (point-min))
2541 (or (looking-at "Move to the session you want to recover,")
2542 (let ((inhibit-read-only t))
033ef863
RS
2543 (insert "Move to the session you want to recover,\n"
2544 "then type C-c C-c to select it.\n\n"
2545 "You can also delete some of these files;\n"
2546 "type d on a line to mark that file for deletion.\n\n")))
9aee5392 2547 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
80280bb7 2548 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
9aee5392 2549
80280bb7 2550(defun recover-session-finish ()
9aee5392
RS
2551 "Choose one saved session to recover auto-save files from.
2552This command is used in the special Dired buffer created by
80280bb7 2553\\[recover-session]."
9aee5392
RS
2554 (interactive)
2555 ;; Get the name of the session file to recover from.
2556 (let ((file (dired-get-filename))
953a03b2 2557 files
9aee5392 2558 (buffer (get-buffer-create " *recover*")))
033ef863 2559 (dired-do-flagged-delete t)
9aee5392
RS
2560 (unwind-protect
2561 (save-excursion
2562 ;; Read in the auto-save-list file.
2563 (set-buffer buffer)
2564 (erase-buffer)
2565 (insert-file-contents file)
953a03b2
RS
2566 ;; Loop thru the text of that file
2567 ;; and get out the names of the files to recover.
2568 (while (not (eobp))
2569 (let (thisfile autofile)
2570 (if (eolp)
2571 ;; This is a pair of lines for a non-file-visiting buffer.
2572 ;; Get the auto-save file name and manufacture
2573 ;; a "visited file name" from that.
2574 (progn
2575 (forward-line 1)
2576 (setq autofile
2577 (buffer-substring-no-properties
2578 (point)
2579 (save-excursion
2580 (end-of-line)
2581 (point))))
2582 (setq thisfile
2583 (expand-file-name
2584 (substring
2585 (file-name-nondirectory autofile)
2586 1 -1)
2587 (file-name-directory autofile)))
2588 (forward-line 1))
2589 ;; This pair of lines is a file-visiting
2590 ;; buffer. Use the visited file name.
2591 (progn
2592 (setq thisfile
2593 (buffer-substring-no-properties
2594 (point) (progn (end-of-line) (point))))
2595 (forward-line 1)
2596 (setq autofile
2597 (buffer-substring-no-properties
2598 (point) (progn (end-of-line) (point))))
2599 (forward-line 1)))
2600 ;; Ignore a file if its auto-save file does not exist now.
2601 (if (file-exists-p autofile)
2602 (setq files (cons thisfile files)))))
2603 (setq files (nreverse files))
945e1965
RS
2604 ;; The file contains a pair of line for each auto-saved buffer.
2605 ;; The first line of the pair contains the visited file name
2606 ;; or is empty if the buffer was not visiting a file.
2607 ;; The second line is the auto-save file name.
953a03b2
RS
2608 (if files
2609 (map-y-or-n-p "Recover %s? "
2610 (lambda (file)
2611 (condition-case nil
2612 (save-excursion (recover-file file))
76d5492b 2613 (error
953a03b2
RS
2614 "Failed to recover `%s'" file)))
2615 files
2616 '("file" "files" "recover"))
2617 (message "No files can be recovered from this session now")))
9aee5392
RS
2618 (kill-buffer buffer))))
2619
73ba610a
RS
2620(defun kill-some-buffers (&optional list)
2621 "For each buffer in LIST, ask whether to kill it.
2622LIST defaults to all existing live buffers."
b4da00e9 2623 (interactive)
73ba610a
RS
2624 (if (null list)
2625 (setq list (buffer-list)))
2626 (while list
2627 (let* ((buffer (car list))
2628 (name (buffer-name buffer)))
2629 (and (not (string-equal name ""))
2630 (/= (aref name 0) ? )
2631 (yes-or-no-p
2632 (format "Buffer %s %s. Kill? "
2633 name
2634 (if (buffer-modified-p buffer)
2635 "HAS BEEN EDITED" "is unmodified")))
2636 (kill-buffer buffer)))
2637 (setq list (cdr list))))
b4da00e9
RM
2638\f
2639(defun auto-save-mode (arg)
2640 "Toggle auto-saving of contents of current buffer.
f3e23606 2641With prefix argument ARG, turn auto-saving on if positive, else off."
b4da00e9
RM
2642 (interactive "P")
2643 (setq buffer-auto-save-file-name
2644 (and (if (null arg)
74b9c2af
RS
2645 (or (not buffer-auto-save-file-name)
2646 ;; If autosave is off because buffer has shrunk,
2647 ;; then toggling should turn it on.
2648 (< buffer-saved-size 0))
b4da00e9
RM
2649 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2650 (if (and buffer-file-name auto-save-visited-file-name
2651 (not buffer-read-only))
2652 buffer-file-name
2653 (make-auto-save-file-name))))
0b7f1ef2
RS
2654 ;; If -1 was stored here, to temporarily turn off saving,
2655 ;; turn it back on.
2656 (and (< buffer-saved-size 0)
2657 (setq buffer-saved-size 0))
b4da00e9
RM
2658 (if (interactive-p)
2659 (message "Auto-save %s (in this buffer)"
2660 (if buffer-auto-save-file-name "on" "off")))
2661 buffer-auto-save-file-name)
2662
2663(defun rename-auto-save-file ()
2664 "Adjust current buffer's auto save file name for current conditions.
2665Also rename any existing auto save file, if it was made in this session."
2666 (let ((osave buffer-auto-save-file-name))
2667 (setq buffer-auto-save-file-name
2668 (make-auto-save-file-name))
2669 (if (and osave buffer-auto-save-file-name
2670 (not (string= buffer-auto-save-file-name buffer-file-name))
2671 (not (string= buffer-auto-save-file-name osave))
2672 (file-exists-p osave)
2673 (recent-auto-save-p))
2674 (rename-file osave buffer-auto-save-file-name t))))
2675
2676(defun make-auto-save-file-name ()
2677 "Return file name to use for auto-saves of current buffer.
2678Does not consider `auto-save-visited-file-name' as that variable is checked
2679before calling this function. You can redefine this for customization.
2680See also `auto-save-file-name-p'."
2681 (if buffer-file-name
28ee503c
KH
2682 (if (and (eq system-type 'ms-dos)
2683 (not (msdos-long-file-names)))
4503dacb
RS
2684 (let ((fn (file-name-nondirectory buffer-file-name)))
2685 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
2686 (concat (file-name-directory buffer-file-name)
2687 "#" (match-string 1 fn)
2688 "." (match-string 3 fn) "#"))
2689 (concat (file-name-directory buffer-file-name)
2690 "#"
2691 (file-name-nondirectory buffer-file-name)
2692 "#"))
0a1763b4
RS
2693
2694 ;; Deal with buffers that don't have any associated files. (Mail
2695 ;; mode tends to create a good number of these.)
2696
7d483e8c 2697 (let ((buffer-name (buffer-name))
0a1763b4 2698 (limit 0))
c3348e10
RS
2699 ;; Eliminate all slashes and backslashes by
2700 ;; replacing them with sequences that start with %.
2701 ;; Quote % also, to keep distinct names distinct.
2702 (while (string-match "[/\\%]" buffer-name limit)
2703 (let* ((character (aref buffer-name (match-beginning 0)))
2704 (replacement
2705 (cond ((eq character ?%) "%%")
2706 ((eq character ?/) "%+")
2707 ((eq character ?\\) "%-"))))
2708 (setq buffer-name (replace-match replacement t t buffer-name))
2709 (setq limit (1+ (match-end 0)))))
a8abaf83
RS
2710 ;; Generate the file name.
2711 (expand-file-name
2712 (format "#%s#%s#" buffer-name (make-temp-name ""))
2713 ;; Try a few alternative directories, to get one we can write it.
2714 (cond
2715 ((file-writable-p default-directory) default-directory)
2716 ((file-writable-p "/var/tmp/") "/var/tmp/")
2717 ("~/"))))))
b4da00e9
RM
2718
2719(defun auto-save-file-name-p (filename)
2720 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2721FILENAME should lack slashes. You can redefine this for customization."
2722 (string-match "^#.*#$" filename))
2723\f
6f4983e6
RS
2724(defun wildcard-to-regexp (wildcard)
2725 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2726The generated regexp will match a filename iff the filename
2727matches that wildcard according to shell rules. Only wildcards known
2728by `sh' are supported."
2729 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
2730 ;; Copy the initial run of non-special characters.
2731 (result (substring wildcard 0 i))
2732 (len (length wildcard)))
2733 ;; If no special characters, we're almost done.
2734 (if i
2735 (while (< i len)
2736 (let ((ch (aref wildcard i))
2737 j)
2738 (setq
2739 result
2740 (concat result
2741 (cond
7e7c9c4e
RS
2742 ((and (eq ch ?\[)
2743 (< (1+ i) len)
2744 (eq (aref wildcard (1+ i)) ?\]))
2745 "\\[")
6f4983e6
RS
2746 ((eq ch ?\[) ; [...] maps to regexp char class
2747 (progn
2748 (setq i (1+ i))
2749 (concat
2750 (cond
2751 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
2752 (progn
2753 (setq i (1+ i))
2754 (if (eq (aref wildcard i) ?\])
2755 (progn
2756 (setq i (1+ i))
2757 "[^]")
2758 "[^")))
2759 ((eq (aref wildcard i) ?^)
2760 ;; Found "[^". Insert a `\0' character
2761 ;; (which cannot happen in a filename)
2762 ;; into the character class, so that `^'
2763 ;; is not the first character after `[',
2764 ;; and thus non-special in a regexp.
2765 (progn
2766 (setq i (1+ i))
2767 "[\000^"))
2768 ((eq (aref wildcard i) ?\])
2769 ;; I don't think `]' can appear in a
2770 ;; character class in a wildcard, but
2771 ;; let's be general here.
2772 (progn
2773 (setq i (1+ i))
2774 "[]"))
2775 (t "["))
2776 (prog1 ; copy everything upto next `]'.
2777 (substring wildcard
2778 i
2779 (setq j (string-match
2780 "]" wildcard i)))
2781 (setq i (if j (1- j) (1- len)))))))
2782 ((eq ch ?.) "\\.")
2783 ((eq ch ?*) "[^\000]*")
2784 ((eq ch ?+) "\\+")
2785 ((eq ch ?^) "\\^")
2786 ((eq ch ?$) "\\$")
2787 ((eq ch ?\\) "\\\\") ; probably cannot happen...
2788 ((eq ch ??) "[^\000]")
2789 (t (char-to-string ch)))))
2790 (setq i (1+ i)))))
2791 ;; Shell wildcards should match the entire filename,
2792 ;; not its part. Make the regexp say so.
2793 (concat "\\`" result "\\'")))
2794\f
21540597 2795(defcustom list-directory-brief-switches
b4da00e9 2796 (if (eq system-type 'vax-vms) "" "-CF")
21540597
RS
2797 "*Switches for list-directory to pass to `ls' for brief listing,"
2798 :type 'string
2799 :group 'dired)
b4da00e9 2800
21540597 2801(defcustom list-directory-verbose-switches
b4da00e9
RM
2802 (if (eq system-type 'vax-vms)
2803 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2804 "-l")
21540597
RS
2805 "*Switches for list-directory to pass to `ls' for verbose listing,"
2806 :type 'string
2807 :group 'dired)
b4da00e9
RM
2808
2809(defun list-directory (dirname &optional verbose)
2810 "Display a list of files in or matching DIRNAME, a la `ls'.
2811DIRNAME is globbed by the shell if necessary.
2812Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2813Actions controlled by variables `list-directory-brief-switches'
2814and `list-directory-verbose-switches'."
2815 (interactive (let ((pfx current-prefix-arg))
2816 (list (read-file-name (if pfx "List directory (verbose): "
2817 "List directory (brief): ")
2818 nil default-directory nil)
2819 pfx)))
2820 (let ((switches (if verbose list-directory-verbose-switches
2821 list-directory-brief-switches)))
2822 (or dirname (setq dirname default-directory))
2823 (setq dirname (expand-file-name dirname))
2824 (with-output-to-temp-buffer "*Directory*"
2825 (buffer-disable-undo standard-output)
2826 (princ "Directory ")
2827 (princ dirname)
2828 (terpri)
c3554e95
RS
2829 (save-excursion
2830 (set-buffer "*Directory*")
5a8a160e
RS
2831 (setq default-directory
2832 (if (file-directory-p dirname)
2833 (file-name-as-directory dirname)
2834 (file-name-directory dirname)))
c3554e95
RS
2835 (let ((wildcard (not (file-directory-p dirname))))
2836 (insert-directory dirname switches wildcard (not wildcard)))))))
2837
2838(defvar insert-directory-program "ls"
2839 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2840
2841;; insert-directory
2842;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2843;; FULL-DIRECTORY-P is nil.
2844;; The single line of output must display FILE's name as it was
2845;; given, namely, an absolute path name.
2846;; - must insert exactly one line for each file if WILDCARD or
2847;; FULL-DIRECTORY-P is t, plus one optional "total" line
2848;; before the file lines, plus optional text after the file lines.
2849;; Lines are delimited by "\n", so filenames containing "\n" are not
2850;; allowed.
2851;; File lines should display the basename.
2852;; - must be consistent with
2853;; - functions dired-move-to-filename, (these two define what a file line is)
2854;; dired-move-to-end-of-filename,
2855;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2856;; dired-insert-headerline
2857;; dired-after-subdir-garbage (defines what a "total" line is)
2858;; - variable dired-subdir-regexp
2859(defun insert-directory (file switches &optional wildcard full-directory-p)
a18b7c81 2860 "Insert directory listing for FILE, formatted according to SWITCHES.
c3554e95 2861Leaves point after the inserted text.
727d277d 2862SWITCHES may be a string of options, or a list of strings.
c3554e95
RS
2863Optional third arg WILDCARD means treat FILE as shell wildcard.
2864Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2865switches do not contain `d', so that a full listing is expected.
2866
2867This works by running a directory listing program
406e12d9 2868whose name is in the variable `insert-directory-program'.
c3554e95 2869If WILDCARD, it also runs the shell specified by `shell-file-name'."
c870ab8e
RS
2870 ;; We need the directory in order to find the right handler.
2871 (let ((handler (find-file-name-handler (expand-file-name file)
2872 'insert-directory)))
c3554e95
RS
2873 (if handler
2874 (funcall handler 'insert-directory file switches
2875 wildcard full-directory-p)
b4da00e9 2876 (if (eq system-type 'vax-vms)
c3554e95 2877 (vms-read-directory file switches (current-buffer))
b7fa904c
RS
2878 (or (= 0
2879 (if wildcard
2880 ;; Run ls in the directory of the file pattern we asked for.
2881 (let ((default-directory
2882 (if (file-name-absolute-p file)
2883 (file-name-directory file)
2884 (file-name-directory (expand-file-name file))))
2885 (pattern (file-name-nondirectory file))
2886 (beg 0))
2887 ;; Quote some characters that have special meanings in shells;
2888 ;; but don't quote the wildcards--we want them to be special.
2889 ;; We also currently don't quote the quoting characters
2890 ;; in case people want to use them explicitly to quote
2891 ;; wildcard characters.
2892 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
2893 (setq pattern
2894 (concat (substring pattern 0 (match-beginning 0))
2895 "\\"
2896 (substring pattern (match-beginning 0)))
2897 beg (1+ (match-end 0))))
2898 (call-process shell-file-name nil t nil
2899 "-c" (concat "\\" ;; Disregard shell aliases!
2900 insert-directory-program
2901 " -d "
2902 (if (stringp switches)
2903 switches
2904 (mapconcat 'identity switches " "))
a8bf610e 2905 " -- "
b7fa904c
RS
2906 pattern)))
2907 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2908 ;; directory if FILE is a symbolic link.
2909 (apply 'call-process
2910 insert-directory-program nil t nil
2911 (let (list)
2912 (if (listp switches)
2913 (setq list switches)
2914 (if (not (equal switches ""))
2915 (progn
2916 ;; Split the switches at any spaces
2917 ;; so we can pass separate options as separate args.
2918 (while (string-match " " switches)
2919 (setq list (cons (substring switches 0 (match-beginning 0))
2920 list)
2921 switches (substring switches (match-end 0))))
2922 (setq list (nreverse (cons switches list))))))
2923 (append list
a8bf610e
RS
2924 ;; Avoid lossage if FILE starts with `-'.
2925 '("--")
b7fa904c
RS
2926 (list
2927 (if full-directory-p
2928 (concat (file-name-as-directory file) ".")
2929 file)))))))
2930 ;; We get here if ls failed.
2931 ;; Access the file to get a suitable error.
2932 (access-file file "Reading directory"))))))
b4da00e9 2933
88902b35 2934(defvar kill-emacs-query-functions nil
65d5c6de 2935 "Functions to call with no arguments to query about killing Emacs.
78c793d1
RS
2936If any of these functions returns nil, killing Emacs is cancelled.
2937`save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
2938but `kill-emacs', the low level primitive, does not.
2939See also `kill-emacs-hook'.")
88902b35 2940
b4da00e9
RM
2941(defun save-buffers-kill-emacs (&optional arg)
2942 "Offer to save each buffer, then kill this Emacs process.
2943With prefix arg, silently save all file-visiting buffers, then kill."
2944 (interactive "P")
2945 (save-some-buffers arg t)
2946 (and (or (not (memq t (mapcar (function
2947 (lambda (buf) (and (buffer-file-name buf)
2948 (buffer-modified-p buf))))
2949 (buffer-list))))
2950 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2951 (or (not (fboundp 'process-list))
2952 ;; process-list is not defined on VMS.
2953 (let ((processes (process-list))
2954 active)
2955 (while processes
528415e7 2956 (and (memq (process-status (car processes)) '(run stop open))
b4da00e9
RM
2957 (let ((val (process-kill-without-query (car processes))))
2958 (process-kill-without-query (car processes) val)
2959 val)
2960 (setq active t))
2961 (setq processes (cdr processes)))
2962 (or (not active)
2963 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
88902b35 2964 ;; Query the user for other things, perhaps.
fb15c113 2965 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
b4da00e9
RM
2966 (kill-emacs)))
2967\f
47afc068
RS
2968;; We use /: as a prefix to "quote" a file name
2969;; so that magic file name handlers will not apply to it.
2970
2971(setq file-name-handler-alist
2972 (cons '("\\`/:" . file-name-non-special)
2973 file-name-handler-alist))
2974
2975;; We depend on being the last handler on the list,
2976;; so that anything else which does need handling
2977;; has been handled already.
2978;; So it is safe for us to inhibit *all* magic file name handlers.
2979
2980(defun file-name-non-special (operation &rest arguments)
2981 (let ((file-name-handler-alist nil)
2982 ;; Get a list of the indices of the args which are file names.
2983 (file-arg-indices
2984 (cdr (or (assq operation
2985 ;; The first four are special because they
2986 ;; return a file name. We want to include the /:
2987 ;; in the return value.
2988 ;; So just avoid stripping it in the first place.
2989 '((expand-file-name . nil)
2990 (file-name-directory . nil)
2991 (file-name-as-directory . nil)
2992 (directory-file-name . nil)
2993 (rename-file 0 1)
2994 (copy-file 0 1)
2995 (make-symbolic-link 0 1)
2996 (add-name-to-file 0 1)))
2997 ;; For all other operations, treat the first argument only
2998 ;; as the file name.
2999 '(nil 0))))
3000 ;; Copy ARGUMENTS so we can replace elements in it.
3001 (arguments (copy-sequence arguments)))
3002 ;; Strip off the /: from the file names that have this handler.
3003 (save-match-data
3004 (while file-arg-indices
3005 (and (nth (car file-arg-indices) arguments)
3006 (string-match "\\`/:" (nth (car file-arg-indices) arguments))
3007 (setcar (nthcdr (car file-arg-indices) arguments)
3008 (substring (nth (car file-arg-indices) arguments) 2)))
3009 (setq file-arg-indices (cdr file-arg-indices))))
3010 (apply operation arguments)))
3011\f
b4da00e9
RM
3012(define-key ctl-x-map "\C-f" 'find-file)
3013(define-key ctl-x-map "\C-q" 'toggle-read-only)
3014(define-key ctl-x-map "\C-r" 'find-file-read-only)
3015(define-key ctl-x-map "\C-v" 'find-alternate-file)
3016(define-key ctl-x-map "\C-s" 'save-buffer)
3017(define-key ctl-x-map "s" 'save-some-buffers)
3018(define-key ctl-x-map "\C-w" 'write-file)
3019(define-key ctl-x-map "i" 'insert-file)
3020(define-key esc-map "~" 'not-modified)
3021(define-key ctl-x-map "\C-d" 'list-directory)
3022(define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
3023
3024(define-key ctl-x-4-map "f" 'find-file-other-window)
3025(define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
3026(define-key ctl-x-4-map "\C-f" 'find-file-other-window)
3027(define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
924f0a24 3028(define-key ctl-x-4-map "\C-o" 'display-buffer)
5bbbceb1 3029
f98955ea
JB
3030(define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
3031(define-key ctl-x-5-map "f" 'find-file-other-frame)
3032(define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
3033(define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
c0274f38
ER
3034
3035;;; files.el ends here