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