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