1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1992 Free Software Foundation, Inc.
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to
21 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25 ;; Defines most of Emacs's file- and directory-handling functions,
26 ;; including basic file visiting, backup generation, link handling,
27 ;; ITS-id version control, load- and write-hook handling, and the like.
31 (defconst delete-auto-save-files t
32 "*Non-nil means delete a buffer's auto-save file when the buffer is saved.")
34 (defconst directory-abbrev-alist
36 "*Alist of abbreviations for file directories.
37 A list of elements of the form (FROM . TO), each meaning to replace
38 FROM with TO when it appears in a directory name. This replacement is
39 done when setting up the default directory of a newly visited file.
40 *Every* FROM string should start with `^'.
42 Use this feature when you have directories which you normally refer to
43 via absolute symbolic links. Make TO the name of the link, and FROM
44 the name it is linked to.")
46 ;;; Turn off backup files on VMS since it has version numbers.
47 (defconst make-backup-files
(not (eq system-type
'vax-vms
))
48 "*Create a backup of each file when it is saved for the first time.
49 This can be done by renaming the file or by copying.
51 Renaming means that Emacs renames the existing file so that it is a
52 backup file, then writes the buffer into a new file. Any other names
53 that the old file had will now refer to the backup file. The new file
54 is owned by you and its group is defaulted.
56 Copying means that Emacs copies the existing file into the backup
57 file, then writes the buffer on top of the existing file. Any other
58 names that the old file had will now refer to the new (edited) file.
59 The file's owner and group are unchanged.
61 The choice of renaming or copying is controlled by the variables
62 `backup-by-copying', `backup-by-copying-when-linked' and
63 `backup-by-copying-when-mismatch'.")
65 ;; Do this so that local variables based on the file name
66 ;; are not overridden by the major mode.
67 (defvar backup-inhibited nil
68 "Non-nil means don't make a backup file for this buffer.")
69 (put 'backup-inhibited
'permanent-local t
)
71 (defconst backup-by-copying nil
72 "*Non-nil means always use copying to create backup files.
73 See documentation of variable `make-backup-files'.")
75 (defconst backup-by-copying-when-linked nil
76 "*Non-nil means use copying to create backups for files with multiple names.
77 This causes the alternate names to refer to the latest version as edited.
78 This variable is relevant only if `backup-by-copying' is nil.")
80 (defconst backup-by-copying-when-mismatch nil
81 "*Non-nil means create backups by copying if this preserves owner or group.
82 Renaming may still be used (subject to control of other variables)
83 when it would not result in changing the owner or group of the file;
84 that is, for files which are owned by you and whose group matches
85 the default for a new file created there by you.
86 This variable is relevant only if `backup-by-copying' is nil.")
88 (defvar backup-enable-predicate
90 (or (< (length name
) 5)
91 (not (string-equal "/tmp/" (substring name
0 5)))))
92 "Predicate that looks at a file name and decides whether to make backups.
93 Called with an absolute file name as argument, it returns t to enable backup.")
95 (defconst buffer-offer-save nil
96 "*Non-nil in a buffer means offer to save the buffer on exit
97 even if the buffer is not visiting a file.
98 Automatically local in all buffers.")
99 (make-variable-buffer-local 'buffer-offer-save
)
101 (defconst find-file-existing-other-name nil
102 "*Non-nil means find a file under alternative names, in existing buffers.
103 This means if any existing buffer is visiting the file you want
104 under another name, you get the existing buffer instead of a new buffer.")
106 (defconst find-file-visit-truename nil
107 "*Non-nil means visit a file under its truename.
108 The truename of a file is found by chasing all links
109 both at the file level and at the levels of the containing directories.")
111 (defvar buffer-file-truename nil
112 "The truename of the file visited in the current buffer.
113 This variable is automatically local in all buffers, when non-nil.")
114 (make-variable-buffer-local 'buffer-file-truename
)
115 (put 'buffer-file-truename
'permanent-local t
)
117 (defvar buffer-file-number nil
118 "The device number and file number of the file visited in the current buffer.
119 The value is a list of the form (FILENUM DEVNUM).
120 This pair of numbers uniquely identifies the file.
121 If the buffer is visiting a new file, the value is nil.")
122 (make-variable-buffer-local 'buffer-file-number
)
123 (put 'buffer-file-number
'permanent-local t
)
125 (defconst file-precious-flag nil
126 "*Non-nil means protect against I/O errors while saving files.
127 Some modes set this non-nil in particular buffers.")
129 (defvar version-control nil
130 "*Control use of version numbers for backup files.
131 t means make numeric backup versions unconditionally.
132 nil means make them for files that have some already.
133 never means do not make them.")
135 (defvar dired-kept-versions
2
136 "*When cleaning directory, number of versions to keep.")
138 (defvar trim-versions-without-asking nil
139 "*If t, deletes excess backup versions silently.
140 If nil, asks confirmation. Any other value prevents any trimming.")
142 (defvar kept-old-versions
2
143 "*Number of oldest versions to keep when a new numbered backup is made.")
145 (defvar kept-new-versions
2
146 "*Number of newest versions to keep when a new numbered backup is made.
147 Includes the new backup. Must be > 0")
149 (defconst require-final-newline nil
150 "*Value of t says silently ensure a file ends in a newline when it is saved.
151 Non-nil but not t says ask user whether to add a newline when there isn't one.
152 nil means don't add newlines.")
154 (defconst auto-save-default t
155 "*Non-nil says by default do auto-saving of every file-visiting buffer.")
157 (defconst auto-save-visited-file-name nil
158 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
159 Normally auto-save files are written under other names.")
161 (defconst save-abbrevs nil
162 "*Non-nil means save word abbrevs too when files are saved.
163 Loading an abbrev file sets this to t.")
165 (defconst find-file-run-dired t
166 "*Non-nil says run dired if find-file is given the name of a directory.")
168 ;;;It is not useful to make this a local variable.
169 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
170 (defvar find-file-not-found-hooks nil
171 "List of functions to be called for `find-file' on nonexistent file.
172 These functions are called as soon as the error is detected.
173 `buffer-file-name' is already set up.
174 The functions are called in the order given until one of them returns non-nil.")
176 ;;;It is not useful to make this a local variable.
177 ;;;(put 'find-file-hooks 'permanent-local t)
178 (defvar find-file-hooks nil
179 "List of functions to be called after a buffer is loaded from a file.
180 The buffer's local variables (if any) will have been processed before the
181 functions are called.")
183 (put 'write-file-hooks
'permanent-local t
)
184 (defvar write-file-hooks nil
185 "List of functions to be called before writing out a buffer to a file.
186 If one of them returns non-nil, the file is considered already written
187 and the rest are not called.
188 These hooks are considered to pertain to the visited file.
189 So this list is cleared if you change the visited file name.
190 See also `write-contents-hooks'.")
192 (defvar write-contents-hooks nil
193 "List of functions to be called before writing out a buffer to a file.
194 If one of them returns non-nil, the file is considered already written
195 and the rest are not called.
196 These hooks are considered to pertain to the buffer's contents,
197 not to the particular visited file; thus, `set-visited-file-name' does
198 not clear this variable, but changing the major mode does clear it.
199 See also `write-file-hooks'.")
201 (defconst enable-local-variables t
202 "*Control use of local-variables lists in files you visit.
203 The value can be t, nil or something else.
204 A value of t means local-variables lists are obeyed;
205 nil means they are ignored; anything else means query.
207 The command \\[normal-mode] always obeys local-variables lists
208 and ignores this variable.")
210 (defconst enable-local-eval
'maybe
211 "*Control processing of the \"variable\" `eval' in a file's local variables.
212 The value can be t, nil or something else.
213 A value of t means obey `eval' variables;
214 nil means ignore them; anything else means query.
216 The command \\[normal-mode] always obeys local-variables lists
217 and ignores this variable.")
219 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
220 (or (fboundp 'lock-buffer
)
221 (fset 'lock-buffer
'ignore
))
222 (or (fboundp 'unlock-buffer
)
223 (fset 'unlock-buffer
'ignore
))
226 "Show the current default directory."
228 (message "Directory %s" default-directory
))
231 "Make DIR become the current buffer's default directory."
232 (interactive "DChange default directory: ")
233 (setq dir
(expand-file-name dir
))
234 (if (not (eq system-type
'vax-vms
))
235 (setq dir
(file-name-as-directory dir
)))
236 (if (not (file-directory-p dir
))
237 (error "%s is not a directory" dir
)
238 (if (file-executable-p dir
)
239 (setq default-directory dir
)
240 (error "Cannot cd to %s: Permission denied" dir
)))
241 ;; We used to call pwd at this point. That's not terribly helpful
242 ;; when we're invoking cd interactively, and the new cmushell-based
243 ;; shell has its own (better) facilities for this.
246 (defun load-file (file)
247 "Load the Lisp file named FILE."
248 (interactive "fLoad file: ")
249 (load (expand-file-name file
) nil nil t
))
251 (defun load-library (library)
252 "Load the library named LIBRARY.
253 This is an interface to the function `load'."
254 (interactive "sLoad library: ")
257 ;; OTHER is the other file to be compared.
258 (defun file-local-copy (file)
259 "Copy the file FILE into a temporary file on this machine.
260 Returns the name of the local copy, or nil, if FILE is directly
262 (let ((handler (find-file-name-handler file
)))
264 (funcall handler
'file-local-copy file
)
267 (defun file-truename (filename)
268 "Return the truename of FILENAME, which should be absolute.
269 The truename of a file name is found by chasing symbolic links
270 both at the level of the file and at the level of the directories
271 containing it, until no links are left at any level."
272 (if (string= filename
"~")
273 (setq filename
(expand-file-name filename
)))
274 (let ((handler (find-file-name-handler filename
)))
275 ;; For file name that has a special handler, call handler.
276 ;; This is so that ange-ftp can save time by doing a no-op.
278 (funcall handler
'file-truename filename
)
279 (let ((dir (file-name-directory filename
))
281 ;; Get the truename of the directory.
282 (setq dirfile
(directory-file-name dir
))
283 ;; If these are equal, we have the (or a) root directory.
284 (or (string= dir dirfile
)
285 (setq dir
(file-name-as-directory (file-truename dirfile
))))
286 ;; Put it back on the file name.
287 (setq filename
(concat dir
(file-name-nondirectory filename
)))
288 ;; Is the file name the name of a link?
289 (setq target
(file-symlink-p filename
))
291 ;; Yes => chase that link, then start all over
292 ;; since the link may point to a directory name that uses links.
293 (file-truename (expand-file-name target dir
))
298 (defun switch-to-buffer-other-window (buffer)
299 "Select buffer BUFFER in another window."
300 (interactive "BSwitch to buffer in other window: ")
301 (let ((pop-up-windows t
))
302 (pop-to-buffer buffer t
)))
304 (defun switch-to-buffer-other-frame (buffer)
305 "Switch to buffer BUFFER in another frame."
306 (interactive "BSwitch to buffer in other frame: ")
307 (let ((pop-up-frames t
))
308 (pop-to-buffer buffer t
)))
310 (defun find-file (filename)
312 Switch to a buffer visiting file FILENAME,
313 creating one if none already exists."
314 (interactive "FFind file: ")
315 (switch-to-buffer (find-file-noselect filename
)))
317 (defun find-file-other-window (filename)
318 "Edit file FILENAME, in another window.
319 May create a new window, or reuse an existing one.
320 See the function `display-buffer'."
321 (interactive "FFind file in other window: ")
322 (switch-to-buffer-other-window (find-file-noselect filename
)))
324 (defun find-file-other-frame (filename)
325 "Edit file FILENAME, in another frame.
326 May create a new frame, or reuse an existing one.
327 See the function `display-buffer'."
328 (interactive "FFind file in other frame: ")
329 (switch-to-buffer-other-frame (find-file-noselect filename
)))
331 (defun find-file-read-only (filename)
332 "Edit file FILENAME but don't allow changes.
333 Like \\[find-file] but marks buffer as read-only.
334 Use \\[toggle-read-only] to permit editing."
335 (interactive "fFind file read-only: ")
337 (setq buffer-read-only t
))
339 (defun find-file-read-only-other-window (filename)
340 "Edit file FILENAME in another window but don't allow changes.
341 Like \\[find-file-other-window] but marks buffer as read-only.
342 Use \\[toggle-read-only] to permit editing."
343 (interactive "fFind file read-only other window: ")
345 (setq buffer-read-only t
))
347 (defun find-file-read-only-other-frame (filename)
348 "Edit file FILENAME in another frame but don't allow changes.
349 Like \\[find-file-other-frame] but marks buffer as read-only.
350 Use \\[toggle-read-only] to permit editing."
351 (interactive "fFind file read-only other frame: ")
352 (find-file-other-frame filename
)
353 (setq buffer-read-only t
))
355 (defun find-alternate-file (filename)
356 "Find file FILENAME, select its buffer, kill previous buffer.
357 If the current buffer now contains an empty file that you just visited
358 \(presumably by mistake), use this command to visit the file you really want."
360 (let ((file buffer-file-name
)
364 (setq file-name
(file-name-nondirectory file
)
365 file-dir
(file-name-directory file
)))
366 (list (read-file-name
367 "Find alternate file: " file-dir nil nil file-name
))))
368 (and (buffer-modified-p)
369 ;; (not buffer-read-only)
370 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
373 (let ((obuf (current-buffer))
374 (ofile buffer-file-name
)
375 (oname (buffer-name)))
376 (rename-buffer " **lose**")
377 (setq buffer-file-name nil
)
381 (find-file filename
))
382 (cond ((eq obuf
(current-buffer))
383 (setq buffer-file-name ofile
)
385 (rename-buffer oname
))))
386 (or (eq (current-buffer) obuf
)
387 (kill-buffer obuf
))))
389 (defun create-file-buffer (filename)
390 "Create a suitably named buffer for visiting FILENAME, and return it.
391 FILENAME (sans directory) is used unchanged if that name is free;
392 otherwise a string <2> or <3> or ... is appended to get an unused name."
393 (let ((lastname (file-name-nondirectory filename
)))
394 (if (string= lastname
"")
395 (setq lastname filename
))
396 (generate-new-buffer lastname
)))
398 (defun generate-new-buffer (name)
399 "Create and return a buffer with a name based on NAME.
400 Choose the buffer's name using `generate-new-buffer-name'."
401 (get-buffer-create (generate-new-buffer-name name
)))
403 (defconst automount-dir-prefix
"^/tmp_mnt/"
404 "Regexp to match the automounter prefix in a directory name.")
406 (defvar abbreviated-home-dir nil
407 "The the user's homedir abbreviated according to `directory-abbrev-list'.")
409 (defun abbreviate-file-name (filename)
410 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
411 This also substitutes \"~\" for the user's home directory.
412 Type \\[describe-variable] directory-abbrev-alist RET for more information."
413 ;; Get rid of the prefixes added by the automounter.
414 (if (and (string-match automount-dir-prefix filename
)
415 (file-exists-p (file-name-directory
416 (substring filename
(1- (match-end 0))))))
417 (setq filename
(substring filename
(1- (match-end 0)))))
418 (let ((tail directory-abbrev-alist
))
419 ;; If any elt of directory-abbrev-alist matches this name,
420 ;; abbreviate accordingly.
422 (if (string-match (car (car tail
)) filename
)
424 (concat (cdr (car tail
)) (substring filename
(match-end 0)))))
425 (setq tail
(cdr tail
)))
426 ;; Compute and save the abbreviated homedir name.
427 ;; We defer computing this until the first time it's needed, to
428 ;; give time for directory-abbrev-alist to be set properly.
429 (or abbreviated-home-dir
430 (setq abbreviated-home-dir
431 (let ((abbreviated-home-dir "$foo"))
432 (concat "^" (abbreviate-file-name (expand-file-name "~"))))))
433 ;; If FILENAME starts with the abbreviated homedir,
434 ;; make it start with `~' instead.
435 (if (string-match abbreviated-home-dir filename
)
437 (concat "~" (substring filename
(match-end 0)))))
440 (defun find-file-noselect (filename &optional nowarn
)
441 "Read file FILENAME into a buffer and return the buffer.
442 If a buffer exists visiting FILENAME, return that one, but
443 verify that the file has not changed since visited or saved.
444 The buffer is not selected, just returned to the caller."
446 (abbreviate-file-name
447 (expand-file-name filename
)))
448 (if (file-directory-p filename
)
449 (if find-file-run-dired
450 (dired-noselect filename
)
451 (error "%s is a directory." filename
))
452 (let* ((buf (get-file-buffer filename
))
453 (truename (abbreviate-file-name (file-truename filename
)))
454 (number (nthcdr 10 (file-attributes truename
)))
455 ;; Find any buffer for a file which has same truename.
459 (list (buffer-list)))
460 (while (and (not found
) list
)
462 (set-buffer (car list
))
463 (if (string= buffer-file-truename truename
)
464 (setq found
(car list
))))
465 (setq list
(cdr list
)))
471 (list (buffer-list)))
472 (while (and (not found
) list
)
474 (set-buffer (car list
))
475 (if (equal buffer-file-number number
)
476 (setq found
(car list
))))
477 (setq list
(cdr list
)))
480 ;; Let user know if there is a buffer with the same truename.
481 (if (and (not buf
) same-truename
(not nowarn
))
482 (message "%s and %s are the same file (%s)"
483 filename
(buffer-file-name same-truename
)
485 (if (and (not buf
) same-number
(not nowarn
))
486 (message "%s and %s are the same file"
487 filename
(buffer-file-name same-number
))))
489 ;; Optionally also find that buffer.
490 (if (or find-file-existing-other-name find-file-visit-truename
)
491 (setq buf
(or same-truename same-number
)))
494 (verify-visited-file-modtime buf
)
495 (cond ((not (file-exists-p filename
))
496 (error "File %s no longer exists!" filename
))
499 (if (buffer-modified-p buf
)
500 "File %s changed on disk. Discard your edits? "
501 "File %s changed on disk. Read the new version? ")
502 (file-name-nondirectory filename
)))
505 (revert-buffer t t
)))))
507 ;;; The truename stuff makes this obsolete.
508 ;;; (let* ((link-name (car (file-attributes filename)))
509 ;;; (linked-buf (and (stringp link-name)
510 ;;; (get-file-buffer link-name))))
511 ;;; (if (bufferp linked-buf)
512 ;;; (message "Symbolic link to file in buffer %s"
513 ;;; (buffer-name linked-buf))))
514 (setq buf
(create-file-buffer filename
))
518 (insert-file-contents filename t
)
521 ;; Run find-file-not-found-hooks until one returns non-nil.
522 (let ((hooks find-file-not-found-hooks
))
524 (not (funcall (car hooks
))))
525 (setq hooks
(cdr hooks
))))))
526 ;; Find the file's truename, and maybe use that as visited name.
527 (setq buffer-file-truename
(abbreviate-file-name truename
))
528 (setq buffer-file-number number
)
529 (if find-file-visit-truename
(setq filename buffer-file-truename
))
530 ;; Set buffer's default directory to that of the file.
531 (setq default-directory
(file-name-directory filename
))
532 ;; Turn off backup files for certain file names. Since
533 ;; this is a permanent local, the major mode won't eliminate it.
534 (and (not (funcall backup-enable-predicate buffer-file-name
))
536 (make-local-variable 'backup-inhibited
)
537 (setq backup-inhibited t
)))
538 (after-find-file error
(not nowarn
))))
541 (defun after-find-file (&optional error warn noauto
)
542 "Called after finding a file and by the default revert function.
543 Sets buffer mode, parses local variables.
544 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
545 error in reading the file. WARN non-nil means warn if there
546 exists an auto-save file more recent than the visited file.
547 NOAUTO means don't mess with auto-save mode.
548 Finishes by calling the functions in `find-file-hooks'."
549 (setq buffer-read-only
(not (file-writable-p buffer-file-name
)))
554 (cond ((and error
(file-attributes buffer-file-name
))
555 (setq buffer-read-only t
)
556 "File exists, but is read-protected.")
557 ((not buffer-read-only
)
559 (file-newer-than-file-p (make-auto-save-file-name)
561 "Auto save file is newer; consider M-x recover-file"
563 (if error
"(New file)" nil
)))
566 "Note: file is write protected")
567 ((file-attributes (directory-file-name default-directory
))
568 "File not found and directory write-protected")
569 ((file-exists-p (file-name-directory buffer-file-name
))
570 (setq buffer-read-only nil
))
572 (setq buffer-read-only nil
)
573 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name
))))
574 "Use M-x make-dir RET RET to create the directory"
575 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
579 (or not-serious
(sit-for 1 nil t
)))))
580 (if (and auto-save-default
(not noauto
))
583 (mapcar 'funcall find-file-hooks
))
585 (defun normal-mode (&optional find-file
)
586 "Choose the major mode for this buffer automatically.
587 Also sets up any specified local variables of the file.
588 Uses the visited file name, the -*- line, and the local variables spec.
590 This function is called automatically from `find-file'. In that case,
591 we may set up specified local variables depending on the value of
592 `enable-local-variables': if it is t, we do; if it is nil, we don't;
593 otherwise, we query. `enable-local-variables' is ignored if you
594 run `normal-mode' explicitly."
596 (or find-file
(funcall (or default-major-mode
'fundamental-mode
)))
599 (error (message "File mode specification error: %s"
600 (prin1-to-string err
))))
602 (let ((enable-local-variables (or (not find-file
)
603 enable-local-variables
)))
604 (hack-local-variables))
605 (error (message "File local-variables error: %s"
606 (prin1-to-string err
)))))
608 (defvar auto-mode-alist
(mapcar 'purecopy
609 '(("\\.text\\'" . text-mode
)
612 ("\\.tex\\'" . TeX-mode
)
613 ("\\.ltx\\'" . LaTeX-mode
)
614 ("\\.el\\'" . emacs-lisp-mode
)
615 ("\\.mm\\'" . nroff-mode
)
616 ("\\.me\\'" . nroff-mode
)
617 ("\\.scm\\'" . scheme-mode
)
618 ("\\.l\\'" . lisp-mode
)
619 ("\\.lisp\\'" . lisp-mode
)
620 ("\\.f\\'" . fortran-mode
)
621 ("\\.for\\'" . fortran-mode
)
622 ("\\.mss\\'" . scribe-mode
)
623 ("\\.pl\\'" . prolog-mode
)
624 ("\\.cc\\'" . c
++-mode
)
625 ("\\.C\\'" . c
++-mode
)
626 ;;; Less common extensions come here
627 ;;; so more common ones above are found faster.
628 ("\\.s\\'" . asm-mode
)
629 ("ChangeLog\\'" . change-log-mode
)
630 ("ChangeLog.[0-9]+\\'" . change-log-mode
)
631 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode
)
632 ;; The following should come after the ChangeLog pattern
633 ;; for the sake of ChangeLog.1, etc.
634 ("\\.[12345678]\\'" . nroff-mode
)
635 ("\\.TeX\\'" . TeX-mode
)
636 ("\\.sty\\'" . LaTeX-mode
)
637 ("\\.bbl\\'" . LaTeX-mode
)
638 ("\\.bib\\'" . bibtex-mode
)
639 ("\\.article\\'" . text-mode
)
640 ("\\.letter\\'" . text-mode
)
641 ("\\.texinfo\\'" . texinfo-mode
)
642 ("\\.texi\\'" . texinfo-mode
)
643 ("\\.lsp\\'" . lisp-mode
)
644 ("\\.awk\\'" . awk-mode
)
645 ("\\.prolog\\'" . prolog-mode
)
646 ;; Mailer puts message to be edited in
647 ;; /tmp/Re.... or Message
648 ("^/tmp/Re" . text-mode
)
649 ("/Message[0-9]*\\'" . text-mode
)
650 ;; some news reader is reported to use this
651 ("^/tmp/fol/" . text-mode
)
653 ("\\.oak\\'" . scheme-mode
)
654 ("\\.scm.[0-9]*\\'" . scheme-mode
)
655 ;; .emacs following a directory delimiter
656 ;; in either Unix or VMS syntax.
657 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode
)
658 ("\\.ml\\'" . lisp-mode
)))
660 Alist of filename patterns vs corresponding major mode functions.
661 Each element looks like (REGEXP . FUNCTION).
662 Visiting a file whose name matches REGEXP causes FUNCTION to be called.")
664 (defun set-auto-mode ()
665 "Select major mode appropriate for current buffer.
666 This checks for a -*- mode tag in the buffer's text, or
667 compares the filename against the entries in auto-mode-alist. It does
668 not check for the \"mode:\" local variable in the Local Variables
669 section of the file; for that, use `hack-local-variables'.
671 If `enable-local-variables' is nil, this function does not check for a
673 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
676 (goto-char (point-min))
677 (skip-chars-forward " \t\n")
678 (if (and enable-local-variables
679 (search-forward "-*-" (save-excursion (end-of-line) (point)) t
)
681 (skip-chars-forward " \t")
683 (search-forward "-*-"
684 (save-excursion (end-of-line) (point))
688 (skip-chars-backward " \t")
691 (if (search-forward ":" end t
)
694 (if (let ((case-fold-search t
))
695 (search-forward "mode:" end t
))
697 (skip-chars-forward " \t")
699 (if (search-forward ";" end t
)
702 (skip-chars-backward " \t")
703 (setq mode
(buffer-substring beg
(point))))))
704 (setq mode
(buffer-substring beg end
)))))
705 (setq mode
(intern (concat (downcase mode
) "-mode")))
706 (let ((alist auto-mode-alist
)
707 (name buffer-file-name
))
708 (let ((case-fold-search (eq system-type
'vax-vms
)))
709 ;; Remove backup-suffixes from file name.
710 (setq name
(file-name-sans-versions name
))
711 ;; Find first matching alist entry.
712 (while (and (not mode
) alist
)
713 (if (string-match (car (car alist
)) name
)
714 (setq mode
(cdr (car alist
))))
715 (setq alist
(cdr alist
)))))))
716 (if mode
(funcall mode
))))
718 (defun hack-local-variables-prop-line ()
719 ;; Set local variables specified in the -*- line.
720 ;; Returns t if mode was set.
722 (goto-char (point-min))
723 (skip-chars-forward " \t\n\r")
725 (end (save-excursion (end-of-line) (point)))
727 ;; Parse the -*- line into the `result' alist.
728 (cond ((not (search-forward "-*-" end t
))
731 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
732 ;; Simple form: "-*- MODENAME -*-".
735 (intern (buffer-substring
739 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
740 ;; (last ";" is optional).
742 (if (search-forward "-*-" end t
)
743 (setq end
(- (point) 3))
744 (error "-*- not terminated before end of line")))
745 (while (< (point) end
)
746 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
747 (error "malformed -*- line"))
748 (goto-char (match-end 0))
749 (let ((key (intern (downcase (buffer-substring
752 (val (save-restriction
753 (narrow-to-region (point) end
)
754 (read (current-buffer)))))
755 (setq result
(cons (cons key val
) result
))
756 (skip-chars-forward " \t;")))
757 (setq result
(nreverse result
))))
761 (while (setq mode
(assq 'mode result
))
762 (setq mode-p t result
(delq mode result
))
763 (funcall (intern (concat (downcase (symbol-name (cdr mode
)))
767 (or (eq enable-local-variables t
)
768 (and enable-local-variables
769 (save-window-excursion
770 (switch-to-buffer (current-buffer))
771 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
772 (file-name-nondirectory buffer-file-name
)))))))
774 (let ((key (car (car result
)))
775 (val (cdr (car result
))))
776 ;; 'mode has already been removed from this list.
777 (hack-one-local-variable key val
))
778 (setq result
(cdr result
))))
781 (defun hack-local-variables ()
782 "Parse and put into effect this buffer's local variables spec."
783 (hack-local-variables-prop-line)
784 ;; Look for "Local variables:" line in last page.
786 (goto-char (point-max))
787 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move
)
788 (if (let ((case-fold-search t
))
789 (and (search-forward "Local Variables:" nil t
)
790 (or (eq enable-local-variables t
)
791 (and enable-local-variables
792 (save-window-excursion
793 (switch-to-buffer (current-buffer))
796 (set-window-start (selected-window) (point)))
797 (y-or-n-p (format "Set local variables as specified at end of %s? "
798 (file-name-nondirectory buffer-file-name
))))))))
800 prefix prefixlen suffix beg
801 (enable-local-eval enable-local-eval
))
802 ;; The prefix is what comes before "local variables:" in its line.
803 ;; The suffix is what comes after "local variables:" in its line.
804 (skip-chars-forward " \t")
806 (setq suffix
(buffer-substring (point)
807 (progn (end-of-line) (point)))))
808 (goto-char (match-beginning 0))
811 (buffer-substring (point)
812 (progn (beginning-of-line) (point)))))
814 (if prefix
(setq prefixlen
(length prefix
)
815 prefix
(regexp-quote prefix
)))
816 (if suffix
(setq suffix
(concat (regexp-quote suffix
) "$")))
818 ;; Look at next local variable spec.
819 (if selective-display
(re-search-forward "[\n\C-m]")
821 ;; Skip the prefix, if any.
823 (if (looking-at prefix
)
824 (forward-char prefixlen
)
825 (error "Local variables entry is missing the prefix")))
826 ;; Find the variable name; strip whitespace.
827 (skip-chars-forward " \t")
829 (skip-chars-forward "^:\n")
830 (if (eolp) (error "Missing colon in local variables entry"))
831 (skip-chars-backward " \t")
832 (let* ((str (buffer-substring beg
(point)))
835 ;; Setting variable named "end" means end of list.
836 (if (string-equal (downcase str
) "end")
838 ;; Otherwise read the variable value.
839 (skip-chars-forward "^:")
841 (setq val
(read (current-buffer)))
842 (skip-chars-backward "\n")
843 (skip-chars-forward " \t")
844 (or (if suffix
(looking-at suffix
) (eolp))
845 (error "Local variables entry is terminated incorrectly"))
846 ;; Set the variable. "Variables" mode and eval are funny.
847 (hack-one-local-variable var val
))))))))
849 (defconst ignored-local-variables
851 "Variables to be ignored in a file's local variable spec.")
853 ;; "Set" one variable in a local variables spec.
854 ;; A few variable names are treated specially.
855 (defun hack-one-local-variable (var val
)
856 (cond ((eq var
'mode
)
857 (funcall (intern (concat (downcase (symbol-name val
))
859 ((memq var ignored-local-variables
)
861 ;; "Setting" eval means either eval it or do nothing.
863 (if (and (not (string= (user-login-name) "root"))
864 (or (eq enable-local-eval t
)
865 (and enable-local-eval
866 (save-window-excursion
867 (switch-to-buffer (current-buffer))
870 (set-window-start (selected-window) (point)))
871 (setq enable-local-eval
872 (y-or-n-p (format "Process `eval' local variable in file %s? "
873 (file-name-nondirectory buffer-file-name
))))))))
874 (save-excursion (eval val
))
875 (message "Ignoring `eval:' in file's local variables")))
876 ;; Ordinary variable, really set it.
877 (t (make-local-variable var
)
881 (defun set-visited-file-name (filename)
882 "Change name of file visited in current buffer to FILENAME.
883 The next time the buffer is saved it will go in the newly specified file.
884 nil or empty string as argument means make buffer not be visiting any file.
885 Remember to delete the initial contents of the minibuffer
886 if you wish to pass an empty string as the argument."
887 (interactive "FSet visited file name: ")
890 (if (string-equal filename
"")
892 (expand-file-name filename
))))
893 (or (equal filename buffer-file-name
)
896 (lock-buffer filename
)
898 (setq buffer-file-name filename
)
899 (if filename
; make buffer name reflect filename.
900 (let ((new-name (file-name-nondirectory buffer-file-name
)))
901 (if (string= new-name
"")
902 (error "Empty file name"))
903 (if (eq system-type
'vax-vms
)
904 (setq new-name
(downcase new-name
)))
905 (setq default-directory
(file-name-directory buffer-file-name
))
906 (rename-buffer new-name t
)))
907 (setq buffer-backed-up nil
)
908 (clear-visited-file-modtime)
911 (setq buffer-file-truename
912 (abbreviate-file-name (file-truename buffer-file-name
)))
913 (if find-file-visit-truename
914 (setq buffer-file-name buffer-file-truename
))
915 (setq buffer-file-number
(nth 10 (file-attributes buffer-file-name
))))
916 (setq buffer-file-truename nil buffer-file-number nil
))
917 ;; write-file-hooks is normally used for things like ftp-find-file
918 ;; that visit things that are not local files as if they were files.
919 ;; Changing to visit an ordinary local file instead should flush the hook.
920 (kill-local-variable 'write-file-hooks
)
921 (kill-local-variable 'revert-buffer-function
)
922 (kill-local-variable 'backup-inhibited
)
923 ;; Turn off backup files for certain file names.
924 ;; Since this is a permanent local, the major mode won't eliminate it.
925 (and (not (funcall backup-enable-predicate buffer-file-name
))
927 (make-local-variable 'backup-inhibited
)
928 (setq backup-inhibited t
)))
929 ;; If auto-save was not already on, turn it on if appropriate.
930 (if (not buffer-auto-save-file-name
)
931 (auto-save-mode (and buffer-file-name auto-save-default
))
932 ;; If auto save is on, start using a new name.
933 ;; We deliberately don't rename or delete the old auto save
934 ;; for the old visited file name. This is because perhaps
935 ;; the user wants to save the new state and then compare with the
936 ;; previous state from the auto save file.
937 (setq buffer-auto-save-file-name
938 (make-auto-save-file-name)))
940 (set-buffer-modified-p t
)))
942 (defun write-file (filename)
943 "Write current buffer into file FILENAME.
944 Makes buffer visit that file, and marks it not modified.
945 If the buffer is already visiting a file, you can specify
946 a directory name as FILENAME, to write a file of the same
947 old name in that directory."
948 ;; (interactive "FWrite file: ")
950 (list (if buffer-file-name
951 (read-file-name "Write file: "
953 (read-file-name "Write file: "
954 (cdr (assq 'default-directory
955 (buffer-local-variables)))
956 nil nil
(buffer-name)))))
957 (or (null filename
) (string-equal filename
"")
959 ;; If arg is just a directory,
960 ;; use same file name, but in that directory.
961 (if (and (file-directory-p filename
) buffer-file-name
)
962 (setq filename
(concat (file-name-as-directory filename
)
963 (file-name-nondirectory buffer-file-name
))))
964 (set-visited-file-name filename
)))
965 (set-buffer-modified-p t
)
968 (defun backup-buffer ()
969 "Make a backup of the disk file visited by the current buffer, if appropriate.
970 This is normally done before saving the buffer the first time.
971 If the value is non-nil, it is the result of `file-modes' on the original
972 file; this means that the caller, after saving the buffer, should change
973 the modes of the new file to agree with the old modes."
974 (if (and make-backup-files
(not backup-inhibited
)
975 (not buffer-backed-up
)
976 (file-exists-p buffer-file-name
)
977 (memq (aref (elt (file-attributes buffer-file-name
) 8) 0)
979 (let ((real-file-name buffer-file-name
)
980 backup-info backupname targets setmodes
)
981 ;; If specified name is a symbolic link, chase it to the target.
982 ;; Thus we make the backups in the directory where the real file is.
983 (while (let ((tem (file-symlink-p real-file-name
)))
986 (expand-file-name tem
987 (file-name-directory real-file-name
))))
989 (setq backup-info
(find-backup-file-name real-file-name
)
990 backupname
(car backup-info
)
991 targets
(cdr backup-info
))
992 ;;; (if (file-directory-p buffer-file-name)
993 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
995 (let ((delete-old-versions
996 ;; If have old versions to maybe delete,
997 ;; ask the user to confirm now, before doing anything.
998 ;; But don't actually delete til later.
1000 (or (eq trim-versions-without-asking t
) (eq trim-versions-without-asking nil
))
1001 (or trim-versions-without-asking
1002 (y-or-n-p (format "Delete excess backup versions of %s? "
1003 real-file-name
))))))
1004 ;; Actually write the back up file.
1006 (if (or file-precious-flag
1007 ; (file-symlink-p buffer-file-name)
1009 (and backup-by-copying-when-linked
1010 (> (file-nlinks real-file-name
) 1))
1011 (and backup-by-copying-when-mismatch
1012 (let ((attr (file-attributes real-file-name
)))
1014 (/= (nth 2 attr
) (user-uid))))))
1016 (copy-file real-file-name backupname t t
)
1018 ;; If copying fails because file BACKUPNAME
1019 ;; is not writable, delete that file and try again.
1020 (if (and (file-exists-p backupname
)
1021 (not (file-writable-p backupname
)))
1022 (delete-file backupname
))
1023 (copy-file real-file-name backupname t t
)))
1024 ;; rename-file should delete old backup.
1025 (rename-file real-file-name backupname t
)
1026 (setq setmodes
(file-modes backupname
)))
1028 ;; If trouble writing the backup, write it in ~.
1029 (setq backupname
(expand-file-name "~/%backup%~"))
1030 (message "Cannot write backup file; backing up in ~/%%backup%%~")
1033 (copy-file real-file-name backupname t t
)
1035 ;; If copying fails because file BACKUPNAME
1036 ;; is not writable, delete that file and try again.
1037 (if (and (file-exists-p backupname
)
1038 (not (file-writable-p backupname
)))
1039 (delete-file backupname
))
1040 (copy-file real-file-name backupname t t
)))))
1041 (setq buffer-backed-up t
)
1042 ;; Now delete the old versions, if desired.
1043 (if delete-old-versions
1046 (delete-file (car targets
))
1048 (setq targets
(cdr targets
))))
1050 (file-error nil
)))))
1052 (defun file-name-sans-versions (name &optional keep-backup-version
)
1053 "Return FILENAME sans backup versions or strings.
1054 This is a separate procedure so your site-init or startup file can
1056 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1057 we do not remove backup version numbers, only true file version numbers."
1058 (let ((handler (find-file-name-handler name
)))
1060 (funcall handler
'file-name-sans-versions name keep-backup-version
)
1062 (if (eq system-type
'vax-vms
)
1063 ;; VMS version number is (a) semicolon, optional
1064 ;; sign, zero or more digits or (b) period, option
1065 ;; sign, zero or more digits, provided this is the
1066 ;; second period encountered outside of the
1067 ;; device/directory part of the file name.
1068 (or (string-match ";[---+]?[0-9]*\\'" name
)
1069 (if (string-match "\\.[^]>:]*\\(\\.[---+]?[0-9]*\\)\\'"
1071 (match-beginning 1))
1073 (if keep-backup-version
1075 (or (string-match "\\.~[0-9]+~\\'" name
)
1076 (string-match "~\\'" name
)
1077 (length name
))))))))
1079 (defun make-backup-file-name (file)
1080 "Create the non-numeric backup file name for FILE.
1081 This is a separate function so you can redefine it for customization."
1084 (defun backup-file-name-p (file)
1085 "Return non-nil if FILE is a backup file name (numeric or not).
1086 This is a separate function so you can redefine it for customization.
1087 You may need to redefine `file-name-sans-versions' as well."
1088 (string-match "~$" file
))
1090 ;; This is used in various files.
1091 ;; The usage of bv-length is not very clean,
1092 ;; but I can't see a good alternative,
1093 ;; so as of now I am leaving it alone.
1094 (defun backup-extract-version (fn)
1095 "Given the name of a numeric backup file, return the backup number.
1096 Uses the free variable `bv-length', whose value should be
1097 the index in the name where the version number begins."
1098 (if (and (string-match "[0-9]+~$" fn bv-length
)
1099 (= (match-beginning 0) bv-length
))
1100 (string-to-int (substring fn bv-length -
1))
1103 ;; I believe there is no need to alter this behavior for VMS;
1104 ;; since backup files are not made on VMS, it should not get called.
1105 (defun find-backup-file-name (fn)
1106 "Find a file name for a backup file, and suggestions for deletions.
1107 Value is a list whose car is the name for the backup file
1108 and whose cdr is a list of old versions to consider deleting now."
1109 (if (eq version-control
'never
)
1110 (list (make-backup-file-name fn
))
1111 (let* ((base-versions (concat (file-name-nondirectory fn
) ".~"))
1112 (bv-length (length base-versions
))
1113 (possibilities (file-name-all-completions
1115 (file-name-directory fn
)))
1116 (versions (sort (mapcar
1117 (function backup-extract-version
)
1120 (high-water-mark (apply 'max
0 versions
))
1123 (> high-water-mark
0)))
1124 (number-to-delete (- (length versions
)
1125 kept-old-versions kept-new-versions -
1)))
1126 (if (not deserve-versions-p
)
1127 (list (make-backup-file-name fn
))
1128 (cons (concat fn
".~" (int-to-string (1+ high-water-mark
)) "~")
1129 (if (> number-to-delete
0)
1130 (mapcar (function (lambda (n)
1131 (concat fn
".~" (int-to-string n
) "~")))
1132 (let ((v (nthcdr kept-old-versions versions
)))
1133 (rplacd (nthcdr (1- number-to-delete
) v
) ())
1136 (defun file-nlinks (filename)
1137 "Return number of names file FILENAME has."
1138 (car (cdr (file-attributes filename
))))
1140 (defun file-relative-name-1 (directory)
1141 (cond ((string= directory
"/")
1143 ((string-match (concat "^" (regexp-quote directory
))
1145 (substring filename
(match-end 0)))
1147 (file-relative-name-1
1148 (file-name-directory (substring directory
0 -
1))))))
1150 (defun file-relative-name (filename &optional directory
)
1151 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1152 (setq filename
(expand-file-name filename
)
1153 directory
(file-name-as-directory (if directory
1154 (expand-file-name directory
)
1155 default-directory
)))
1156 (file-relative-name-1 directory
))
1158 (defun save-buffer (&optional args
)
1159 "Save current buffer in visited file if modified. Versions described below.
1160 By default, makes the previous version into a backup file
1161 if previously requested or if this is the first save.
1162 With 1 or 3 \\[universal-argument]'s, marks this version
1163 to become a backup when the next save is done.
1164 With 2 or 3 \\[universal-argument]'s,
1165 unconditionally makes the previous version into a backup file.
1166 With argument of 0, never makes the previous version into a backup file.
1168 If a file's name is FOO, the names of its numbered backup versions are
1169 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1170 Numeric backups (rather than FOO~) will be made if value of
1171 `version-control' is not the atom `never' and either there are already
1172 numeric versions of the file being backed up, or `version-control' is
1174 We don't want excessive versions piling up, so there are variables
1175 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1176 and `kept-new-versions', which tells how many newest versions to keep.
1177 Defaults are 2 old versions and 2 new.
1178 `dired-kept-versions' controls dired's clean-directory (.) command.
1179 If `trim-versions-without-asking' is nil, system will query user
1180 before trimming versions. Otherwise it does it silently."
1182 (let ((modp (buffer-modified-p))
1183 (large (> (buffer-size) 50000))
1184 (make-backup-files (and make-backup-files
(not (eq args
0)))))
1185 (and modp
(memq args
'(16 64)) (setq buffer-backed-up nil
))
1186 (if (and modp large
) (message "Saving file %s..." (buffer-file-name)))
1188 (and modp
(memq args
'(4 64)) (setq buffer-backed-up nil
))))
1190 (defun delete-auto-save-file-if-necessary (&optional force
)
1191 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1192 Normally delete only if the file was written by this Emacs since
1193 the last real save, but optional arg FORCE non-nil means delete anyway."
1194 (and buffer-auto-save-file-name delete-auto-save-files
1195 (not (string= buffer-file-name buffer-auto-save-file-name
))
1196 (or force
(recent-auto-save-p))
1199 (delete-file buffer-auto-save-file-name
)
1201 (set-buffer-auto-saved))))
1203 (defun basic-save-buffer ()
1204 "Save the current buffer in its visited file, if it has been modified."
1206 (if (buffer-modified-p)
1207 (let ((recent-save (recent-auto-save-p))
1208 setmodes tempsetmodes
)
1209 ;; On VMS, rename file and buffer to get rid of version number.
1210 (if (and (eq system-type
'vax-vms
)
1211 (not (string= buffer-file-name
1212 (file-name-sans-versions buffer-file-name
))))
1213 (let (buffer-new-name)
1214 ;; Strip VMS version number before save.
1215 (setq buffer-file-name
1216 (file-name-sans-versions buffer-file-name
))
1217 ;; Construct a (unique) buffer name to correspond.
1218 (let ((buf (create-file-buffer (downcase buffer-file-name
))))
1219 (setq buffer-new-name
(buffer-name buf
))
1221 (rename-buffer buffer-new-name
)))
1222 ;; If buffer has no file name, ask user for one.
1223 (or buffer-file-name
1225 (setq buffer-file-name
1226 (expand-file-name (read-file-name "File to save in: ") nil
)
1227 default-directory
(file-name-directory buffer-file-name
))
1228 (auto-save-mode auto-save-default
)))
1229 (or (verify-visited-file-modtime (current-buffer))
1230 (not (file-exists-p buffer-file-name
))
1232 (format "%s has changed since visited or saved. Save anyway? "
1233 (file-name-nondirectory buffer-file-name
)))
1234 (error "Save not confirmed"))
1237 (and (> (point-max) 1)
1238 (/= (char-after (1- (point-max))) ?
\n)
1239 (or (eq require-final-newline t
)
1240 (and require-final-newline
1242 (format "Buffer %s does not end in newline. Add one? "
1245 (goto-char (point-max))
1247 (let ((hooks (append write-contents-hooks write-file-hooks
))
1250 (not (setq done
(funcall (car hooks
)))))
1251 (setq hooks
(cdr hooks
)))
1252 ;; If a hook returned t, file is already "written".
1254 (if (not (file-writable-p buffer-file-name
))
1255 (let ((dir (file-name-directory buffer-file-name
)))
1256 (if (not (file-directory-p dir
))
1257 (error "%s is not a directory" dir
)
1258 (if (not (file-exists-p buffer-file-name
))
1259 (error "Directory %s write-protected" dir
)
1261 (format "File %s is write-protected; try to save anyway? "
1262 (file-name-nondirectory
1264 (setq tempsetmodes t
)
1265 (error "Attempt to save to a file which you aren't allowed to write"))))))
1266 (or buffer-backed-up
1267 (setq setmodes
(backup-buffer)))
1268 (if file-precious-flag
1269 ;; If file is precious, write temp name, then rename it.
1270 (let ((dir (file-name-directory buffer-file-name
))
1271 (realname buffer-file-name
)
1272 tempname temp nogood i succeed
)
1275 ;; Find the temporary name to write under.
1277 (setq tempname
(format "%s#tmp#%d" dir i
))
1278 (setq nogood
(file-exists-p tempname
))
1281 (progn (clear-visited-file-modtime)
1282 (write-region (point-min) (point-max)
1283 tempname nil realname
)
1285 ;; If writing the temp file fails,
1286 ;; delete the temp file.
1287 (or succeed
(delete-file tempname
)))
1288 ;; Since we have created an entirely new file
1289 ;; and renamed it, make sure it gets the
1290 ;; right permission bits set.
1291 (setq setmodes
(file-modes buffer-file-name
))
1292 ;; We succeeded in writing the temp file,
1294 (rename-file tempname buffer-file-name t
))
1295 ;; If file not writable, see if we can make it writable
1296 ;; temporarily while we write it.
1297 ;; But no need to do so if we have just backed it up
1298 ;; (setmodes is set) because that says we're superseding.
1299 (cond ((and tempsetmodes
(not setmodes
))
1300 ;; Change the mode back, after writing.
1301 (setq setmodes
(file-modes buffer-file-name
))
1302 (set-file-modes buffer-file-name
511)))
1303 (write-region (point-min) (point-max)
1304 buffer-file-name nil t
)))))
1305 (setq buffer-file-number
(nth 10 (file-attributes buffer-file-name
)))
1308 (set-file-modes buffer-file-name setmodes
)
1310 ;; If the auto-save file was recent before this command,
1312 (delete-auto-save-file-if-necessary recent-save
)
1313 (run-hooks 'after-save-hooks
))
1314 (message "(No changes need to be saved)")))
1316 (defun save-some-buffers (&optional arg exiting
)
1317 "Save some modified file-visiting buffers. Asks user about each one.
1318 Optional argument (the prefix) non-nil means save all with no questions.
1319 Optional second argument EXITING means ask about certain non-file buffers
1320 as well as about file buffers."
1322 (save-window-excursion
1323 (if (zerop (map-y-or-n-p
1326 (and (buffer-modified-p buffer
)
1328 (buffer-file-name buffer
)
1332 (and buffer-offer-save
(> (buffer-size) 0)))))
1335 (if (buffer-file-name buffer
)
1336 (format "Save file %s? "
1337 (buffer-file-name buffer
))
1338 (format "Save buffer %s? "
1339 (buffer-name buffer
)))))))
1345 '("buffer" "buffers" "save")
1346 (list (list ?\C-r
(lambda (buf)
1348 (setq view-exit-action
1350 (exit-recursive-edit)))
1352 ;; Return nil to ask about BUF again.
1354 "display the current buffer"))
1356 (message "(No files need saving)"))))
1358 (defun not-modified (&optional arg
)
1359 "Mark current buffer as unmodified, not needing to be saved.
1360 With prefix arg, mark buffer as modified, so \\[save-buffer] will save."
1362 (message (if arg
"Modification-flag set"
1363 "Modification-flag cleared"))
1364 (set-buffer-modified-p arg
))
1366 (defun toggle-read-only (&optional arg
)
1367 "Change whether this buffer is visiting its file read-only.
1368 With arg, set read-only iff arg is positive."
1370 (setq buffer-read-only
1372 (not buffer-read-only
)
1373 (> (prefix-numeric-value arg
) 0)))
1374 ;; Force mode-line redisplay
1375 (set-buffer-modified-p (buffer-modified-p)))
1377 (defun insert-file (filename)
1378 "Insert contents of file FILENAME into buffer after point.
1379 Set mark after the inserted text.
1381 This function is meant for the user to run interactively.
1382 Don't call it from programs! Use `insert-file-contents' instead.
1383 \(Its calling sequence is different; see its documentation)."
1384 (interactive "fInsert file: ")
1385 (let ((tem (insert-file-contents filename
)))
1386 (push-mark (+ (point) (car (cdr tem
))))))
1388 (defun append-to-file (start end filename
)
1389 "Append the contents of the region to the end of file FILENAME.
1390 When called from a function, expects three arguments,
1391 START, END and FILENAME. START and END are buffer positions
1392 saying what text to write."
1393 (interactive "r\nFAppend to file: ")
1394 (write-region start end filename t
))
1396 (defun file-newest-backup (filename)
1397 "Return most recent backup file for FILENAME or nil if no backups exist."
1398 (let* ((filename (expand-file-name filename
))
1399 (file (file-name-nondirectory filename
))
1400 (dir (file-name-directory filename
))
1401 (comp (file-name-all-completions file dir
))
1404 (setq file
(concat dir
(car comp
))
1406 (if (and (backup-file-name-p file
)
1407 (or (null newest
) (file-newer-than-file-p file newest
)))
1408 (setq newest file
)))
1411 (defun rename-uniquely ()
1412 "Rename current buffer to a similar name not already taken.
1413 This function is useful for creating multiple shell process buffers
1414 or multiple mail buffers, etc."
1416 (let* ((new-buf (generate-new-buffer (buffer-name)))
1417 (name (buffer-name new-buf
)))
1418 (kill-buffer new-buf
)
1419 (rename-buffer name
)
1420 (set-buffer-modified-p (buffer-modified-p)))) ; force mode line update
1422 (defun make-directory (dir &optional parents
)
1423 "Create the directory DIR and any nonexistent parent dirs."
1424 (interactive "FMake directory: \nP")
1425 (let ((handler (find-file-name-handler dir
)))
1427 (funcall handler
'make-directory dir parents
)
1429 (make-directory-internal dir
)
1430 (let ((dir (directory-file-name (expand-file-name dir
)))
1432 (while (not (file-exists-p dir
))
1433 (setq create-list
(cons dir create-list
)
1434 dir
(directory-file-name (file-name-directory dir
))))
1436 (make-directory-internal (car create-list
))
1437 (setq create-list
(cdr create-list
))))))))
1439 (put 'revert-buffer-function
'permanent-local t
)
1440 (defvar revert-buffer-function nil
1441 "Function to use to revert this buffer, or nil to do the default.")
1443 (put 'revert-buffer-insert-file-contents-function
'permanent-local t
)
1444 (defvar revert-buffer-insert-file-contents-function nil
1445 "Function to use to insert contents when reverting this buffer.
1446 Gets two args, first the nominal file name to use,
1447 and second, t if reading the auto-save file.")
1449 (defun revert-buffer (&optional ignore-auto noconfirm
)
1450 "Replace the buffer text with the text of the visited file on disk.
1451 This undoes all changes since the file was visited or saved.
1452 With a prefix argument, offer to revert from latest auto-save file, if
1453 that is more recent than the visited file.
1455 When called from lisp, the first argument is IGNORE-AUTO; only offer
1456 to revert from the auto-save file when this is nil. Note that the
1457 sense of this argument is the reverse of the prefix argument, for the
1458 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
1461 Optional second argument NOCONFIRM means don't ask for confirmation at
1464 If the value of `revert-buffer-function' is non-nil, it is called to
1466 ;; I admit it's odd to reverse the sense of the prefix argument, but
1467 ;; there is a lot of code out there which assumes that the first
1468 ;; argument should be t to avoid consulting the auto-save file, and
1469 ;; there's no straightforward way to encourage authors to notice a
1470 ;; reversal of the argument sense. So I'm just changing the user
1471 ;; interface, but leaving the programmatic interface the same.
1472 (interactive (list (not prefix-arg
)))
1473 (if revert-buffer-function
1474 (funcall revert-buffer-function ignore-auto noconfirm
)
1475 (let* ((opoint (point))
1476 (auto-save-p (and (not ignore-auto
)
1477 (recent-auto-save-p)
1478 buffer-auto-save-file-name
1479 (file-readable-p buffer-auto-save-file-name
)
1481 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
1482 (file-name (if auto-save-p
1483 buffer-auto-save-file-name
1485 (cond ((null file-name
)
1486 (error "Buffer does not seem to be associated with any file"))
1488 (yes-or-no-p (format "Revert buffer from file %s? "
1490 ;; If file was backed up but has changed since,
1491 ;; we shd make another backup.
1492 (and (not auto-save-p
)
1493 (not (verify-visited-file-modtime (current-buffer)))
1494 (setq buffer-backed-up nil
))
1495 ;; Get rid of all undo records for this buffer.
1496 (or (eq buffer-undo-list t
)
1497 (setq buffer-undo-list nil
))
1498 (let ((buffer-read-only nil
)
1499 ;; Don't make undo records for the reversion.
1500 (buffer-undo-list t
))
1501 (if revert-buffer-insert-file-contents-function
1502 (funcall revert-buffer-insert-file-contents-function
1503 file-name auto-save-p
)
1504 (if (not (file-exists-p file-name
))
1505 (error "File %s no longer exists!" file-name
))
1506 ;; Bind buffer-file-name to nil
1507 ;; so that we don't try to lock the file.
1508 (let ((buffer-file-name nil
))
1512 (insert-file-contents file-name
(not auto-save-p
))))
1513 (goto-char (min opoint
(point-max)))
1514 (after-find-file nil nil t
)
1517 (defun recover-file (file)
1518 "Visit file FILE, but get contents from its last auto-save file."
1520 (let ((prompt-file buffer-file-name
)
1524 (setq file-name
(file-name-nondirectory prompt-file
)
1525 file-dir
(file-name-directory prompt-file
)))
1526 (list (read-file-name "Recover file: "
1527 file-dir nil nil file-name
))))
1528 (setq file
(expand-file-name file
))
1529 (if (auto-save-file-name-p file
) (error "%s is an auto-save file" file
))
1530 (let ((file-name (let ((buffer-file-name file
))
1531 (make-auto-save-file-name))))
1532 (cond ((not (file-newer-than-file-p file-name file
))
1533 (error "Auto-save file %s not current" file-name
))
1534 ((save-window-excursion
1535 (if (not (eq system-type
'vax-vms
))
1536 (with-output-to-temp-buffer "*Directory*"
1537 (buffer-disable-undo standard-output
)
1538 (call-process "ls" nil standard-output nil
1539 (if (file-symlink-p file
) "-lL" "-l")
1541 (yes-or-no-p (format "Recover auto save file %s? " file-name
)))
1542 (switch-to-buffer (find-file-noselect file t
))
1543 (let ((buffer-read-only nil
))
1545 (insert-file-contents file-name nil
))
1546 (after-find-file nil nil t
))
1547 (t (error "Recover-file cancelled.")))))
1549 (defun kill-some-buffers ()
1550 "For each buffer, ask whether to kill it."
1552 (let ((list (buffer-list)))
1554 (let* ((buffer (car list
))
1555 (name (buffer-name buffer
)))
1556 (and (not (string-equal name
""))
1557 (/= (aref name
0) ?
)
1559 (format "Buffer %s %s. Kill? "
1561 (if (buffer-modified-p buffer
)
1562 "HAS BEEN EDITED" "is unmodified")))
1563 (kill-buffer buffer
)))
1564 (setq list
(cdr list
)))))
1566 (defun auto-save-mode (arg)
1567 "Toggle auto-saving of contents of current buffer.
1568 With prefix argument ARG, turn auto-saving on if positive, else off."
1570 (setq buffer-auto-save-file-name
1572 (not buffer-auto-save-file-name
)
1573 (or (eq arg t
) (listp arg
) (and (integerp arg
) (> arg
0))))
1574 (if (and buffer-file-name auto-save-visited-file-name
1575 (not buffer-read-only
))
1577 (make-auto-save-file-name))))
1579 (message "Auto-save %s (in this buffer)"
1580 (if buffer-auto-save-file-name
"on" "off")))
1581 buffer-auto-save-file-name
)
1583 (defun rename-auto-save-file ()
1584 "Adjust current buffer's auto save file name for current conditions.
1585 Also rename any existing auto save file, if it was made in this session."
1586 (let ((osave buffer-auto-save-file-name
))
1587 (setq buffer-auto-save-file-name
1588 (make-auto-save-file-name))
1589 (if (and osave buffer-auto-save-file-name
1590 (not (string= buffer-auto-save-file-name buffer-file-name
))
1591 (not (string= buffer-auto-save-file-name osave
))
1592 (file-exists-p osave
)
1593 (recent-auto-save-p))
1594 (rename-file osave buffer-auto-save-file-name t
))))
1596 (defun make-auto-save-file-name ()
1597 "Return file name to use for auto-saves of current buffer.
1598 Does not consider `auto-save-visited-file-name' as that variable is checked
1599 before calling this function. You can redefine this for customization.
1600 See also `auto-save-file-name-p'."
1601 (if buffer-file-name
1602 (concat (file-name-directory buffer-file-name
)
1604 (file-name-nondirectory buffer-file-name
)
1606 ;; For non-file bfr, use bfr name and Emacs pid.
1607 (expand-file-name (format "#%s#%s#" (buffer-name) (make-temp-name "")))))
1609 (defun auto-save-file-name-p (filename)
1610 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
1611 FILENAME should lack slashes. You can redefine this for customization."
1612 (string-match "^#.*#$" filename
))
1614 (defconst list-directory-brief-switches
1615 (if (eq system-type
'vax-vms
) "" "-CF")
1616 "*Switches for list-directory to pass to `ls' for brief listing,")
1618 (defconst list-directory-verbose-switches
1619 (if (eq system-type
'vax-vms
)
1620 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
1622 "*Switches for list-directory to pass to `ls' for verbose listing,")
1624 (defun list-directory (dirname &optional verbose
)
1625 "Display a list of files in or matching DIRNAME, a la `ls'.
1626 DIRNAME is globbed by the shell if necessary.
1627 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
1628 Actions controlled by variables `list-directory-brief-switches'
1629 and `list-directory-verbose-switches'."
1630 (interactive (let ((pfx current-prefix-arg
))
1631 (list (read-file-name (if pfx
"List directory (verbose): "
1632 "List directory (brief): ")
1633 nil default-directory nil
)
1635 (let ((switches (if verbose list-directory-verbose-switches
1636 list-directory-brief-switches
)))
1637 (or dirname
(setq dirname default-directory
))
1638 (setq dirname
(expand-file-name dirname
))
1639 (with-output-to-temp-buffer "*Directory*"
1640 (buffer-disable-undo standard-output
)
1641 (princ "Directory ")
1645 (set-buffer "*Directory*")
1646 (let ((wildcard (not (file-directory-p dirname
))))
1647 (insert-directory dirname switches wildcard
(not wildcard
)))))))
1649 (defvar insert-directory-program
"ls"
1650 "Absolute or relative name of the `ls' program used by `insert-directory'.")
1653 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
1654 ;; FULL-DIRECTORY-P is nil.
1655 ;; The single line of output must display FILE's name as it was
1656 ;; given, namely, an absolute path name.
1657 ;; - must insert exactly one line for each file if WILDCARD or
1658 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
1659 ;; before the file lines, plus optional text after the file lines.
1660 ;; Lines are delimited by "\n", so filenames containing "\n" are not
1662 ;; File lines should display the basename.
1663 ;; - must be consistent with
1664 ;; - functions dired-move-to-filename, (these two define what a file line is)
1665 ;; dired-move-to-end-of-filename,
1666 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
1667 ;; dired-insert-headerline
1668 ;; dired-after-subdir-garbage (defines what a "total" line is)
1669 ;; - variable dired-subdir-regexp
1670 (defun insert-directory (file switches
&optional wildcard full-directory-p
)
1671 "Insert directory listing for of FILE, formatted according to SWITCHES.
1672 Leaves point after the inserted text.
1673 Optional third arg WILDCARD means treat FILE as shell wildcard.
1674 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
1675 switches do not contain `d', so that a full listing is expected.
1677 This works by running a directory listing program
1678 whose name is in the variable `insert-directory-program'.
1679 If WILDCARD, it also runs the shell specified by `shell-file-name'."
1680 (let ((handler (find-file-name-handler file
)))
1682 (funcall handler
'insert-directory file switches
1683 wildcard full-directory-p
)
1684 (if (eq system-type
'vax-vms
)
1685 (vms-read-directory file switches
(current-buffer))
1687 (let ((default-directory (file-name-directory file
)))
1688 (call-process shell-file-name nil t nil
1689 "-c" (concat insert-directory-program
1691 (file-name-nondirectory file
))))
1692 ;;; ;; Chase links till we reach a non-link.
1694 ;;; (while (setq symlink (file-symlink-p file))
1695 ;;; (setq file symlink)))
1696 (call-process insert-directory-program nil t nil switches file
))))))
1698 (defun save-buffers-kill-emacs (&optional arg
)
1699 "Offer to save each buffer, then kill this Emacs process.
1700 With prefix arg, silently save all file-visiting buffers, then kill."
1702 (save-some-buffers arg t
)
1703 (and (or (not (memq t
(mapcar (function
1704 (lambda (buf) (and (buffer-file-name buf
)
1705 (buffer-modified-p buf
))))
1707 (yes-or-no-p "Modified buffers exist; exit anyway? "))
1708 (or (not (fboundp 'process-list
))
1709 ;; process-list is not defined on VMS.
1710 (let ((processes (process-list))
1713 (and (memq (process-status (car processes
)) '(run stop open
))
1714 (let ((val (process-kill-without-query (car processes
))))
1715 (process-kill-without-query (car processes
) val
)
1718 (setq processes
(cdr processes
)))
1720 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
1723 (define-key ctl-x-map
"\C-f" 'find-file
)
1724 (define-key ctl-x-map
"\C-q" 'toggle-read-only
)
1725 (define-key ctl-x-map
"\C-r" 'find-file-read-only
)
1726 (define-key ctl-x-map
"\C-v" 'find-alternate-file
)
1727 (define-key ctl-x-map
"\C-s" 'save-buffer
)
1728 (define-key ctl-x-map
"s" 'save-some-buffers
)
1729 (define-key ctl-x-map
"\C-w" 'write-file
)
1730 (define-key ctl-x-map
"i" 'insert-file
)
1731 (define-key esc-map
"~" 'not-modified
)
1732 (define-key ctl-x-map
"\C-d" 'list-directory
)
1733 (define-key ctl-x-map
"\C-c" 'save-buffers-kill-emacs
)
1735 (define-key ctl-x-4-map
"f" 'find-file-other-window
)
1736 (define-key ctl-x-4-map
"r" 'find-file-read-only-other-window
)
1737 (define-key ctl-x-4-map
"\C-f" 'find-file-other-window
)
1738 (define-key ctl-x-4-map
"b" 'switch-to-buffer-other-window
)
1739 (define-key ctl-x-4-map
"\C-o" 'display-buffer
)
1741 (define-key ctl-x-5-map
"b" 'switch-to-buffer-other-frame
)
1742 (define-key ctl-x-5-map
"f" 'find-file-other-frame
)
1743 (define-key ctl-x-5-map
"\C-f" 'find-file-other-frame
)
1744 (define-key ctl-x-5-map
"r" 'find-file-read-only-other-frame
)
1746 ;;; files.el ends here