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