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