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