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