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