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