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