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