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