Added and fixed documentation.
[bpt/emacs.git] / lisp / files.el
CommitLineData
c0274f38
ER
1;;; files.el --- file input and output commands for Emacs
2
a292c99f 3;; Copyright (C) 1985, 1986, 1987, 1992, 1993 Free Software Foundation, Inc.
b4da00e9 4
3a801d0c
ER
5;; Maintainer: FSF
6
b4da00e9
RM
7;; This file is part of GNU Emacs.
8
9;; GNU Emacs is free software; you can redistribute it and/or modify
10;; it under the terms of the GNU General Public License as published by
e5167999 11;; the Free Software Foundation; either version 2, or (at your option)
b4da00e9
RM
12;; any later version.
13
14;; GNU Emacs is distributed in the hope that it will be useful,
15;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17;; GNU General Public License for more details.
18
19;; You should have received a copy of the GNU General Public License
20;; along with GNU Emacs; see the file COPYING. If not, write to
21;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22
e41b2db1
ER
23;;; Commentary:
24
25;; Defines most of Emacs's file- and directory-handling functions,
26;; including basic file visiting, backup generation, link handling,
27;; ITS-id version control, load- and write-hook handling, and the like.
28
e5167999
ER
29;;; Code:
30
b4da00e9
RM
31(defconst delete-auto-save-files t
32 "*Non-nil means delete a buffer's auto-save file when the buffer is saved.")
33
34(defconst directory-abbrev-alist
35 nil
36 "*Alist of abbreviations for file directories.
37A list of elements of the form (FROM . TO), each meaning to replace
38FROM with TO when it appears in a directory name. This replacement is
39done when setting up the default directory of a newly visited file.
40*Every* FROM string should start with `^'.
41
42Use this feature when you have directories which you normally refer to
43via absolute symbolic links. Make TO the name of the link, and FROM
44the name it is linked to.")
45
46;;; Turn off backup files on VMS since it has version numbers.
47(defconst make-backup-files (not (eq system-type 'vax-vms))
48 "*Create a backup of each file when it is saved for the first time.
49This can be done by renaming the file or by copying.
50
51Renaming means that Emacs renames the existing file so that it is a
52backup file, then writes the buffer into a new file. Any other names
53that the old file had will now refer to the backup file. The new file
54is owned by you and its group is defaulted.
55
56Copying means that Emacs copies the existing file into the backup
57file, then writes the buffer on top of the existing file. Any other
58names that the old file had will now refer to the new (edited) file.
59The file's owner and group are unchanged.
60
61The choice of renaming or copying is controlled by the variables
62`backup-by-copying', `backup-by-copying-when-linked' and
63`backup-by-copying-when-mismatch'.")
64
65;; Do this so that local variables based on the file name
66;; are not overridden by the major mode.
67(defvar backup-inhibited nil
68 "Non-nil means don't make a backup file for this buffer.")
69(put 'backup-inhibited 'permanent-local t)
70
71(defconst backup-by-copying nil
72 "*Non-nil means always use copying to create backup files.
73See documentation of variable `make-backup-files'.")
74
75(defconst backup-by-copying-when-linked nil
76 "*Non-nil means use copying to create backups for files with multiple names.
77This causes the alternate names to refer to the latest version as edited.
78This variable is relevant only if `backup-by-copying' is nil.")
79
80(defconst backup-by-copying-when-mismatch nil
81 "*Non-nil means create backups by copying if this preserves owner or group.
82Renaming may still be used (subject to control of other variables)
83when it would not result in changing the owner or group of the file;
84that is, for files which are owned by you and whose group matches
85the default for a new file created there by you.
86This variable is relevant only if `backup-by-copying' is nil.")
87
88(defvar backup-enable-predicate
89 '(lambda (name)
90 (or (< (length name) 5)
91 (not (string-equal "/tmp/" (substring name 0 5)))))
92 "Predicate that looks at a file name and decides whether to make backups.
93Called with an absolute file name as argument, it returns t to enable backup.")
94
95(defconst buffer-offer-save nil
96 "*Non-nil in a buffer means offer to save the buffer on exit
97even if the buffer is not visiting a file.
98Automatically local in all buffers.")
99(make-variable-buffer-local 'buffer-offer-save)
100
f3e23606
RS
101(defconst find-file-existing-other-name nil
102 "*Non-nil means find a file under alternative names, in existing buffers.
103This means if any existing buffer is visiting the file you want
104under another name, you get the existing buffer instead of a new buffer.")
105
106(defconst find-file-visit-truename nil
107 "*Non-nil means visit a file under its truename.
108The truename of a file is found by chasing all links
109both at the file level and at the levels of the containing directories.")
110
111(defvar buffer-file-truename nil
112 "The truename of the file visited in the current buffer.
113This variable is automatically local in all buffers, when non-nil.")
114(make-variable-buffer-local 'buffer-file-truename)
115(put 'buffer-file-truename 'permanent-local t)
116
117(defvar buffer-file-number nil
118 "The device number and file number of the file visited in the current buffer.
119The value is a list of the form (FILENUM DEVNUM).
120This pair of numbers uniquely identifies the file.
121If the buffer is visiting a new file, the value is nil.")
122(make-variable-buffer-local 'buffer-file-number)
123(put 'buffer-file-number 'permanent-local t)
124
b4da00e9
RM
125(defconst file-precious-flag nil
126 "*Non-nil means protect against I/O errors while saving files.
127Some modes set this non-nil in particular buffers.")
128
129(defvar version-control nil
130 "*Control use of version numbers for backup files.
131t means make numeric backup versions unconditionally.
132nil means make them for files that have some already.
133never means do not make them.")
134
135(defvar dired-kept-versions 2
136 "*When cleaning directory, number of versions to keep.")
137
138(defvar trim-versions-without-asking nil
6d74b528
ER
139 "*If t, deletes excess backup versions silently.
140If nil, asks confirmation. Any other value prevents any trimming.")
b4da00e9
RM
141
142(defvar kept-old-versions 2
143 "*Number of oldest versions to keep when a new numbered backup is made.")
144
145(defvar kept-new-versions 2
146 "*Number of newest versions to keep when a new numbered backup is made.
147Includes the new backup. Must be > 0")
148
149(defconst require-final-newline nil
150 "*Value of t says silently ensure a file ends in a newline when it is saved.
151Non-nil but not t says ask user whether to add a newline when there isn't one.
152nil means don't add newlines.")
153
154(defconst auto-save-default t
155 "*Non-nil says by default do auto-saving of every file-visiting buffer.")
156
157(defconst auto-save-visited-file-name nil
158 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
159Normally auto-save files are written under other names.")
160
161(defconst save-abbrevs nil
162 "*Non-nil means save word abbrevs too when files are saved.
163Loading an abbrev file sets this to t.")
164
165(defconst find-file-run-dired t
166 "*Non-nil says run dired if find-file is given the name of a directory.")
167
92966e6f
RS
168;;;It is not useful to make this a local variable.
169;;;(put 'find-file-not-found-hooks 'permanent-local t)
b4da00e9
RM
170(defvar find-file-not-found-hooks nil
171 "List of functions to be called for `find-file' on nonexistent file.
172These functions are called as soon as the error is detected.
173`buffer-file-name' is already set up.
174The functions are called in the order given until one of them returns non-nil.")
175
92966e6f
RS
176;;;It is not useful to make this a local variable.
177;;;(put 'find-file-hooks 'permanent-local t)
b4da00e9
RM
178(defvar find-file-hooks nil
179 "List of functions to be called after a buffer is loaded from a file.
180The buffer's local variables (if any) will have been processed before the
181functions are called.")
182
c9dca4e0 183;;; In case someone does make it local.
b4da00e9
RM
184(put 'write-file-hooks 'permanent-local t)
185(defvar write-file-hooks nil
186 "List of functions to be called before writing out a buffer to a file.
187If one of them returns non-nil, the file is considered already written
8c0e7b73
JB
188and the rest are not called.
189These hooks are considered to pertain to the visited file.
190So this list is cleared if you change the visited file name.
c9dca4e0
RS
191See also `write-contents-hooks'.
192Don't make this variable buffer-local; instead, use `local-write-file-hooks'.")
193
194(put 'local-write-file-hooks 'permanent-local t)
195(defvar local-write-file-hooks nil
196 "Just like `write-file-hooks', except intended for per-buffer use.
197The functions in this list are called before the ones in
198`write-file-hooks'.")
8c0e7b73
JB
199
200(defvar write-contents-hooks nil
201 "List of functions to be called before writing out a buffer to a file.
202If one of them returns non-nil, the file is considered already written
203and the rest are not called.
204These hooks are considered to pertain to the buffer's contents,
205not to the particular visited file; thus, `set-visited-file-name' does
206not clear this variable, but changing the major mode does clear it.
207See also `write-file-hooks'.")
b4da00e9
RM
208
209(defconst enable-local-variables t
210 "*Control use of local-variables lists in files you visit.
211The value can be t, nil or something else.
212A value of t means local-variables lists are obeyed;
213nil means they are ignored; anything else means query.
214
215The command \\[normal-mode] always obeys local-variables lists
216and ignores this variable.")
217
2bba782c 218(defconst enable-local-eval 'maybe
d207b766
RS
219 "*Control processing of the \"variable\" `eval' in a file's local variables.
220The value can be t, nil or something else.
221A value of t means obey `eval' variables;
222nil means ignore them; anything else means query.
223
224The command \\[normal-mode] always obeys local-variables lists
225and ignores this variable.")
b4da00e9
RM
226
227;; Avoid losing in versions where CLASH_DETECTION is disabled.
228(or (fboundp 'lock-buffer)
229 (fset 'lock-buffer 'ignore))
230(or (fboundp 'unlock-buffer)
231 (fset 'unlock-buffer 'ignore))
232\f
233(defun pwd ()
234 "Show the current default directory."
235 (interactive nil)
236 (message "Directory %s" default-directory))
237
238(defun cd (dir)
239 "Make DIR become the current buffer's default directory."
240 (interactive "DChange default directory: ")
241 (setq dir (expand-file-name dir))
242 (if (not (eq system-type 'vax-vms))
243 (setq dir (file-name-as-directory dir)))
244 (if (not (file-directory-p dir))
245 (error "%s is not a directory" dir)
246 (if (file-executable-p dir)
247 (setq default-directory dir)
248 (error "Cannot cd to %s: Permission denied" dir)))
5bbbceb1
JB
249 ;; We used to call pwd at this point. That's not terribly helpful
250 ;; when we're invoking cd interactively, and the new cmushell-based
251 ;; shell has its own (better) facilities for this.
252)
b4da00e9
RM
253
254(defun load-file (file)
255 "Load the Lisp file named FILE."
256 (interactive "fLoad file: ")
257 (load (expand-file-name file) nil nil t))
258
259(defun load-library (library)
260 "Load the library named LIBRARY.
261This is an interface to the function `load'."
262 (interactive "sLoad library: ")
263 (load library))
5d68c2c2
RS
264
265;; OTHER is the other file to be compared.
266(defun file-local-copy (file)
267 "Copy the file FILE into a temporary file on this machine.
268Returns the name of the local copy, or nil, if FILE is directly
269accessible."
5dbfdacd 270 (let ((handler (find-file-name-handler file)))
5d68c2c2
RS
271 (if handler
272 (funcall handler 'file-local-copy file)
273 nil)))
f3e23606
RS
274
275(defun file-truename (filename)
276 "Return the truename of FILENAME, which should be absolute.
277The truename of a file name is found by chasing symbolic links
278both at the level of the file and at the level of the directories
279containing it, until no links are left at any level."
6d1df4b2
JB
280 (if (string= filename "~")
281 (setq filename (expand-file-name filename)))
5dbfdacd 282 (let ((handler (find-file-name-handler filename)))
6f176f94
RS
283 ;; For file name that has a special handler, call handler.
284 ;; This is so that ange-ftp can save time by doing a no-op.
285 (if handler
286 (funcall handler 'file-truename filename)
287 (let ((dir (file-name-directory filename))
288 target dirfile)
289 ;; Get the truename of the directory.
290 (setq dirfile (directory-file-name dir))
291 ;; If these are equal, we have the (or a) root directory.
292 (or (string= dir dirfile)
293 (setq dir (file-name-as-directory (file-truename dirfile))))
294 ;; Put it back on the file name.
295 (setq filename (concat dir (file-name-nondirectory filename)))
296 ;; Is the file name the name of a link?
297 (setq target (file-symlink-p filename))
298 (if target
299 ;; Yes => chase that link, then start all over
300 ;; since the link may point to a directory name that uses links.
301 (file-truename (expand-file-name target dir))
302 ;; No, we are done!
303 filename)))))
5dbfdacd 304
b4da00e9
RM
305\f
306(defun switch-to-buffer-other-window (buffer)
307 "Select buffer BUFFER in another window."
308 (interactive "BSwitch to buffer in other window: ")
309 (let ((pop-up-windows t))
310 (pop-to-buffer buffer t)))
311
f98955ea
JB
312(defun switch-to-buffer-other-frame (buffer)
313 "Switch to buffer BUFFER in another frame."
314 (interactive "BSwitch to buffer in other frame: ")
315 (let ((pop-up-frames t))
2be5e5db 316 (pop-to-buffer buffer t)))
5bbbceb1 317
b4da00e9
RM
318(defun find-file (filename)
319 "Edit file FILENAME.
320Switch to a buffer visiting file FILENAME,
321creating one if none already exists."
322 (interactive "FFind file: ")
323 (switch-to-buffer (find-file-noselect filename)))
324
325(defun find-file-other-window (filename)
326 "Edit file FILENAME, in another window.
327May create a new window, or reuse an existing one.
328See the function `display-buffer'."
329 (interactive "FFind file in other window: ")
330 (switch-to-buffer-other-window (find-file-noselect filename)))
331
f98955ea
JB
332(defun find-file-other-frame (filename)
333 "Edit file FILENAME, in another frame.
334May create a new frame, or reuse an existing one.
5bbbceb1 335See the function `display-buffer'."
f98955ea
JB
336 (interactive "FFind file in other frame: ")
337 (switch-to-buffer-other-frame (find-file-noselect filename)))
5bbbceb1 338
b4da00e9
RM
339(defun find-file-read-only (filename)
340 "Edit file FILENAME but don't allow changes.
341Like \\[find-file] but marks buffer as read-only.
342Use \\[toggle-read-only] to permit editing."
343 (interactive "fFind file read-only: ")
344 (find-file filename)
345 (setq buffer-read-only t))
346
347(defun find-file-read-only-other-window (filename)
348 "Edit file FILENAME in another window but don't allow changes.
349Like \\[find-file-other-window] but marks buffer as read-only.
350Use \\[toggle-read-only] to permit editing."
351 (interactive "fFind file read-only other window: ")
352 (find-file filename)
353 (setq buffer-read-only t))
354
f98955ea
JB
355(defun find-file-read-only-other-frame (filename)
356 "Edit file FILENAME in another frame but don't allow changes.
357Like \\[find-file-other-frame] but marks buffer as read-only.
5bbbceb1 358Use \\[toggle-read-only] to permit editing."
f98955ea
JB
359 (interactive "fFind file read-only other frame: ")
360 (find-file-other-frame filename)
5bbbceb1
JB
361 (setq buffer-read-only t))
362
b4da00e9
RM
363(defun find-alternate-file (filename)
364 "Find file FILENAME, select its buffer, kill previous buffer.
365If the current buffer now contains an empty file that you just visited
366\(presumably by mistake), use this command to visit the file you really want."
367 (interactive
368 (let ((file buffer-file-name)
369 (file-name nil)
370 (file-dir nil))
371 (and file
372 (setq file-name (file-name-nondirectory file)
373 file-dir (file-name-directory file)))
a61f59b4
JA
374 (list (read-file-name
375 "Find alternate file: " file-dir nil nil file-name))))
b4da00e9
RM
376 (and (buffer-modified-p)
377 ;; (not buffer-read-only)
378 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
379 (buffer-name))))
380 (error "Aborted"))
381 (let ((obuf (current-buffer))
382 (ofile buffer-file-name)
383 (oname (buffer-name)))
384 (rename-buffer " **lose**")
385 (setq buffer-file-name nil)
386 (unwind-protect
387 (progn
388 (unlock-buffer)
389 (find-file filename))
390 (cond ((eq obuf (current-buffer))
391 (setq buffer-file-name ofile)
392 (lock-buffer)
393 (rename-buffer oname))))
394 (or (eq (current-buffer) obuf)
395 (kill-buffer obuf))))
396
397(defun create-file-buffer (filename)
398 "Create a suitably named buffer for visiting FILENAME, and return it.
399FILENAME (sans directory) is used unchanged if that name is free;
400otherwise a string <2> or <3> or ... is appended to get an unused name."
401 (let ((lastname (file-name-nondirectory filename)))
402 (if (string= lastname "")
403 (setq lastname filename))
404 (generate-new-buffer lastname)))
405
5bbbceb1
JB
406(defun generate-new-buffer (name)
407 "Create and return a buffer with a name based on NAME.
29165787 408Choose the buffer's name using `generate-new-buffer-name'."
5bbbceb1
JB
409 (get-buffer-create (generate-new-buffer-name name)))
410
e373f201
JB
411(defconst automount-dir-prefix "^/tmp_mnt/"
412 "Regexp to match the automounter prefix in a directory name.")
413
ffb3a4db
RS
414(defvar abbreviated-home-dir nil
415 "The the user's homedir abbreviated according to `directory-abbrev-list'.")
416
5bbbceb1 417(defun abbreviate-file-name (filename)
29165787 418 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
5bbbceb1 419This also substitutes \"~\" for the user's home directory.
29165787 420Type \\[describe-variable] directory-abbrev-alist RET for more information."
e373f201
JB
421 ;; Get rid of the prefixes added by the automounter.
422 (if (and (string-match automount-dir-prefix filename)
423 (file-exists-p (file-name-directory
424 (substring filename (1- (match-end 0))))))
425 (setq filename (substring filename (1- (match-end 0)))))
5bbbceb1 426 (let ((tail directory-abbrev-alist))
ffb3a4db
RS
427 ;; If any elt of directory-abbrev-alist matches this name,
428 ;; abbreviate accordingly.
5bbbceb1
JB
429 (while tail
430 (if (string-match (car (car tail)) filename)
431 (setq filename
432 (concat (cdr (car tail)) (substring filename (match-end 0)))))
433 (setq tail (cdr tail)))
ffb3a4db
RS
434 ;; Compute and save the abbreviated homedir name.
435 ;; We defer computing this until the first time it's needed, to
436 ;; give time for directory-abbrev-alist to be set properly.
437 (or abbreviated-home-dir
438 (setq abbreviated-home-dir
439 (let ((abbreviated-home-dir "$foo"))
440 (concat "^" (abbreviate-file-name (expand-file-name "~"))))))
441 ;; If FILENAME starts with the abbreviated homedir,
442 ;; make it start with `~' instead.
443 (if (string-match abbreviated-home-dir filename)
5bbbceb1
JB
444 (setq filename
445 (concat "~" (substring filename (match-end 0)))))
446 filename))
447
b4da00e9
RM
448(defun find-file-noselect (filename &optional nowarn)
449 "Read file FILENAME into a buffer and return the buffer.
450If a buffer exists visiting FILENAME, return that one, but
451verify that the file has not changed since visited or saved.
452The buffer is not selected, just returned to the caller."
e373f201
JB
453 (setq filename
454 (abbreviate-file-name
455 (expand-file-name filename)))
b4da00e9
RM
456 (if (file-directory-p filename)
457 (if find-file-run-dired
458 (dired-noselect filename)
459 (error "%s is a directory." filename))
f3e23606
RS
460 (let* ((buf (get-file-buffer filename))
461 (truename (abbreviate-file-name (file-truename filename)))
462 (number (nthcdr 10 (file-attributes truename)))
463 ;; Find any buffer for a file which has same truename.
464 (same-truename
465 (or buf ; Shortcut
466 (let (found
467 (list (buffer-list)))
468 (while (and (not found) list)
469 (save-excursion
470 (set-buffer (car list))
4269ed64
RM
471 (if (and buffer-file-name
472 (string= buffer-file-truename truename))
f3e23606
RS
473 (setq found (car list))))
474 (setq list (cdr list)))
475 found)))
476 (same-number
477 (or buf ; Shortcut
478 (and number
479 (let (found
480 (list (buffer-list)))
481 (while (and (not found) list)
482 (save-excursion
483 (set-buffer (car list))
4e7afa86
RS
484 (if (and (equal buffer-file-number number)
485 ;; Verify this buffer's file number
486 ;; still belongs to its file.
487 (file-exists-p buffer-file-name)
488 (equal (nthcdr 10 (file-attributes buffer-file-name)) number))
f3e23606
RS
489 (setq found (car list))))
490 (setq list (cdr list)))
491 found))))
492 error)
493 ;; Let user know if there is a buffer with the same truename.
494 (if (and (not buf) same-truename (not nowarn))
495 (message "%s and %s are the same file (%s)"
496 filename (buffer-file-name same-truename)
497 truename)
498 (if (and (not buf) same-number (not nowarn))
499 (message "%s and %s are the same file"
500 filename (buffer-file-name same-number))))
501
502 ;; Optionally also find that buffer.
503 (if (or find-file-existing-other-name find-file-visit-truename)
504 (setq buf (or same-truename same-number)))
b4da00e9
RM
505 (if buf
506 (or nowarn
507 (verify-visited-file-modtime buf)
508 (cond ((not (file-exists-p filename))
509 (error "File %s no longer exists!" filename))
510 ((yes-or-no-p
511 (format
512 (if (buffer-modified-p buf)
513 "File %s changed on disk. Discard your edits? "
514 "File %s changed on disk. Read the new version? ")
515 (file-name-nondirectory filename)))
516 (save-excursion
517 (set-buffer buf)
518 (revert-buffer t t)))))
519 (save-excursion
f3e23606
RS
520;;; The truename stuff makes this obsolete.
521;;; (let* ((link-name (car (file-attributes filename)))
522;;; (linked-buf (and (stringp link-name)
523;;; (get-file-buffer link-name))))
524;;; (if (bufferp linked-buf)
525;;; (message "Symbolic link to file in buffer %s"
526;;; (buffer-name linked-buf))))
b4da00e9
RM
527 (setq buf (create-file-buffer filename))
528 (set-buffer buf)
529 (erase-buffer)
530 (condition-case ()
531 (insert-file-contents filename t)
532 (file-error
533 (setq error t)
534 ;; Run find-file-not-found-hooks until one returns non-nil.
535 (let ((hooks find-file-not-found-hooks))
536 (while (and hooks
537 (not (funcall (car hooks))))
538 (setq hooks (cdr hooks))))))
f3e23606
RS
539 ;; Find the file's truename, and maybe use that as visited name.
540 (setq buffer-file-truename (abbreviate-file-name truename))
541 (setq buffer-file-number number)
542 (if find-file-visit-truename (setq filename buffer-file-truename))
b4da00e9
RM
543 ;; Set buffer's default directory to that of the file.
544 (setq default-directory (file-name-directory filename))
545 ;; Turn off backup files for certain file names. Since
546 ;; this is a permanent local, the major mode won't eliminate it.
547 (and (not (funcall backup-enable-predicate buffer-file-name))
548 (progn
549 (make-local-variable 'backup-inhibited)
550 (setq backup-inhibited t)))
551 (after-find-file error (not nowarn))))
552 buf)))
553\f
8cfb9d46 554(defun after-find-file (&optional error warn noauto)
b4da00e9
RM
555 "Called after finding a file and by the default revert function.
556Sets buffer mode, parses local variables.
8cfb9d46 557Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
b4da00e9
RM
558error in reading the file. WARN non-nil means warn if there
559exists an auto-save file more recent than the visited file.
8cfb9d46 560NOAUTO means don't mess with auto-save mode.
b4da00e9
RM
561Finishes by calling the functions in `find-file-hooks'."
562 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
563 (if noninteractive
564 nil
565 (let* (not-serious
566 (msg
567 (cond ((and error (file-attributes buffer-file-name))
568 (setq buffer-read-only t)
569 "File exists, but is read-protected.")
570 ((not buffer-read-only)
571 (if (and warn
572 (file-newer-than-file-p (make-auto-save-file-name)
573 buffer-file-name))
574 "Auto save file is newer; consider M-x recover-file"
575 (setq not-serious t)
576 (if error "(New file)" nil)))
577 ((not error)
578 (setq not-serious t)
579 "Note: file is write protected")
580 ((file-attributes (directory-file-name default-directory))
581 "File not found and directory write-protected")
4e43240a
RS
582 ((file-exists-p (file-name-directory buffer-file-name))
583 (setq buffer-read-only nil))
b4da00e9 584 (t
5bbbceb1 585 (setq buffer-read-only nil)
4e43240a
RS
586 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
587 "Use M-x make-dir RET RET to create the directory"
588 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
b4da00e9
RM
589 (if msg
590 (progn
591 (message msg)
592 (or not-serious (sit-for 1 nil t)))))
8cfb9d46 593 (if (and auto-save-default (not noauto))
b4da00e9
RM
594 (auto-save-mode t)))
595 (normal-mode t)
596 (mapcar 'funcall find-file-hooks))
597
598(defun normal-mode (&optional find-file)
599 "Choose the major mode for this buffer automatically.
600Also sets up any specified local variables of the file.
601Uses the visited file name, the -*- line, and the local variables spec.
602
603This function is called automatically from `find-file'. In that case,
604we may set up specified local variables depending on the value of
605`enable-local-variables': if it is t, we do; if it is nil, we don't;
606otherwise, we query. `enable-local-variables' is ignored if you
607run `normal-mode' explicitly."
608 (interactive)
609 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
610 (condition-case err
611 (set-auto-mode)
612 (error (message "File mode specification error: %s"
613 (prin1-to-string err))))
614 (condition-case err
7b3f3dc2
JB
615 (let ((enable-local-variables (or (not find-file)
616 enable-local-variables)))
617 (hack-local-variables))
b4da00e9
RM
618 (error (message "File local-variables error: %s"
619 (prin1-to-string err)))))
620
7b3f3dc2
JB
621(defvar auto-mode-alist (mapcar 'purecopy
622 '(("\\.text\\'" . text-mode)
623 ("\\.c\\'" . c-mode)
624 ("\\.h\\'" . c-mode)
625 ("\\.tex\\'" . TeX-mode)
626 ("\\.ltx\\'" . LaTeX-mode)
627 ("\\.el\\'" . emacs-lisp-mode)
628 ("\\.mm\\'" . nroff-mode)
629 ("\\.me\\'" . nroff-mode)
c80d2575
ER
630 ("\\.ms\\'" . nroff-mode)
631 ("\\.man\\'" . nroff-mode)
7b3f3dc2
JB
632 ("\\.scm\\'" . scheme-mode)
633 ("\\.l\\'" . lisp-mode)
634 ("\\.lisp\\'" . lisp-mode)
635 ("\\.f\\'" . fortran-mode)
636 ("\\.for\\'" . fortran-mode)
637 ("\\.mss\\'" . scribe-mode)
638 ("\\.pl\\'" . prolog-mode)
639 ("\\.cc\\'" . c++-mode)
640 ("\\.C\\'" . c++-mode)
d87f0d7f 641 ("\\.mk\\'" . makefile-mode)
c80d2575 642 ("[Mm]akefile" . makefile-mode)
7b3f3dc2
JB
643;;; Less common extensions come here
644;;; so more common ones above are found faster.
645 ("\\.s\\'" . asm-mode)
646 ("ChangeLog\\'" . change-log-mode)
7adc58e5 647 ("ChangeLog.[0-9]+\\'" . change-log-mode)
7b3f3dc2 648 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
7adc58e5
RS
649;; The following should come after the ChangeLog pattern
650;; for the sake of ChangeLog.1, etc.
651 ("\\.[12345678]\\'" . nroff-mode)
7b3f3dc2
JB
652 ("\\.TeX\\'" . TeX-mode)
653 ("\\.sty\\'" . LaTeX-mode)
654 ("\\.bbl\\'" . LaTeX-mode)
655 ("\\.bib\\'" . bibtex-mode)
656 ("\\.article\\'" . text-mode)
657 ("\\.letter\\'" . text-mode)
658 ("\\.texinfo\\'" . texinfo-mode)
fd5285f3 659 ("\\.texi\\'" . texinfo-mode)
7b3f3dc2
JB
660 ("\\.lsp\\'" . lisp-mode)
661 ("\\.awk\\'" . awk-mode)
662 ("\\.prolog\\'" . prolog-mode)
c80d2575 663 ("\\.tar\\'" . tar-mode)
7b3f3dc2
JB
664 ;; Mailer puts message to be edited in
665 ;; /tmp/Re.... or Message
666 ("^/tmp/Re" . text-mode)
667 ("/Message[0-9]*\\'" . text-mode)
668 ;; some news reader is reported to use this
669 ("^/tmp/fol/" . text-mode)
670 ("\\.y\\'" . c-mode)
c80d2575 671 ("\\.lex\\'" . c-mode)
7b3f3dc2
JB
672 ("\\.oak\\'" . scheme-mode)
673 ("\\.scm.[0-9]*\\'" . scheme-mode)
674 ;; .emacs following a directory delimiter
675 ;; in either Unix or VMS syntax.
676 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
677 ("\\.ml\\'" . lisp-mode)))
678 "\
679Alist of filename patterns vs corresponding major mode functions.
680Each element looks like (REGEXP . FUNCTION).
681Visiting a file whose name matches REGEXP causes FUNCTION to be called.")
682
b4da00e9
RM
683(defun set-auto-mode ()
684 "Select major mode appropriate for current buffer.
7b3f3dc2
JB
685This checks for a -*- mode tag in the buffer's text, or
686compares the filename against the entries in auto-mode-alist. It does
687not check for the \"mode:\" local variable in the Local Variables
688section of the file; for that, use `hack-local-variables'.
689
f3e23606 690If `enable-local-variables' is nil, this function does not check for a
7b3f3dc2 691-*- mode tag."
b4da00e9
RM
692 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
693 (let (beg end mode)
694 (save-excursion
695 (goto-char (point-min))
696 (skip-chars-forward " \t\n")
7b3f3dc2 697 (if (and enable-local-variables
a292c99f
RM
698 (search-forward "-*-" (save-excursion
699 ;; If the file begins with "#!"
700 ;; (exec interpreter magic), look
701 ;; for mode frobs in the first two
702 ;; lines. You cannot necessarily
703 ;; put them in the first line of
704 ;; such a file without screwing up
705 ;; the interpreter invocation.
706 (end-of-line (and (looking-at "^#!") 2))
707 (point)) t)
b4da00e9
RM
708 (progn
709 (skip-chars-forward " \t")
710 (setq beg (point))
7b3f3dc2
JB
711 (search-forward "-*-"
712 (save-excursion (end-of-line) (point))
713 t))
b4da00e9
RM
714 (progn
715 (forward-char -3)
716 (skip-chars-backward " \t")
717 (setq end (point))
718 (goto-char beg)
719 (if (search-forward ":" end t)
720 (progn
721 (goto-char beg)
722 (if (let ((case-fold-search t))
723 (search-forward "mode:" end t))
724 (progn
725 (skip-chars-forward " \t")
726 (setq beg (point))
727 (if (search-forward ";" end t)
728 (forward-char -1)
729 (goto-char end))
730 (skip-chars-backward " \t")
731 (setq mode (buffer-substring beg (point))))))
732 (setq mode (buffer-substring beg end)))))
733 (setq mode (intern (concat (downcase mode) "-mode")))
734 (let ((alist auto-mode-alist)
735 (name buffer-file-name))
736 (let ((case-fold-search (eq system-type 'vax-vms)))
737 ;; Remove backup-suffixes from file name.
738 (setq name (file-name-sans-versions name))
739 ;; Find first matching alist entry.
740 (while (and (not mode) alist)
741 (if (string-match (car (car alist)) name)
742 (setq mode (cdr (car alist))))
743 (setq alist (cdr alist)))))))
744 (if mode (funcall mode))))
745
f3e23606
RS
746(defun hack-local-variables-prop-line ()
747 ;; Set local variables specified in the -*- line.
748 ;; Returns t if mode was set.
749 (save-excursion
750 (goto-char (point-min))
751 (skip-chars-forward " \t\n\r")
752 (let ((result '())
753 (end (save-excursion (end-of-line) (point)))
754 mode-p)
755 ;; Parse the -*- line into the `result' alist.
756 (cond ((not (search-forward "-*-" end t))
757 ;; doesn't have one.
758 nil)
759 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
760 ;; Simple form: "-*- MODENAME -*-".
761 (setq result
762 (list (cons 'mode
763 (intern (buffer-substring
764 (match-beginning 1)
765 (match-end 1)))))))
766 (t
767 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
768 ;; (last ";" is optional).
769 (save-excursion
770 (if (search-forward "-*-" end t)
771 (setq end (- (point) 3))
772 (error "-*- not terminated before end of line")))
773 (while (< (point) end)
774 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
775 (error "malformed -*- line"))
776 (goto-char (match-end 0))
777 (let ((key (intern (downcase (buffer-substring
778 (match-beginning 1)
779 (match-end 1)))))
780 (val (save-restriction
781 (narrow-to-region (point) end)
782 (read (current-buffer)))))
783 (setq result (cons (cons key val) result))
784 (skip-chars-forward " \t;")))
785 (setq result (nreverse result))))
786
787 ;; Mode is magic.
788 (let (mode)
789 (while (setq mode (assq 'mode result))
790 (setq mode-p t result (delq mode result))
791 (funcall (intern (concat (downcase (symbol-name (cdr mode)))
792 "-mode")))))
793
794 (if (and result
795 (or (eq enable-local-variables t)
796 (and enable-local-variables
797 (save-window-excursion
798 (switch-to-buffer (current-buffer))
799 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
800 (file-name-nondirectory buffer-file-name)))))))
801 (while result
802 (let ((key (car (car result)))
803 (val (cdr (car result))))
804 ;; 'mode has already been removed from this list.
805 (hack-one-local-variable key val))
806 (setq result (cdr result))))
807 mode-p)))
808
7b3f3dc2 809(defun hack-local-variables ()
5792c834 810 "Parse and put into effect this buffer's local variables spec."
f3e23606 811 (hack-local-variables-prop-line)
b4da00e9
RM
812 ;; Look for "Local variables:" line in last page.
813 (save-excursion
814 (goto-char (point-max))
815 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
816 (if (let ((case-fold-search t))
817 (and (search-forward "Local Variables:" nil t)
7b3f3dc2 818 (or (eq enable-local-variables t)
b4da00e9
RM
819 (and enable-local-variables
820 (save-window-excursion
821 (switch-to-buffer (current-buffer))
822 (save-excursion
823 (beginning-of-line)
824 (set-window-start (selected-window) (point)))
825 (y-or-n-p (format "Set local variables as specified at end of %s? "
826 (file-name-nondirectory buffer-file-name))))))))
827 (let ((continue t)
2bba782c
RS
828 prefix prefixlen suffix beg
829 (enable-local-eval enable-local-eval))
b4da00e9
RM
830 ;; The prefix is what comes before "local variables:" in its line.
831 ;; The suffix is what comes after "local variables:" in its line.
832 (skip-chars-forward " \t")
833 (or (eolp)
834 (setq suffix (buffer-substring (point)
835 (progn (end-of-line) (point)))))
836 (goto-char (match-beginning 0))
837 (or (bolp)
838 (setq prefix
839 (buffer-substring (point)
840 (progn (beginning-of-line) (point)))))
7b3f3dc2 841
b4da00e9
RM
842 (if prefix (setq prefixlen (length prefix)
843 prefix (regexp-quote prefix)))
844 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
845 (while continue
846 ;; Look at next local variable spec.
847 (if selective-display (re-search-forward "[\n\C-m]")
848 (forward-line 1))
849 ;; Skip the prefix, if any.
850 (if prefix
851 (if (looking-at prefix)
852 (forward-char prefixlen)
853 (error "Local variables entry is missing the prefix")))
854 ;; Find the variable name; strip whitespace.
855 (skip-chars-forward " \t")
856 (setq beg (point))
857 (skip-chars-forward "^:\n")
858 (if (eolp) (error "Missing colon in local variables entry"))
859 (skip-chars-backward " \t")
860 (let* ((str (buffer-substring beg (point)))
861 (var (read str))
862 val)
863 ;; Setting variable named "end" means end of list.
864 (if (string-equal (downcase str) "end")
865 (setq continue nil)
866 ;; Otherwise read the variable value.
867 (skip-chars-forward "^:")
868 (forward-char 1)
869 (setq val (read (current-buffer)))
870 (skip-chars-backward "\n")
871 (skip-chars-forward " \t")
872 (or (if suffix (looking-at suffix) (eolp))
873 (error "Local variables entry is terminated incorrectly"))
874 ;; Set the variable. "Variables" mode and eval are funny.
f3e23606
RS
875 (hack-one-local-variable var val))))))))
876
877(defconst ignored-local-variables
878 '(enable-local-eval)
879 "Variables to be ignored in a file's local variable spec.")
880
881;; "Set" one variable in a local variables spec.
882;; A few variable names are treated specially.
883(defun hack-one-local-variable (var val)
884 (cond ((eq var 'mode)
885 (funcall (intern (concat (downcase (symbol-name val))
886 "-mode"))))
887 ((memq var ignored-local-variables)
888 nil)
889 ;; "Setting" eval means either eval it or do nothing.
890 ((eq var 'eval)
891 (if (and (not (string= (user-login-name) "root"))
892 (or (eq enable-local-eval t)
893 (and enable-local-eval
894 (save-window-excursion
895 (switch-to-buffer (current-buffer))
896 (save-excursion
897 (beginning-of-line)
898 (set-window-start (selected-window) (point)))
899 (setq enable-local-eval
900 (y-or-n-p (format "Process `eval' local variable in file %s? "
901 (file-name-nondirectory buffer-file-name))))))))
902 (save-excursion (eval val))
903 (message "Ignoring `eval:' in file's local variables")))
904 ;; Ordinary variable, really set it.
905 (t (make-local-variable var)
906 (set var val))))
907
b4da00e9
RM
908\f
909(defun set-visited-file-name (filename)
910 "Change name of file visited in current buffer to FILENAME.
911The next time the buffer is saved it will go in the newly specified file.
912nil or empty string as argument means make buffer not be visiting any file.
913Remember to delete the initial contents of the minibuffer
914if you wish to pass an empty string as the argument."
915 (interactive "FSet visited file name: ")
916 (if filename
917 (setq filename
918 (if (string-equal filename "")
919 nil
920 (expand-file-name filename))))
921 (or (equal filename buffer-file-name)
922 (null filename)
923 (progn
924 (lock-buffer filename)
925 (unlock-buffer)))
926 (setq buffer-file-name filename)
927 (if filename ; make buffer name reflect filename.
5bbbceb1 928 (let ((new-name (file-name-nondirectory buffer-file-name)))
b4da00e9
RM
929 (if (string= new-name "")
930 (error "Empty file name"))
931 (if (eq system-type 'vax-vms)
932 (setq new-name (downcase new-name)))
933 (setq default-directory (file-name-directory buffer-file-name))
5bbbceb1 934 (rename-buffer new-name t)))
b4da00e9
RM
935 (setq buffer-backed-up nil)
936 (clear-visited-file-modtime)
f3e23606
RS
937 (if filename
938 (progn
939 (setq buffer-file-truename
940 (abbreviate-file-name (file-truename buffer-file-name)))
941 (if find-file-visit-truename
942 (setq buffer-file-name buffer-file-truename))
943 (setq buffer-file-number (nth 10 (file-attributes buffer-file-name))))
944 (setq buffer-file-truename nil buffer-file-number nil))
b4da00e9
RM
945 ;; write-file-hooks is normally used for things like ftp-find-file
946 ;; that visit things that are not local files as if they were files.
947 ;; Changing to visit an ordinary local file instead should flush the hook.
948 (kill-local-variable 'write-file-hooks)
c9dca4e0 949 (kill-local-variable 'local-write-file-hooks)
b4da00e9
RM
950 (kill-local-variable 'revert-buffer-function)
951 (kill-local-variable 'backup-inhibited)
952 ;; Turn off backup files for certain file names.
953 ;; Since this is a permanent local, the major mode won't eliminate it.
954 (and (not (funcall backup-enable-predicate buffer-file-name))
955 (progn
956 (make-local-variable 'backup-inhibited)
957 (setq backup-inhibited t)))
958 ;; If auto-save was not already on, turn it on if appropriate.
959 (if (not buffer-auto-save-file-name)
6861ad22
RS
960 (auto-save-mode (and buffer-file-name auto-save-default))
961 ;; If auto save is on, start using a new name.
962 ;; We deliberately don't rename or delete the old auto save
963 ;; for the old visited file name. This is because perhaps
964 ;; the user wants to save the new state and then compare with the
965 ;; previous state from the auto save file.
966 (setq buffer-auto-save-file-name
967 (make-auto-save-file-name)))
b4da00e9
RM
968 (if buffer-file-name
969 (set-buffer-modified-p t)))
970
971(defun write-file (filename)
972 "Write current buffer into file FILENAME.
41f48cb1
RS
973Makes buffer visit that file, and marks it not modified.
974If the buffer is already visiting a file, you can specify
975a directory name as FILENAME, to write a file of the same
976old name in that directory."
b4da00e9
RM
977;; (interactive "FWrite file: ")
978 (interactive
979 (list (if buffer-file-name
980 (read-file-name "Write file: "
981 nil nil nil nil)
982 (read-file-name "Write file: "
983 (cdr (assq 'default-directory
984 (buffer-local-variables)))
985 nil nil (buffer-name)))))
986 (or (null filename) (string-equal filename "")
41f48cb1
RS
987 (progn
988 ;; If arg is just a directory,
989 ;; use same file name, but in that directory.
990 (if (and (file-directory-p filename) buffer-file-name)
991 (setq filename (concat (file-name-as-directory filename)
992 (file-name-nondirectory buffer-file-name))))
993 (set-visited-file-name filename)))
b4da00e9
RM
994 (set-buffer-modified-p t)
995 (save-buffer))
996\f
997(defun backup-buffer ()
998 "Make a backup of the disk file visited by the current buffer, if appropriate.
999This is normally done before saving the buffer the first time.
1000If the value is non-nil, it is the result of `file-modes' on the original
1001file; this means that the caller, after saving the buffer, should change
1002the modes of the new file to agree with the old modes."
1003 (if (and make-backup-files (not backup-inhibited)
1004 (not buffer-backed-up)
1005 (file-exists-p buffer-file-name)
1006 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1007 '(?- ?l)))
1008 (let ((real-file-name buffer-file-name)
1009 backup-info backupname targets setmodes)
1010 ;; If specified name is a symbolic link, chase it to the target.
1011 ;; Thus we make the backups in the directory where the real file is.
1012 (while (let ((tem (file-symlink-p real-file-name)))
1013 (if tem
1014 (setq real-file-name
1015 (expand-file-name tem
1016 (file-name-directory real-file-name))))
1017 tem))
1018 (setq backup-info (find-backup-file-name real-file-name)
1019 backupname (car backup-info)
1020 targets (cdr backup-info))
1021;;; (if (file-directory-p buffer-file-name)
1022;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1023 (condition-case ()
1024 (let ((delete-old-versions
1025 ;; If have old versions to maybe delete,
1026 ;; ask the user to confirm now, before doing anything.
1027 ;; But don't actually delete til later.
1028 (and targets
6d74b528 1029 (or (eq trim-versions-without-asking t) (eq trim-versions-without-asking nil))
b4da00e9
RM
1030 (or trim-versions-without-asking
1031 (y-or-n-p (format "Delete excess backup versions of %s? "
1032 real-file-name))))))
1033 ;; Actually write the back up file.
1034 (condition-case ()
1035 (if (or file-precious-flag
1036; (file-symlink-p buffer-file-name)
1037 backup-by-copying
1038 (and backup-by-copying-when-linked
1039 (> (file-nlinks real-file-name) 1))
1040 (and backup-by-copying-when-mismatch
1041 (let ((attr (file-attributes real-file-name)))
1042 (or (nth 9 attr)
1043 (/= (nth 2 attr) (user-uid))))))
65864ae0
RS
1044 (condition-case ()
1045 (copy-file real-file-name backupname t t)
1046 (file-error
1047 ;; If copying fails because file BACKUPNAME
1048 ;; is not writable, delete that file and try again.
1049 (if (and (file-exists-p backupname)
1050 (not (file-writable-p backupname)))
1051 (delete-file backupname))
1052 (copy-file real-file-name backupname t t)))
1053 ;; rename-file should delete old backup.
b4da00e9
RM
1054 (rename-file real-file-name backupname t)
1055 (setq setmodes (file-modes backupname)))
1056 (file-error
1057 ;; If trouble writing the backup, write it in ~.
1058 (setq backupname (expand-file-name "~/%backup%~"))
1059 (message "Cannot write backup file; backing up in ~/%%backup%%~")
1060 (sleep-for 1)
65864ae0
RS
1061 (condition-case ()
1062 (copy-file real-file-name backupname t t)
1063 (file-error
1064 ;; If copying fails because file BACKUPNAME
1065 ;; is not writable, delete that file and try again.
1066 (if (and (file-exists-p backupname)
1067 (not (file-writable-p backupname)))
1068 (delete-file backupname))
1069 (copy-file real-file-name backupname t t)))))
b4da00e9
RM
1070 (setq buffer-backed-up t)
1071 ;; Now delete the old versions, if desired.
1072 (if delete-old-versions
1073 (while targets
1074 (condition-case ()
1075 (delete-file (car targets))
1076 (file-error nil))
1077 (setq targets (cdr targets))))
1078 setmodes)
1079 (file-error nil)))))
1080
c3554e95 1081(defun file-name-sans-versions (name &optional keep-backup-version)
b4da00e9
RM
1082 "Return FILENAME sans backup versions or strings.
1083This is a separate procedure so your site-init or startup file can
c3554e95
RS
1084redefine it.
1085If the optional argument KEEP-BACKUP-VERSION is non-nil,
1086we do not remove backup version numbers, only true file version numbers."
5dbfdacd 1087 (let ((handler (find-file-name-handler name)))
c3554e95
RS
1088 (if handler
1089 (funcall handler 'file-name-sans-versions name keep-backup-version)
1090 (substring name 0
1091 (if (eq system-type 'vax-vms)
1092 ;; VMS version number is (a) semicolon, optional
1093 ;; sign, zero or more digits or (b) period, option
1094 ;; sign, zero or more digits, provided this is the
1095 ;; second period encountered outside of the
1096 ;; device/directory part of the file name.
1097 (or (string-match ";[---+]?[0-9]*\\'" name)
1098 (if (string-match "\\.[^]>:]*\\(\\.[---+]?[0-9]*\\)\\'"
1099 name)
1100 (match-beginning 1))
1101 (length name))
1102 (if keep-backup-version
1103 (length name)
1104 (or (string-match "\\.~[0-9]+~\\'" name)
1105 (string-match "~\\'" name)
1106 (length name))))))))
b4da00e9
RM
1107
1108(defun make-backup-file-name (file)
1109 "Create the non-numeric backup file name for FILE.
1110This is a separate function so you can redefine it for customization."
1111 (concat file "~"))
1112
1113(defun backup-file-name-p (file)
1114 "Return non-nil if FILE is a backup file name (numeric or not).
1115This is a separate function so you can redefine it for customization.
1116You may need to redefine `file-name-sans-versions' as well."
1117 (string-match "~$" file))
1118
2d051399
RS
1119;; This is used in various files.
1120;; The usage of bv-length is not very clean,
1121;; but I can't see a good alternative,
1122;; so as of now I am leaving it alone.
1123(defun backup-extract-version (fn)
1124 "Given the name of a numeric backup file, return the backup number.
1125Uses the free variable `bv-length', whose value should be
1126the index in the name where the version number begins."
1127 (if (and (string-match "[0-9]+~$" fn bv-length)
1128 (= (match-beginning 0) bv-length))
1129 (string-to-int (substring fn bv-length -1))
1130 0))
1131
b4da00e9
RM
1132;; I believe there is no need to alter this behavior for VMS;
1133;; since backup files are not made on VMS, it should not get called.
1134(defun find-backup-file-name (fn)
1135 "Find a file name for a backup file, and suggestions for deletions.
1136Value is a list whose car is the name for the backup file
1137 and whose cdr is a list of old versions to consider deleting now."
1138 (if (eq version-control 'never)
1139 (list (make-backup-file-name fn))
1140 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1141 (bv-length (length base-versions))
1142 (possibilities (file-name-all-completions
1143 base-versions
1144 (file-name-directory fn)))
79058860 1145 (versions (sort (mapcar
2d051399 1146 (function backup-extract-version)
79058860 1147 possibilities)
b4da00e9 1148 '<))
5bbbceb1 1149 (high-water-mark (apply 'max 0 versions))
b4da00e9
RM
1150 (deserve-versions-p
1151 (or version-control
1152 (> high-water-mark 0)))
1153 (number-to-delete (- (length versions)
1154 kept-old-versions kept-new-versions -1)))
1155 (if (not deserve-versions-p)
1156 (list (make-backup-file-name fn))
1157 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
9115e938
NF
1158 (if (and (> number-to-delete 0)
1159 ;; Delete nothing if there is overflow
1160 ;; in the number of versions to keep.
1161 (>= (+ kept-new-versions kept-old-versions -1) 0))
b4da00e9
RM
1162 (mapcar (function (lambda (n)
1163 (concat fn ".~" (int-to-string n) "~")))
1164 (let ((v (nthcdr kept-old-versions versions)))
1165 (rplacd (nthcdr (1- number-to-delete) v) ())
1166 v))))))))
1167
b4da00e9
RM
1168(defun file-nlinks (filename)
1169 "Return number of names file FILENAME has."
1170 (car (cdr (file-attributes filename))))
6c636af9 1171
46fa3073
RS
1172(defun file-relative-name-1 (directory)
1173 (cond ((string= directory "/")
1174 filename)
1175 ((string-match (concat "^" (regexp-quote directory))
1176 filename)
1177 (substring filename (match-end 0)))
1178 (t
1179 (file-relative-name-1
1180 (file-name-directory (substring directory 0 -1))))))
1181
6c636af9
RM
1182(defun file-relative-name (filename &optional directory)
1183 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1184 (setq filename (expand-file-name filename)
ea912aa6
RM
1185 directory (file-name-as-directory (if directory
1186 (expand-file-name directory)
6c636af9 1187 default-directory)))
46fa3073 1188 (file-relative-name-1 directory))
b4da00e9
RM
1189\f
1190(defun save-buffer (&optional args)
1191 "Save current buffer in visited file if modified. Versions described below.
1192By default, makes the previous version into a backup file
1193 if previously requested or if this is the first save.
1194With 1 or 3 \\[universal-argument]'s, marks this version
1195 to become a backup when the next save is done.
1196With 2 or 3 \\[universal-argument]'s,
1197 unconditionally makes the previous version into a backup file.
1198With argument of 0, never makes the previous version into a backup file.
1199
1200If a file's name is FOO, the names of its numbered backup versions are
1201 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1202Numeric backups (rather than FOO~) will be made if value of
1203 `version-control' is not the atom `never' and either there are already
1204 numeric versions of the file being backed up, or `version-control' is
1205 non-nil.
1206We don't want excessive versions piling up, so there are variables
1207 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1208 and `kept-new-versions', which tells how many newest versions to keep.
1209 Defaults are 2 old versions and 2 new.
1210`dired-kept-versions' controls dired's clean-directory (.) command.
1211If `trim-versions-without-asking' is nil, system will query user
1212 before trimming versions. Otherwise it does it silently."
1213 (interactive "p")
1214 (let ((modp (buffer-modified-p))
1215 (large (> (buffer-size) 50000))
1216 (make-backup-files (and make-backup-files (not (eq args 0)))))
1217 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
1218 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
1219 (basic-save-buffer)
1220 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
1221
1222(defun delete-auto-save-file-if-necessary (&optional force)
1223 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1224Normally delete only if the file was written by this Emacs since
1225the last real save, but optional arg FORCE non-nil means delete anyway."
1226 (and buffer-auto-save-file-name delete-auto-save-files
1227 (not (string= buffer-file-name buffer-auto-save-file-name))
1228 (or force (recent-auto-save-p))
1229 (progn
1230 (condition-case ()
1231 (delete-file buffer-auto-save-file-name)
1232 (file-error nil))
1233 (set-buffer-auto-saved))))
1234
1235(defun basic-save-buffer ()
1236 "Save the current buffer in its visited file, if it has been modified."
1237 (interactive)
1238 (if (buffer-modified-p)
1239 (let ((recent-save (recent-auto-save-p))
1240 setmodes tempsetmodes)
1241 ;; On VMS, rename file and buffer to get rid of version number.
1242 (if (and (eq system-type 'vax-vms)
1243 (not (string= buffer-file-name
1244 (file-name-sans-versions buffer-file-name))))
1245 (let (buffer-new-name)
1246 ;; Strip VMS version number before save.
1247 (setq buffer-file-name
1248 (file-name-sans-versions buffer-file-name))
1249 ;; Construct a (unique) buffer name to correspond.
1250 (let ((buf (create-file-buffer (downcase buffer-file-name))))
1251 (setq buffer-new-name (buffer-name buf))
1252 (kill-buffer buf))
1253 (rename-buffer buffer-new-name)))
1254 ;; If buffer has no file name, ask user for one.
1255 (or buffer-file-name
1256 (progn
1257 (setq buffer-file-name
1258 (expand-file-name (read-file-name "File to save in: ") nil)
1259 default-directory (file-name-directory buffer-file-name))
1260 (auto-save-mode auto-save-default)))
1261 (or (verify-visited-file-modtime (current-buffer))
1262 (not (file-exists-p buffer-file-name))
1263 (yes-or-no-p
1264 (format "%s has changed since visited or saved. Save anyway? "
1265 (file-name-nondirectory buffer-file-name)))
1266 (error "Save not confirmed"))
1267 (save-restriction
1268 (widen)
1269 (and (> (point-max) 1)
1270 (/= (char-after (1- (point-max))) ?\n)
1271 (or (eq require-final-newline t)
1272 (and require-final-newline
1273 (y-or-n-p
1274 (format "Buffer %s does not end in newline. Add one? "
1275 (buffer-name)))))
1276 (save-excursion
1277 (goto-char (point-max))
1278 (insert ?\n)))
c9dca4e0
RS
1279 (let ((hooks (append write-contents-hooks local-write-file-hooks
1280 write-file-hooks))
b4da00e9
RM
1281 (done nil))
1282 (while (and hooks
1283 (not (setq done (funcall (car hooks)))))
1284 (setq hooks (cdr hooks)))
1285 ;; If a hook returned t, file is already "written".
1286 (cond ((not done)
1287 (if (not (file-writable-p buffer-file-name))
1288 (let ((dir (file-name-directory buffer-file-name)))
1289 (if (not (file-directory-p dir))
1290 (error "%s is not a directory" dir)
1291 (if (not (file-exists-p buffer-file-name))
1292 (error "Directory %s write-protected" dir)
1293 (if (yes-or-no-p
1294 (format "File %s is write-protected; try to save anyway? "
1295 (file-name-nondirectory
1296 buffer-file-name)))
1297 (setq tempsetmodes t)
1298 (error "Attempt to save to a file which you aren't allowed to write"))))))
1299 (or buffer-backed-up
1300 (setq setmodes (backup-buffer)))
1301 (if file-precious-flag
f3e23606
RS
1302 ;; If file is precious, write temp name, then rename it.
1303 (let ((dir (file-name-directory buffer-file-name))
1304 (realname buffer-file-name)
1305 tempname temp nogood i succeed)
1306 (setq i 0)
1307 (setq nogood t)
1308 ;; Find the temporary name to write under.
1309 (while nogood
1310 (setq tempname (format "%s#tmp#%d" dir i))
1311 (setq nogood (file-exists-p tempname))
1312 (setq i (1+ i)))
b4da00e9
RM
1313 (unwind-protect
1314 (progn (clear-visited-file-modtime)
1315 (write-region (point-min) (point-max)
f3e23606
RS
1316 tempname nil realname)
1317 (setq succeed t))
1318 ;; If writing the temp file fails,
1319 ;; delete the temp file.
1320 (or succeed (delete-file tempname)))
b411d947
JB
1321 ;; Since we have created an entirely new file
1322 ;; and renamed it, make sure it gets the
1323 ;; right permission bits set.
1324 (setq setmodes (file-modes buffer-file-name))
f3e23606
RS
1325 ;; We succeeded in writing the temp file,
1326 ;; so rename it.
1327 (rename-file tempname buffer-file-name t))
b4da00e9
RM
1328 ;; If file not writable, see if we can make it writable
1329 ;; temporarily while we write it.
1330 ;; But no need to do so if we have just backed it up
1331 ;; (setmodes is set) because that says we're superseding.
1332 (cond ((and tempsetmodes (not setmodes))
1333 ;; Change the mode back, after writing.
1334 (setq setmodes (file-modes buffer-file-name))
1335 (set-file-modes buffer-file-name 511)))
1336 (write-region (point-min) (point-max)
1337 buffer-file-name nil t)))))
f3e23606 1338 (setq buffer-file-number (nth 10 (file-attributes buffer-file-name)))
b4da00e9
RM
1339 (if setmodes
1340 (condition-case ()
f3e23606 1341 (set-file-modes buffer-file-name setmodes)
b4da00e9
RM
1342 (error nil))))
1343 ;; If the auto-save file was recent before this command,
1344 ;; delete it now.
1345 (delete-auto-save-file-if-necessary recent-save)
1346 (run-hooks 'after-save-hooks))
1347 (message "(No changes need to be saved)")))
1348
b4da00e9
RM
1349(defun save-some-buffers (&optional arg exiting)
1350 "Save some modified file-visiting buffers. Asks user about each one.
5bbbceb1
JB
1351Optional argument (the prefix) non-nil means save all with no questions.
1352Optional second argument EXITING means ask about certain non-file buffers
1353 as well as about file buffers."
b4da00e9 1354 (interactive "P")
907482b9 1355 (save-window-excursion
b5e86cb3
RM
1356 (if (zerop (map-y-or-n-p
1357 (function
1358 (lambda (buffer)
1359 (and (buffer-modified-p buffer)
1360 (or
1361 (buffer-file-name buffer)
1362 (and exiting
1363 (progn
1364 (set-buffer buffer)
1365 (and buffer-offer-save (> (buffer-size) 0)))))
1366 (if arg
1367 t
1368 (if (buffer-file-name buffer)
1369 (format "Save file %s? "
1370 (buffer-file-name buffer))
1371 (format "Save buffer %s? "
1372 (buffer-name buffer)))))))
1373 (function
1374 (lambda (buffer)
e065a56e
JB
1375 (set-buffer buffer)
1376 (save-buffer)))
b5e86cb3 1377 (buffer-list)
907482b9 1378 '("buffer" "buffers" "save")
df01170b
RS
1379 (list (list ?\C-r (lambda (buf)
1380 (view-buffer buf)
1586b965
RS
1381 (setq view-exit-action
1382 '(lambda (ignore)
1383 (exit-recursive-edit)))
df01170b
RS
1384 (recursive-edit)
1385 ;; Return nil to ask about BUF again.
1386 nil)
907482b9
RM
1387 "display the current buffer"))
1388 ))
b5e86cb3 1389 (message "(No files need saving)"))))
b4da00e9
RM
1390\f
1391(defun not-modified (&optional arg)
1392 "Mark current buffer as unmodified, not needing to be saved.
1393With prefix arg, mark buffer as modified, so \\[save-buffer] will save."
1394 (interactive "P")
1395 (message (if arg "Modification-flag set"
1396 "Modification-flag cleared"))
1397 (set-buffer-modified-p arg))
1398
1399(defun toggle-read-only (&optional arg)
1400 "Change whether this buffer is visiting its file read-only.
1401With arg, set read-only iff arg is positive."
1402 (interactive "P")
1403 (setq buffer-read-only
1404 (if (null arg)
1405 (not buffer-read-only)
1406 (> (prefix-numeric-value arg) 0)))
1407 ;; Force mode-line redisplay
1408 (set-buffer-modified-p (buffer-modified-p)))
1409
1410(defun insert-file (filename)
1411 "Insert contents of file FILENAME into buffer after point.
1412Set mark after the inserted text.
1413
1414This function is meant for the user to run interactively.
1415Don't call it from programs! Use `insert-file-contents' instead.
1416\(Its calling sequence is different; see its documentation)."
1417 (interactive "fInsert file: ")
1418 (let ((tem (insert-file-contents filename)))
1419 (push-mark (+ (point) (car (cdr tem))))))
1420
1421(defun append-to-file (start end filename)
1422 "Append the contents of the region to the end of file FILENAME.
1423When called from a function, expects three arguments,
1424START, END and FILENAME. START and END are buffer positions
1425saying what text to write."
1426 (interactive "r\nFAppend to file: ")
1427 (write-region start end filename t))
1428
1429(defun file-newest-backup (filename)
1430 "Return most recent backup file for FILENAME or nil if no backups exist."
1431 (let* ((filename (expand-file-name filename))
1432 (file (file-name-nondirectory filename))
1433 (dir (file-name-directory filename))
1434 (comp (file-name-all-completions file dir))
1435 newest)
1436 (while comp
1437 (setq file (concat dir (car comp))
1438 comp (cdr comp))
1439 (if (and (backup-file-name-p file)
1440 (or (null newest) (file-newer-than-file-p file newest)))
1441 (setq newest file)))
1442 newest))
1443
1444(defun rename-uniquely ()
1445 "Rename current buffer to a similar name not already taken.
1446This function is useful for creating multiple shell process buffers
1447or multiple mail buffers, etc."
1448 (interactive)
1449 (let* ((new-buf (generate-new-buffer (buffer-name)))
1450 (name (buffer-name new-buf)))
1451 (kill-buffer new-buf)
1452 (rename-buffer name)
1453 (set-buffer-modified-p (buffer-modified-p)))) ; force mode line update
5bbbceb1 1454
4e43240a
RS
1455(defun make-directory (dir &optional parents)
1456 "Create the directory DIR and any nonexistent parent dirs."
1457 (interactive "FMake directory: \nP")
5dbfdacd 1458 (let ((handler (find-file-name-handler dir)))
4e43240a
RS
1459 (if handler
1460 (funcall handler 'make-directory dir parents)
1461 (if (not parents)
1462 (make-directory-internal dir)
1463 (let ((dir (directory-file-name (expand-file-name dir)))
1464 create-list)
1465 (while (not (file-exists-p dir))
1466 (setq create-list (cons dir create-list)
1467 dir (directory-file-name (file-name-directory dir))))
1468 (while create-list
1469 (make-directory-internal (car create-list))
1470 (setq create-list (cdr create-list))))))))
b4da00e9
RM
1471\f
1472(put 'revert-buffer-function 'permanent-local t)
1473(defvar revert-buffer-function nil
1474 "Function to use to revert this buffer, or nil to do the default.")
1475
1476(put 'revert-buffer-insert-file-contents-function 'permanent-local t)
1477(defvar revert-buffer-insert-file-contents-function nil
1478 "Function to use to insert contents when reverting this buffer.
1479Gets two args, first the nominal file name to use,
1480and second, t if reading the auto-save file.")
1481
1ab31687 1482(defun revert-buffer (&optional ignore-auto noconfirm)
b4da00e9
RM
1483 "Replace the buffer text with the text of the visited file on disk.
1484This undoes all changes since the file was visited or saved.
8c0e7b73
JB
1485With a prefix argument, offer to revert from latest auto-save file, if
1486that is more recent than the visited file.
1ab31687
JB
1487
1488When called from lisp, the first argument is IGNORE-AUTO; only offer
1489to revert from the auto-save file when this is nil. Note that the
1490sense of this argument is the reverse of the prefix argument, for the
1491sake of backward compatibility. IGNORE-AUTO is optional, defaulting
1492to nil.
1493
1494Optional second argument NOCONFIRM means don't ask for confirmation at
1495all.
b4da00e9 1496
8c0e7b73
JB
1497If the value of `revert-buffer-function' is non-nil, it is called to
1498do the work."
1ab31687
JB
1499 ;; I admit it's odd to reverse the sense of the prefix argument, but
1500 ;; there is a lot of code out there which assumes that the first
1501 ;; argument should be t to avoid consulting the auto-save file, and
1502 ;; there's no straightforward way to encourage authors to notice a
1503 ;; reversal of the argument sense. So I'm just changing the user
1504 ;; interface, but leaving the programmatic interface the same.
1505 (interactive (list (not prefix-arg)))
b4da00e9 1506 (if revert-buffer-function
1ab31687 1507 (funcall revert-buffer-function ignore-auto noconfirm)
b4da00e9 1508 (let* ((opoint (point))
1ab31687
JB
1509 (auto-save-p (and (not ignore-auto)
1510 (recent-auto-save-p)
b4da00e9
RM
1511 buffer-auto-save-file-name
1512 (file-readable-p buffer-auto-save-file-name)
1513 (y-or-n-p
1514 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
1515 (file-name (if auto-save-p
1516 buffer-auto-save-file-name
1517 buffer-file-name)))
1518 (cond ((null file-name)
1519 (error "Buffer does not seem to be associated with any file"))
1520 ((or noconfirm
1521 (yes-or-no-p (format "Revert buffer from file %s? "
1522 file-name)))
1523 ;; If file was backed up but has changed since,
1524 ;; we shd make another backup.
1525 (and (not auto-save-p)
5bbbceb1 1526 (not (verify-visited-file-modtime (current-buffer)))
b4da00e9
RM
1527 (setq buffer-backed-up nil))
1528 ;; Get rid of all undo records for this buffer.
1529 (or (eq buffer-undo-list t)
1530 (setq buffer-undo-list nil))
1531 (let ((buffer-read-only nil)
1532 ;; Don't make undo records for the reversion.
1533 (buffer-undo-list t))
1534 (if revert-buffer-insert-file-contents-function
1535 (funcall revert-buffer-insert-file-contents-function
1536 file-name auto-save-p)
1537 (if (not (file-exists-p file-name))
1538 (error "File %s no longer exists!" file-name))
1539 ;; Bind buffer-file-name to nil
1540 ;; so that we don't try to lock the file.
1541 (let ((buffer-file-name nil))
1542 (or auto-save-p
1543 (unlock-buffer))
1544 (erase-buffer))
1545 (insert-file-contents file-name (not auto-save-p))))
1546 (goto-char (min opoint (point-max)))
8cfb9d46 1547 (after-find-file nil nil t)
b4da00e9
RM
1548 t)))))
1549
1550(defun recover-file (file)
1551 "Visit file FILE, but get contents from its last auto-save file."
1552 (interactive
1553 (let ((prompt-file buffer-file-name)
1554 (file-name nil)
1555 (file-dir nil))
1556 (and prompt-file
1557 (setq file-name (file-name-nondirectory prompt-file)
1558 file-dir (file-name-directory prompt-file)))
1559 (list (read-file-name "Recover file: "
1560 file-dir nil nil file-name))))
1561 (setq file (expand-file-name file))
1562 (if (auto-save-file-name-p file) (error "%s is an auto-save file" file))
1563 (let ((file-name (let ((buffer-file-name file))
1564 (make-auto-save-file-name))))
1565 (cond ((not (file-newer-than-file-p file-name file))
1566 (error "Auto-save file %s not current" file-name))
1567 ((save-window-excursion
1568 (if (not (eq system-type 'vax-vms))
1569 (with-output-to-temp-buffer "*Directory*"
1570 (buffer-disable-undo standard-output)
1571 (call-process "ls" nil standard-output nil
2dc2b736
RS
1572 (if (file-symlink-p file) "-lL" "-l")
1573 file file-name)))
b4da00e9
RM
1574 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
1575 (switch-to-buffer (find-file-noselect file t))
1576 (let ((buffer-read-only nil))
1577 (erase-buffer)
1578 (insert-file-contents file-name nil))
8cfb9d46 1579 (after-find-file nil nil t))
b4da00e9
RM
1580 (t (error "Recover-file cancelled.")))))
1581
1582(defun kill-some-buffers ()
1583 "For each buffer, ask whether to kill it."
1584 (interactive)
1585 (let ((list (buffer-list)))
1586 (while list
1587 (let* ((buffer (car list))
1588 (name (buffer-name buffer)))
1589 (and (not (string-equal name ""))
1590 (/= (aref name 0) ? )
1591 (yes-or-no-p
1592 (format "Buffer %s %s. Kill? "
1593 name
1594 (if (buffer-modified-p buffer)
1595 "HAS BEEN EDITED" "is unmodified")))
1596 (kill-buffer buffer)))
1597 (setq list (cdr list)))))
1598\f
1599(defun auto-save-mode (arg)
1600 "Toggle auto-saving of contents of current buffer.
f3e23606 1601With prefix argument ARG, turn auto-saving on if positive, else off."
b4da00e9
RM
1602 (interactive "P")
1603 (setq buffer-auto-save-file-name
1604 (and (if (null arg)
1605 (not buffer-auto-save-file-name)
1606 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
1607 (if (and buffer-file-name auto-save-visited-file-name
1608 (not buffer-read-only))
1609 buffer-file-name
1610 (make-auto-save-file-name))))
1611 (if (interactive-p)
1612 (message "Auto-save %s (in this buffer)"
1613 (if buffer-auto-save-file-name "on" "off")))
1614 buffer-auto-save-file-name)
1615
1616(defun rename-auto-save-file ()
1617 "Adjust current buffer's auto save file name for current conditions.
1618Also rename any existing auto save file, if it was made in this session."
1619 (let ((osave buffer-auto-save-file-name))
1620 (setq buffer-auto-save-file-name
1621 (make-auto-save-file-name))
1622 (if (and osave buffer-auto-save-file-name
1623 (not (string= buffer-auto-save-file-name buffer-file-name))
1624 (not (string= buffer-auto-save-file-name osave))
1625 (file-exists-p osave)
1626 (recent-auto-save-p))
1627 (rename-file osave buffer-auto-save-file-name t))))
1628
1629(defun make-auto-save-file-name ()
1630 "Return file name to use for auto-saves of current buffer.
1631Does not consider `auto-save-visited-file-name' as that variable is checked
1632before calling this function. You can redefine this for customization.
1633See also `auto-save-file-name-p'."
1634 (if buffer-file-name
1635 (concat (file-name-directory buffer-file-name)
1636 "#"
1637 (file-name-nondirectory buffer-file-name)
1638 "#")
1639 ;; For non-file bfr, use bfr name and Emacs pid.
1640 (expand-file-name (format "#%s#%s#" (buffer-name) (make-temp-name "")))))
1641
1642(defun auto-save-file-name-p (filename)
1643 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
1644FILENAME should lack slashes. You can redefine this for customization."
1645 (string-match "^#.*#$" filename))
1646\f
1647(defconst list-directory-brief-switches
1648 (if (eq system-type 'vax-vms) "" "-CF")
1649 "*Switches for list-directory to pass to `ls' for brief listing,")
1650
1651(defconst list-directory-verbose-switches
1652 (if (eq system-type 'vax-vms)
1653 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
1654 "-l")
1655 "*Switches for list-directory to pass to `ls' for verbose listing,")
1656
1657(defun list-directory (dirname &optional verbose)
1658 "Display a list of files in or matching DIRNAME, a la `ls'.
1659DIRNAME is globbed by the shell if necessary.
1660Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
1661Actions controlled by variables `list-directory-brief-switches'
1662and `list-directory-verbose-switches'."
1663 (interactive (let ((pfx current-prefix-arg))
1664 (list (read-file-name (if pfx "List directory (verbose): "
1665 "List directory (brief): ")
1666 nil default-directory nil)
1667 pfx)))
1668 (let ((switches (if verbose list-directory-verbose-switches
1669 list-directory-brief-switches)))
1670 (or dirname (setq dirname default-directory))
1671 (setq dirname (expand-file-name dirname))
1672 (with-output-to-temp-buffer "*Directory*"
1673 (buffer-disable-undo standard-output)
1674 (princ "Directory ")
1675 (princ dirname)
1676 (terpri)
c3554e95
RS
1677 (save-excursion
1678 (set-buffer "*Directory*")
1679 (let ((wildcard (not (file-directory-p dirname))))
1680 (insert-directory dirname switches wildcard (not wildcard)))))))
1681
1682(defvar insert-directory-program "ls"
1683 "Absolute or relative name of the `ls' program used by `insert-directory'.")
1684
1685;; insert-directory
1686;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
1687;; FULL-DIRECTORY-P is nil.
1688;; The single line of output must display FILE's name as it was
1689;; given, namely, an absolute path name.
1690;; - must insert exactly one line for each file if WILDCARD or
1691;; FULL-DIRECTORY-P is t, plus one optional "total" line
1692;; before the file lines, plus optional text after the file lines.
1693;; Lines are delimited by "\n", so filenames containing "\n" are not
1694;; allowed.
1695;; File lines should display the basename.
1696;; - must be consistent with
1697;; - functions dired-move-to-filename, (these two define what a file line is)
1698;; dired-move-to-end-of-filename,
1699;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
1700;; dired-insert-headerline
1701;; dired-after-subdir-garbage (defines what a "total" line is)
1702;; - variable dired-subdir-regexp
1703(defun insert-directory (file switches &optional wildcard full-directory-p)
1704 "Insert directory listing for of FILE, formatted according to SWITCHES.
1705Leaves point after the inserted text.
1706Optional third arg WILDCARD means treat FILE as shell wildcard.
1707Optional fourth arg FULL-DIRECTORY-P means file is a directory and
1708switches do not contain `d', so that a full listing is expected.
1709
1710This works by running a directory listing program
406e12d9 1711whose name is in the variable `insert-directory-program'.
c3554e95 1712If WILDCARD, it also runs the shell specified by `shell-file-name'."
5dbfdacd 1713 (let ((handler (find-file-name-handler file)))
c3554e95
RS
1714 (if handler
1715 (funcall handler 'insert-directory file switches
1716 wildcard full-directory-p)
b4da00e9 1717 (if (eq system-type 'vax-vms)
c3554e95
RS
1718 (vms-read-directory file switches (current-buffer))
1719 (if wildcard
1720 (let ((default-directory (file-name-directory file)))
1721 (call-process shell-file-name nil t nil
1722 "-c" (concat insert-directory-program
1723 " -d " switches " "
1724 (file-name-nondirectory file))))
632c2579
JB
1725 ;; Chase links till we reach a non-link.
1726 ;; This used to be commented out, but Barry Margolin says:
1727 ;; SunOS 4.1.3 (and SV and POSIX?) lists the link
1728 ;; if we give a link to a directory - yuck!
1729 (let (symlink)
1730 (while (setq symlink (file-symlink-p file))
1731 (setq file symlink)))
c3554e95 1732 (call-process insert-directory-program nil t nil switches file))))))
b4da00e9
RM
1733
1734(defun save-buffers-kill-emacs (&optional arg)
1735 "Offer to save each buffer, then kill this Emacs process.
1736With prefix arg, silently save all file-visiting buffers, then kill."
1737 (interactive "P")
1738 (save-some-buffers arg t)
1739 (and (or (not (memq t (mapcar (function
1740 (lambda (buf) (and (buffer-file-name buf)
1741 (buffer-modified-p buf))))
1742 (buffer-list))))
1743 (yes-or-no-p "Modified buffers exist; exit anyway? "))
1744 (or (not (fboundp 'process-list))
1745 ;; process-list is not defined on VMS.
1746 (let ((processes (process-list))
1747 active)
1748 (while processes
528415e7 1749 (and (memq (process-status (car processes)) '(run stop open))
b4da00e9
RM
1750 (let ((val (process-kill-without-query (car processes))))
1751 (process-kill-without-query (car processes) val)
1752 val)
1753 (setq active t))
1754 (setq processes (cdr processes)))
1755 (or (not active)
1756 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
1757 (kill-emacs)))
1758\f
1759(define-key ctl-x-map "\C-f" 'find-file)
1760(define-key ctl-x-map "\C-q" 'toggle-read-only)
1761(define-key ctl-x-map "\C-r" 'find-file-read-only)
1762(define-key ctl-x-map "\C-v" 'find-alternate-file)
1763(define-key ctl-x-map "\C-s" 'save-buffer)
1764(define-key ctl-x-map "s" 'save-some-buffers)
1765(define-key ctl-x-map "\C-w" 'write-file)
1766(define-key ctl-x-map "i" 'insert-file)
1767(define-key esc-map "~" 'not-modified)
1768(define-key ctl-x-map "\C-d" 'list-directory)
1769(define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
1770
1771(define-key ctl-x-4-map "f" 'find-file-other-window)
1772(define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
1773(define-key ctl-x-4-map "\C-f" 'find-file-other-window)
1774(define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
924f0a24 1775(define-key ctl-x-4-map "\C-o" 'display-buffer)
5bbbceb1 1776
f98955ea
JB
1777(define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
1778(define-key ctl-x-5-map "f" 'find-file-other-frame)
1779(define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
1780(define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
c0274f38
ER
1781
1782;;; files.el ends here