*** 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)))
79058860
JB
842 (versions (sort (mapcar
843 (function
844 (lambda (fn)
845 (if (and (string-match "[0-9]+~$" fn bv-length)
846 (= (match-beginning 0) bv-length))
847 (string-to-int (substring fn bv-length -1))
848 0)))
849 possibilities)
b4da00e9 850 '<))
5bbbceb1 851 (high-water-mark (apply 'max 0 versions))
b4da00e9
RM
852 (deserve-versions-p
853 (or version-control
854 (> high-water-mark 0)))
855 (number-to-delete (- (length versions)
856 kept-old-versions kept-new-versions -1)))
857 (if (not deserve-versions-p)
858 (list (make-backup-file-name fn))
859 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
860 (if (> number-to-delete 0)
861 (mapcar (function (lambda (n)
862 (concat fn ".~" (int-to-string n) "~")))
863 (let ((v (nthcdr kept-old-versions versions)))
864 (rplacd (nthcdr (1- number-to-delete) v) ())
865 v))))))))
866
b4da00e9
RM
867(defun file-nlinks (filename)
868 "Return number of names file FILENAME has."
869 (car (cdr (file-attributes filename))))
870\f
871(defun save-buffer (&optional args)
872 "Save current buffer in visited file if modified. Versions described below.
873By default, makes the previous version into a backup file
874 if previously requested or if this is the first save.
875With 1 or 3 \\[universal-argument]'s, marks this version
876 to become a backup when the next save is done.
877With 2 or 3 \\[universal-argument]'s,
878 unconditionally makes the previous version into a backup file.
879With argument of 0, never makes the previous version into a backup file.
880
881If a file's name is FOO, the names of its numbered backup versions are
882 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
883Numeric backups (rather than FOO~) will be made if value of
884 `version-control' is not the atom `never' and either there are already
885 numeric versions of the file being backed up, or `version-control' is
886 non-nil.
887We don't want excessive versions piling up, so there are variables
888 `kept-old-versions', which tells Emacs how many oldest versions to keep,
889 and `kept-new-versions', which tells how many newest versions to keep.
890 Defaults are 2 old versions and 2 new.
891`dired-kept-versions' controls dired's clean-directory (.) command.
892If `trim-versions-without-asking' is nil, system will query user
893 before trimming versions. Otherwise it does it silently."
894 (interactive "p")
895 (let ((modp (buffer-modified-p))
896 (large (> (buffer-size) 50000))
897 (make-backup-files (and make-backup-files (not (eq args 0)))))
898 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
899 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
900 (basic-save-buffer)
901 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
902
903(defun delete-auto-save-file-if-necessary (&optional force)
904 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
905Normally delete only if the file was written by this Emacs since
906the last real save, but optional arg FORCE non-nil means delete anyway."
907 (and buffer-auto-save-file-name delete-auto-save-files
908 (not (string= buffer-file-name buffer-auto-save-file-name))
909 (or force (recent-auto-save-p))
910 (progn
911 (condition-case ()
912 (delete-file buffer-auto-save-file-name)
913 (file-error nil))
914 (set-buffer-auto-saved))))
915
916(defun basic-save-buffer ()
917 "Save the current buffer in its visited file, if it has been modified."
918 (interactive)
919 (if (buffer-modified-p)
920 (let ((recent-save (recent-auto-save-p))
921 setmodes tempsetmodes)
922 ;; On VMS, rename file and buffer to get rid of version number.
923 (if (and (eq system-type 'vax-vms)
924 (not (string= buffer-file-name
925 (file-name-sans-versions buffer-file-name))))
926 (let (buffer-new-name)
927 ;; Strip VMS version number before save.
928 (setq buffer-file-name
929 (file-name-sans-versions buffer-file-name))
930 ;; Construct a (unique) buffer name to correspond.
931 (let ((buf (create-file-buffer (downcase buffer-file-name))))
932 (setq buffer-new-name (buffer-name buf))
933 (kill-buffer buf))
934 (rename-buffer buffer-new-name)))
935 ;; If buffer has no file name, ask user for one.
936 (or buffer-file-name
937 (progn
938 (setq buffer-file-name
939 (expand-file-name (read-file-name "File to save in: ") nil)
940 default-directory (file-name-directory buffer-file-name))
941 (auto-save-mode auto-save-default)))
942 (or (verify-visited-file-modtime (current-buffer))
943 (not (file-exists-p buffer-file-name))
944 (yes-or-no-p
945 (format "%s has changed since visited or saved. Save anyway? "
946 (file-name-nondirectory buffer-file-name)))
947 (error "Save not confirmed"))
948 (save-restriction
949 (widen)
950 (and (> (point-max) 1)
951 (/= (char-after (1- (point-max))) ?\n)
952 (or (eq require-final-newline t)
953 (and require-final-newline
954 (y-or-n-p
955 (format "Buffer %s does not end in newline. Add one? "
956 (buffer-name)))))
957 (save-excursion
958 (goto-char (point-max))
959 (insert ?\n)))
8c0e7b73 960 (let ((hooks (append write-contents-hooks write-file-hooks))
b4da00e9
RM
961 (done nil))
962 (while (and hooks
963 (not (setq done (funcall (car hooks)))))
964 (setq hooks (cdr hooks)))
965 ;; If a hook returned t, file is already "written".
966 (cond ((not done)
967 (if (not (file-writable-p buffer-file-name))
968 (let ((dir (file-name-directory buffer-file-name)))
969 (if (not (file-directory-p dir))
970 (error "%s is not a directory" dir)
971 (if (not (file-exists-p buffer-file-name))
972 (error "Directory %s write-protected" dir)
973 (if (yes-or-no-p
974 (format "File %s is write-protected; try to save anyway? "
975 (file-name-nondirectory
976 buffer-file-name)))
977 (setq tempsetmodes t)
978 (error "Attempt to save to a file which you aren't allowed to write"))))))
979 (or buffer-backed-up
980 (setq setmodes (backup-buffer)))
981 (if file-precious-flag
982 ;; If file is precious, rename it away before
983 ;; overwriting it.
984 (let ((rename t)
985 realname tempname temp)
986 ;; Chase symlinks; rename the ultimate actual file.
987 (setq realname buffer-file-name)
988 (while (setq temp (file-symlink-p realname))
989 (setq realname temp))
990 (setq tempname (concat realname "#"))
991 (condition-case ()
992 (progn (rename-file realname tempname t)
993 (setq setmodes (file-modes tempname)))
994 (file-error (setq rename nil tempname nil)))
995 (if (file-directory-p realname)
996 (error "%s is a directory" realname))
997 (unwind-protect
998 (progn (clear-visited-file-modtime)
999 (write-region (point-min) (point-max)
1000 realname nil t)
1001 (setq rename nil))
1002 ;; If rename is still t, writing failed.
1003 ;; So rename the old file back to original name,
1004 (if rename
1005 (progn
1006 (rename-file tempname realname t)
1007 (clear-visited-file-modtime))
1008 ;; Otherwise we don't need the original file,
1009 ;; so flush it, if we still have it.
1010 ;; If rename failed due to name length restriction
1011 ;; then TEMPNAME is now nil.
1012 (if tempname
1013 (condition-case ()
1014 (delete-file tempname)
1015 (error nil))))))
1016 ;; If file not writable, see if we can make it writable
1017 ;; temporarily while we write it.
1018 ;; But no need to do so if we have just backed it up
1019 ;; (setmodes is set) because that says we're superseding.
1020 (cond ((and tempsetmodes (not setmodes))
1021 ;; Change the mode back, after writing.
1022 (setq setmodes (file-modes buffer-file-name))
1023 (set-file-modes buffer-file-name 511)))
1024 (write-region (point-min) (point-max)
1025 buffer-file-name nil t)))))
1026 (if setmodes
1027 (condition-case ()
1028 (set-file-modes buffer-file-name setmodes)
1029 (error nil))))
1030 ;; If the auto-save file was recent before this command,
1031 ;; delete it now.
1032 (delete-auto-save-file-if-necessary recent-save)
1033 (run-hooks 'after-save-hooks))
1034 (message "(No changes need to be saved)")))
1035
b4da00e9
RM
1036(defun save-some-buffers (&optional arg exiting)
1037 "Save some modified file-visiting buffers. Asks user about each one.
5bbbceb1
JB
1038Optional argument (the prefix) non-nil means save all with no questions.
1039Optional second argument EXITING means ask about certain non-file buffers
1040 as well as about file buffers."
b4da00e9 1041 (interactive "P")
b5e86cb3
RM
1042 (save-excursion
1043 (if (zerop (map-y-or-n-p
1044 (function
1045 (lambda (buffer)
1046 (and (buffer-modified-p buffer)
1047 (or
1048 (buffer-file-name buffer)
1049 (and exiting
1050 (progn
1051 (set-buffer buffer)
1052 (and buffer-offer-save (> (buffer-size) 0)))))
1053 (if arg
1054 t
1055 (if (buffer-file-name buffer)
1056 (format "Save file %s? "
1057 (buffer-file-name buffer))
1058 (format "Save buffer %s? "
1059 (buffer-name buffer)))))))
1060 (function
1061 (lambda (buffer)
e065a56e
JB
1062 (set-buffer buffer)
1063 (save-buffer)))
b5e86cb3
RM
1064 (buffer-list)
1065 '("buffer" "buffers" "save")))
1066 (message "(No files need saving)"))))
b4da00e9
RM
1067\f
1068(defun not-modified (&optional arg)
1069 "Mark current buffer as unmodified, not needing to be saved.
1070With prefix arg, mark buffer as modified, so \\[save-buffer] will save."
1071 (interactive "P")
1072 (message (if arg "Modification-flag set"
1073 "Modification-flag cleared"))
1074 (set-buffer-modified-p arg))
1075
1076(defun toggle-read-only (&optional arg)
1077 "Change whether this buffer is visiting its file read-only.
1078With arg, set read-only iff arg is positive."
1079 (interactive "P")
1080 (setq buffer-read-only
1081 (if (null arg)
1082 (not buffer-read-only)
1083 (> (prefix-numeric-value arg) 0)))
1084 ;; Force mode-line redisplay
1085 (set-buffer-modified-p (buffer-modified-p)))
1086
1087(defun insert-file (filename)
1088 "Insert contents of file FILENAME into buffer after point.
1089Set mark after the inserted text.
1090
1091This function is meant for the user to run interactively.
1092Don't call it from programs! Use `insert-file-contents' instead.
1093\(Its calling sequence is different; see its documentation)."
1094 (interactive "fInsert file: ")
1095 (let ((tem (insert-file-contents filename)))
1096 (push-mark (+ (point) (car (cdr tem))))))
1097
1098(defun append-to-file (start end filename)
1099 "Append the contents of the region to the end of file FILENAME.
1100When called from a function, expects three arguments,
1101START, END and FILENAME. START and END are buffer positions
1102saying what text to write."
1103 (interactive "r\nFAppend to file: ")
1104 (write-region start end filename t))
1105
1106(defun file-newest-backup (filename)
1107 "Return most recent backup file for FILENAME or nil if no backups exist."
1108 (let* ((filename (expand-file-name filename))
1109 (file (file-name-nondirectory filename))
1110 (dir (file-name-directory filename))
1111 (comp (file-name-all-completions file dir))
1112 newest)
1113 (while comp
1114 (setq file (concat dir (car comp))
1115 comp (cdr comp))
1116 (if (and (backup-file-name-p file)
1117 (or (null newest) (file-newer-than-file-p file newest)))
1118 (setq newest file)))
1119 newest))
1120
1121(defun rename-uniquely ()
1122 "Rename current buffer to a similar name not already taken.
1123This function is useful for creating multiple shell process buffers
1124or multiple mail buffers, etc."
1125 (interactive)
1126 (let* ((new-buf (generate-new-buffer (buffer-name)))
1127 (name (buffer-name new-buf)))
1128 (kill-buffer new-buf)
1129 (rename-buffer name)
1130 (set-buffer-modified-p (buffer-modified-p)))) ; force mode line update
5bbbceb1
JB
1131
1132(defun make-directory-path (path)
1133 "Create all the directories along path that don't exist yet."
1134 (interactive "Fdirectory path to create: ")
1135 (let ((path (directory-file-name (expand-file-name path)))
1136 create-list)
1137 (while (not (file-exists-p path))
1138 (setq create-list (cons path create-list)
1139 path (directory-file-name (file-name-directory path))))
1140 (while create-list
1141 (make-directory (car create-list))
1142 (setq create-list (cdr create-list)))))
1143
b4da00e9
RM
1144\f
1145(put 'revert-buffer-function 'permanent-local t)
1146(defvar revert-buffer-function nil
1147 "Function to use to revert this buffer, or nil to do the default.")
1148
1149(put 'revert-buffer-insert-file-contents-function 'permanent-local t)
1150(defvar revert-buffer-insert-file-contents-function nil
1151 "Function to use to insert contents when reverting this buffer.
1152Gets two args, first the nominal file name to use,
1153and second, t if reading the auto-save file.")
1154
8c0e7b73 1155(defun revert-buffer (&optional check-auto noconfirm)
b4da00e9
RM
1156 "Replace the buffer text with the text of the visited file on disk.
1157This undoes all changes since the file was visited or saved.
8c0e7b73
JB
1158With a prefix argument, offer to revert from latest auto-save file, if
1159that is more recent than the visited file.
1160When called from lisp, this is the first argument, CHECK-AUTO; it is optional.
b4da00e9
RM
1161Optional second argument NOCONFIRM means don't ask for confirmation at all.
1162
8c0e7b73
JB
1163If the value of `revert-buffer-function' is non-nil, it is called to
1164do the work."
b4da00e9
RM
1165 (interactive "P")
1166 (if revert-buffer-function
8c0e7b73 1167 (funcall revert-buffer-function (not check-auto) noconfirm)
b4da00e9 1168 (let* ((opoint (point))
8c0e7b73 1169 (auto-save-p (and check-auto (recent-auto-save-p)
b4da00e9
RM
1170 buffer-auto-save-file-name
1171 (file-readable-p buffer-auto-save-file-name)
1172 (y-or-n-p
1173 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
1174 (file-name (if auto-save-p
1175 buffer-auto-save-file-name
1176 buffer-file-name)))
1177 (cond ((null file-name)
1178 (error "Buffer does not seem to be associated with any file"))
1179 ((or noconfirm
1180 (yes-or-no-p (format "Revert buffer from file %s? "
1181 file-name)))
1182 ;; If file was backed up but has changed since,
1183 ;; we shd make another backup.
1184 (and (not auto-save-p)
5bbbceb1 1185 (not (verify-visited-file-modtime (current-buffer)))
b4da00e9
RM
1186 (setq buffer-backed-up nil))
1187 ;; Get rid of all undo records for this buffer.
1188 (or (eq buffer-undo-list t)
1189 (setq buffer-undo-list nil))
1190 (let ((buffer-read-only nil)
1191 ;; Don't make undo records for the reversion.
1192 (buffer-undo-list t))
1193 (if revert-buffer-insert-file-contents-function
1194 (funcall revert-buffer-insert-file-contents-function
1195 file-name auto-save-p)
1196 (if (not (file-exists-p file-name))
1197 (error "File %s no longer exists!" file-name))
1198 ;; Bind buffer-file-name to nil
1199 ;; so that we don't try to lock the file.
1200 (let ((buffer-file-name nil))
1201 (or auto-save-p
1202 (unlock-buffer))
1203 (erase-buffer))
1204 (insert-file-contents file-name (not auto-save-p))))
1205 (goto-char (min opoint (point-max)))
1206 (after-find-file nil)
1207 t)))))
1208
1209(defun recover-file (file)
1210 "Visit file FILE, but get contents from its last auto-save file."
1211 (interactive
1212 (let ((prompt-file buffer-file-name)
1213 (file-name nil)
1214 (file-dir nil))
1215 (and prompt-file
1216 (setq file-name (file-name-nondirectory prompt-file)
1217 file-dir (file-name-directory prompt-file)))
1218 (list (read-file-name "Recover file: "
1219 file-dir nil nil file-name))))
1220 (setq file (expand-file-name file))
1221 (if (auto-save-file-name-p file) (error "%s is an auto-save file" file))
1222 (let ((file-name (let ((buffer-file-name file))
1223 (make-auto-save-file-name))))
1224 (cond ((not (file-newer-than-file-p file-name file))
1225 (error "Auto-save file %s not current" file-name))
1226 ((save-window-excursion
1227 (if (not (eq system-type 'vax-vms))
1228 (with-output-to-temp-buffer "*Directory*"
1229 (buffer-disable-undo standard-output)
1230 (call-process "ls" nil standard-output nil
2dc2b736
RS
1231 (if (file-symlink-p file) "-lL" "-l")
1232 file file-name)))
b4da00e9
RM
1233 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
1234 (switch-to-buffer (find-file-noselect file t))
1235 (let ((buffer-read-only nil))
1236 (erase-buffer)
1237 (insert-file-contents file-name nil))
1238 (after-find-file nil))
1239 (t (error "Recover-file cancelled.")))))
1240
1241(defun kill-some-buffers ()
1242 "For each buffer, ask whether to kill it."
1243 (interactive)
1244 (let ((list (buffer-list)))
1245 (while list
1246 (let* ((buffer (car list))
1247 (name (buffer-name buffer)))
1248 (and (not (string-equal name ""))
1249 (/= (aref name 0) ? )
1250 (yes-or-no-p
1251 (format "Buffer %s %s. Kill? "
1252 name
1253 (if (buffer-modified-p buffer)
1254 "HAS BEEN EDITED" "is unmodified")))
1255 (kill-buffer buffer)))
1256 (setq list (cdr list)))))
1257\f
1258(defun auto-save-mode (arg)
1259 "Toggle auto-saving of contents of current buffer.
1260With ARG, turn auto-saving on if positive, else off."
1261 (interactive "P")
1262 (setq buffer-auto-save-file-name
1263 (and (if (null arg)
1264 (not buffer-auto-save-file-name)
1265 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
1266 (if (and buffer-file-name auto-save-visited-file-name
1267 (not buffer-read-only))
1268 buffer-file-name
1269 (make-auto-save-file-name))))
1270 (if (interactive-p)
1271 (message "Auto-save %s (in this buffer)"
1272 (if buffer-auto-save-file-name "on" "off")))
1273 buffer-auto-save-file-name)
1274
1275(defun rename-auto-save-file ()
1276 "Adjust current buffer's auto save file name for current conditions.
1277Also rename any existing auto save file, if it was made in this session."
1278 (let ((osave buffer-auto-save-file-name))
1279 (setq buffer-auto-save-file-name
1280 (make-auto-save-file-name))
1281 (if (and osave buffer-auto-save-file-name
1282 (not (string= buffer-auto-save-file-name buffer-file-name))
1283 (not (string= buffer-auto-save-file-name osave))
1284 (file-exists-p osave)
1285 (recent-auto-save-p))
1286 (rename-file osave buffer-auto-save-file-name t))))
1287
1288(defun make-auto-save-file-name ()
1289 "Return file name to use for auto-saves of current buffer.
1290Does not consider `auto-save-visited-file-name' as that variable is checked
1291before calling this function. You can redefine this for customization.
1292See also `auto-save-file-name-p'."
1293 (if buffer-file-name
1294 (concat (file-name-directory buffer-file-name)
1295 "#"
1296 (file-name-nondirectory buffer-file-name)
1297 "#")
1298 ;; For non-file bfr, use bfr name and Emacs pid.
1299 (expand-file-name (format "#%s#%s#" (buffer-name) (make-temp-name "")))))
1300
1301(defun auto-save-file-name-p (filename)
1302 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
1303FILENAME should lack slashes. You can redefine this for customization."
1304 (string-match "^#.*#$" filename))
1305\f
1306(defconst list-directory-brief-switches
1307 (if (eq system-type 'vax-vms) "" "-CF")
1308 "*Switches for list-directory to pass to `ls' for brief listing,")
1309
1310(defconst list-directory-verbose-switches
1311 (if (eq system-type 'vax-vms)
1312 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
1313 "-l")
1314 "*Switches for list-directory to pass to `ls' for verbose listing,")
1315
1316(defun list-directory (dirname &optional verbose)
1317 "Display a list of files in or matching DIRNAME, a la `ls'.
1318DIRNAME is globbed by the shell if necessary.
1319Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
1320Actions controlled by variables `list-directory-brief-switches'
1321and `list-directory-verbose-switches'."
1322 (interactive (let ((pfx current-prefix-arg))
1323 (list (read-file-name (if pfx "List directory (verbose): "
1324 "List directory (brief): ")
1325 nil default-directory nil)
1326 pfx)))
1327 (let ((switches (if verbose list-directory-verbose-switches
1328 list-directory-brief-switches)))
1329 (or dirname (setq dirname default-directory))
1330 (setq dirname (expand-file-name dirname))
1331 (with-output-to-temp-buffer "*Directory*"
1332 (buffer-disable-undo standard-output)
1333 (princ "Directory ")
1334 (princ dirname)
1335 (terpri)
1336 (if (eq system-type 'vax-vms)
1337 (vms-read-directory dirname switches standard-output)
1338 (if (file-directory-p dirname)
1339 (save-excursion
1340 (set-buffer "*Directory*")
1341 (call-process "ls" nil standard-output nil switches
1342 (setq default-directory
1343 (file-name-as-directory dirname))))
1344 (let ((default-directory (file-name-directory dirname)))
1345 (if (file-exists-p default-directory)
1346 (call-process shell-file-name nil standard-output nil
1347 "-c" (concat "exec ls "
1348 switches " "
1349 (file-name-nondirectory dirname)))
1350 (princ "No such directory: ")
1351 (princ dirname)
1352 (terpri))))))))
1353
1354(defun save-buffers-kill-emacs (&optional arg)
1355 "Offer to save each buffer, then kill this Emacs process.
1356With prefix arg, silently save all file-visiting buffers, then kill."
1357 (interactive "P")
1358 (save-some-buffers arg t)
1359 (and (or (not (memq t (mapcar (function
1360 (lambda (buf) (and (buffer-file-name buf)
1361 (buffer-modified-p buf))))
1362 (buffer-list))))
1363 (yes-or-no-p "Modified buffers exist; exit anyway? "))
1364 (or (not (fboundp 'process-list))
1365 ;; process-list is not defined on VMS.
1366 (let ((processes (process-list))
1367 active)
1368 (while processes
528415e7 1369 (and (memq (process-status (car processes)) '(run stop open))
b4da00e9
RM
1370 (let ((val (process-kill-without-query (car processes))))
1371 (process-kill-without-query (car processes) val)
1372 val)
1373 (setq active t))
1374 (setq processes (cdr processes)))
1375 (or (not active)
1376 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
1377 (kill-emacs)))
1378\f
1379(define-key ctl-x-map "\C-f" 'find-file)
1380(define-key ctl-x-map "\C-q" 'toggle-read-only)
1381(define-key ctl-x-map "\C-r" 'find-file-read-only)
1382(define-key ctl-x-map "\C-v" 'find-alternate-file)
1383(define-key ctl-x-map "\C-s" 'save-buffer)
1384(define-key ctl-x-map "s" 'save-some-buffers)
1385(define-key ctl-x-map "\C-w" 'write-file)
1386(define-key ctl-x-map "i" 'insert-file)
1387(define-key esc-map "~" 'not-modified)
1388(define-key ctl-x-map "\C-d" 'list-directory)
1389(define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
1390
1391(define-key ctl-x-4-map "f" 'find-file-other-window)
1392(define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
1393(define-key ctl-x-4-map "\C-f" 'find-file-other-window)
1394(define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
35aaf00c 1395(define-key ctl-x-4-map "o" 'display-buffer)
5bbbceb1 1396
87ef29fd
JB
1397(define-key ctl-x-5-map "b" 'switch-to-buffer-other-screen)
1398(define-key ctl-x-5-map "f" 'find-file-other-screen)
1399(define-key ctl-x-5-map "\C-f" 'find-file-other-screen)
1400(define-key ctl-x-5-map "r" 'find-file-read-only-other-screen)
c0274f38
ER
1401
1402;;; files.el ends here