1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1993 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 ;;; In case someone does make it local.
184 (put 'write-file-hooks
'permanent-local t
)
185 (defvar write-file-hooks nil
186 "List of functions to be called before writing out a buffer to a file.
187 If one of them returns non-nil, the file is considered already written
188 and the rest are not called.
189 These hooks are considered to pertain to the visited file.
190 So this list is cleared if you change the visited file name.
191 See also `write-contents-hooks'.
192 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.")
194 (put 'local-write-file-hooks
'permanent-local t
)
195 (defvar local-write-file-hooks nil
196 "Just like `write-file-hooks', except intended for per-buffer use.
197 The functions in this list are called before the ones in
198 `write-file-hooks'.")
200 (defvar write-contents-hooks nil
201 "List of functions to be called before writing out a buffer to a file.
202 If one of them returns non-nil, the file is considered already written
203 and the rest are not called.
204 These hooks are considered to pertain to the buffer's contents,
205 not to the particular visited file; thus, `set-visited-file-name' does
206 not clear this variable, but changing the major mode does clear it.
207 See also `write-file-hooks'.")
209 (defconst enable-local-variables t
210 "*Control use of local-variables lists in files you visit.
211 The value can be t, nil or something else.
212 A value of t means local-variables lists are obeyed;
213 nil means they are ignored; anything else means query.
215 The command \\[normal-mode] always obeys local-variables lists
216 and ignores this variable.")
218 (defconst enable-local-eval
'maybe
219 "*Control processing of the \"variable\" `eval' in a file's local variables.
220 The value can be t, nil or something else.
221 A value of t means obey `eval' variables;
222 nil means ignore them; anything else means query.
224 The command \\[normal-mode] always obeys local-variables lists
225 and ignores this variable.")
227 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
228 (or (fboundp 'lock-buffer
)
229 (fset 'lock-buffer
'ignore
))
230 (or (fboundp 'unlock-buffer
)
231 (fset 'unlock-buffer
'ignore
))
234 "Show the current default directory."
236 (message "Directory %s" default-directory
))
239 "Make DIR become the current buffer's default directory."
240 (interactive "DChange default directory: ")
241 (setq dir
(expand-file-name dir
))
242 (if (not (eq system-type
'vax-vms
))
243 (setq dir
(file-name-as-directory dir
)))
244 (if (not (file-directory-p dir
))
245 (error "%s is not a directory" dir
)
246 (if (file-executable-p dir
)
247 (setq default-directory dir
)
248 (error "Cannot cd to %s: Permission denied" dir
)))
249 ;; We used to call pwd at this point. That's not terribly helpful
250 ;; when we're invoking cd interactively, and the new cmushell-based
251 ;; shell has its own (better) facilities for this.
254 (defun load-file (file)
255 "Load the Lisp file named FILE."
256 (interactive "fLoad file: ")
257 (load (expand-file-name file
) nil nil t
))
259 (defun load-library (library)
260 "Load the library named LIBRARY.
261 This is an interface to the function `load'."
262 (interactive "sLoad library: ")
265 ;; OTHER is the other file to be compared.
266 (defun file-local-copy (file)
267 "Copy the file FILE into a temporary file on this machine.
268 Returns the name of the local copy, or nil, if FILE is directly
270 (let ((handler (find-file-name-handler file
)))
272 (funcall handler
'file-local-copy file
)
275 (defun file-truename (filename)
276 "Return the truename of FILENAME, which should be absolute.
277 The truename of a file name is found by chasing symbolic links
278 both at the level of the file and at the level of the directories
279 containing it, until no links are left at any level."
280 (if (string= filename
"~")
281 (setq filename
(expand-file-name filename
)))
282 (let ((handler (find-file-name-handler filename
)))
283 ;; For file name that has a special handler, call handler.
284 ;; This is so that ange-ftp can save time by doing a no-op.
286 (funcall handler
'file-truename filename
)
287 (let ((dir (file-name-directory filename
))
289 ;; Get the truename of the directory.
290 (setq dirfile
(directory-file-name dir
))
291 ;; If these are equal, we have the (or a) root directory.
292 (or (string= dir dirfile
)
293 (setq dir
(file-name-as-directory (file-truename dirfile
))))
294 ;; Put it back on the file name.
295 (setq filename
(concat dir
(file-name-nondirectory filename
)))
296 ;; Is the file name the name of a link?
297 (setq target
(file-symlink-p filename
))
299 ;; Yes => chase that link, then start all over
300 ;; since the link may point to a directory name that uses links.
301 (file-truename (expand-file-name target dir
))
306 (defun switch-to-buffer-other-window (buffer)
307 "Select buffer BUFFER in another window."
308 (interactive "BSwitch to buffer in other window: ")
309 (let ((pop-up-windows t
))
310 (pop-to-buffer buffer t
)))
312 (defun switch-to-buffer-other-frame (buffer)
313 "Switch to buffer BUFFER in another frame."
314 (interactive "BSwitch to buffer in other frame: ")
315 (let ((pop-up-frames t
))
316 (pop-to-buffer buffer t
)))
318 (defun find-file (filename)
320 Switch to a buffer visiting file FILENAME,
321 creating one if none already exists."
322 (interactive "FFind file: ")
323 (switch-to-buffer (find-file-noselect filename
)))
325 (defun find-file-other-window (filename)
326 "Edit file FILENAME, in another window.
327 May create a new window, or reuse an existing one.
328 See the function `display-buffer'."
329 (interactive "FFind file in other window: ")
330 (switch-to-buffer-other-window (find-file-noselect filename
)))
332 (defun find-file-other-frame (filename)
333 "Edit file FILENAME, in another frame.
334 May create a new frame, or reuse an existing one.
335 See the function `display-buffer'."
336 (interactive "FFind file in other frame: ")
337 (switch-to-buffer-other-frame (find-file-noselect filename
)))
339 (defun find-file-read-only (filename)
340 "Edit file FILENAME but don't allow changes.
341 Like \\[find-file] but marks buffer as read-only.
342 Use \\[toggle-read-only] to permit editing."
343 (interactive "fFind file read-only: ")
345 (setq buffer-read-only t
))
347 (defun find-file-read-only-other-window (filename)
348 "Edit file FILENAME in another window but don't allow changes.
349 Like \\[find-file-other-window] but marks buffer as read-only.
350 Use \\[toggle-read-only] to permit editing."
351 (interactive "fFind file read-only other window: ")
353 (setq buffer-read-only t
))
355 (defun find-file-read-only-other-frame (filename)
356 "Edit file FILENAME in another frame but don't allow changes.
357 Like \\[find-file-other-frame] but marks buffer as read-only.
358 Use \\[toggle-read-only] to permit editing."
359 (interactive "fFind file read-only other frame: ")
360 (find-file-other-frame filename
)
361 (setq buffer-read-only t
))
363 (defun find-alternate-file (filename)
364 "Find file FILENAME, select its buffer, kill previous buffer.
365 If the current buffer now contains an empty file that you just visited
366 \(presumably by mistake), use this command to visit the file you really want."
368 (let ((file buffer-file-name
)
372 (setq file-name
(file-name-nondirectory file
)
373 file-dir
(file-name-directory file
)))
374 (list (read-file-name
375 "Find alternate file: " file-dir nil nil file-name
))))
376 (and (buffer-modified-p)
377 ;; (not buffer-read-only)
378 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
381 (let ((obuf (current-buffer))
382 (ofile buffer-file-name
)
383 (oname (buffer-name)))
384 (rename-buffer " **lose**")
385 (setq buffer-file-name nil
)
389 (find-file filename
))
390 (cond ((eq obuf
(current-buffer))
391 (setq buffer-file-name ofile
)
393 (rename-buffer oname
))))
394 (or (eq (current-buffer) obuf
)
395 (kill-buffer obuf
))))
397 (defun create-file-buffer (filename)
398 "Create a suitably named buffer for visiting FILENAME, and return it.
399 FILENAME (sans directory) is used unchanged if that name is free;
400 otherwise a string <2> or <3> or ... is appended to get an unused name."
401 (let ((lastname (file-name-nondirectory filename
)))
402 (if (string= lastname
"")
403 (setq lastname filename
))
404 (generate-new-buffer lastname
)))
406 (defun generate-new-buffer (name)
407 "Create and return a buffer with a name based on NAME.
408 Choose the buffer's name using `generate-new-buffer-name'."
409 (get-buffer-create (generate-new-buffer-name name
)))
411 (defconst automount-dir-prefix
"^/tmp_mnt/"
412 "Regexp to match the automounter prefix in a directory name.")
414 (defvar abbreviated-home-dir nil
415 "The the user's homedir abbreviated according to `directory-abbrev-list'.")
417 (defun abbreviate-file-name (filename)
418 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
419 This also substitutes \"~\" for the user's home directory.
420 Type \\[describe-variable] directory-abbrev-alist RET for more information."
421 ;; Get rid of the prefixes added by the automounter.
422 (if (and (string-match automount-dir-prefix filename
)
423 (file-exists-p (file-name-directory
424 (substring filename
(1- (match-end 0))))))
425 (setq filename
(substring filename
(1- (match-end 0)))))
426 (let ((tail directory-abbrev-alist
))
427 ;; If any elt of directory-abbrev-alist matches this name,
428 ;; abbreviate accordingly.
430 (if (string-match (car (car tail
)) filename
)
432 (concat (cdr (car tail
)) (substring filename
(match-end 0)))))
433 (setq tail
(cdr tail
)))
434 ;; Compute and save the abbreviated homedir name.
435 ;; We defer computing this until the first time it's needed, to
436 ;; give time for directory-abbrev-alist to be set properly.
437 (or abbreviated-home-dir
438 (setq abbreviated-home-dir
439 (let ((abbreviated-home-dir "$foo"))
440 (concat "^" (abbreviate-file-name (expand-file-name "~"))))))
441 ;; If FILENAME starts with the abbreviated homedir,
442 ;; make it start with `~' instead.
443 (if (string-match abbreviated-home-dir filename
)
445 (concat "~" (substring filename
(match-end 0)))))
448 (defun find-file-noselect (filename &optional nowarn
)
449 "Read file FILENAME into a buffer and return the buffer.
450 If a buffer exists visiting FILENAME, return that one, but
451 verify that the file has not changed since visited or saved.
452 The buffer is not selected, just returned to the caller."
454 (abbreviate-file-name
455 (expand-file-name filename
)))
456 (if (file-directory-p filename
)
457 (if find-file-run-dired
458 (dired-noselect filename
)
459 (error "%s is a directory." filename
))
460 (let* ((buf (get-file-buffer filename
))
461 (truename (abbreviate-file-name (file-truename filename
)))
462 (number (nthcdr 10 (file-attributes truename
)))
463 ;; Find any buffer for a file which has same truename.
467 (list (buffer-list)))
468 (while (and (not found
) list
)
470 (set-buffer (car list
))
471 (if (and buffer-file-name
472 (string= buffer-file-truename truename
))
473 (setq found
(car list
))))
474 (setq list
(cdr list
)))
480 (list (buffer-list)))
481 (while (and (not found
) list
)
483 (set-buffer (car list
))
484 (if (and (equal buffer-file-number number
)
485 ;; Verify this buffer's file number
486 ;; still belongs to its file.
487 (file-exists-p buffer-file-name
)
488 (equal (nthcdr 10 (file-attributes buffer-file-name
)) number
))
489 (setq found
(car list
))))
490 (setq list
(cdr list
)))
493 ;; Let user know if there is a buffer with the same truename.
494 (if (and (not buf
) same-truename
(not nowarn
))
495 (message "%s and %s are the same file (%s)"
496 filename
(buffer-file-name same-truename
)
498 (if (and (not buf
) same-number
(not nowarn
))
499 (message "%s and %s are the same file"
500 filename
(buffer-file-name same-number
))))
502 ;; Optionally also find that buffer.
503 (if (or find-file-existing-other-name find-file-visit-truename
)
504 (setq buf
(or same-truename same-number
)))
507 (verify-visited-file-modtime buf
)
508 (cond ((not (file-exists-p filename
))
509 (error "File %s no longer exists!" filename
))
512 (if (buffer-modified-p buf
)
513 "File %s changed on disk. Discard your edits? "
514 "File %s changed on disk. Read the new version? ")
515 (file-name-nondirectory filename
)))
518 (revert-buffer t t
)))))
520 ;;; The truename stuff makes this obsolete.
521 ;;; (let* ((link-name (car (file-attributes filename)))
522 ;;; (linked-buf (and (stringp link-name)
523 ;;; (get-file-buffer link-name))))
524 ;;; (if (bufferp linked-buf)
525 ;;; (message "Symbolic link to file in buffer %s"
526 ;;; (buffer-name linked-buf))))
527 (setq buf
(create-file-buffer filename
))
531 (insert-file-contents filename t
)
534 ;; Run find-file-not-found-hooks until one returns non-nil.
535 (let ((hooks find-file-not-found-hooks
))
537 (not (funcall (car hooks
))))
538 (setq hooks
(cdr hooks
))))))
539 ;; Find the file's truename, and maybe use that as visited name.
540 (setq buffer-file-truename
(abbreviate-file-name truename
))
541 (setq buffer-file-number number
)
542 (if find-file-visit-truename
(setq filename buffer-file-truename
))
543 ;; Set buffer's default directory to that of the file.
544 (setq default-directory
(file-name-directory filename
))
545 ;; Turn off backup files for certain file names. Since
546 ;; this is a permanent local, the major mode won't eliminate it.
547 (and (not (funcall backup-enable-predicate buffer-file-name
))
549 (make-local-variable 'backup-inhibited
)
550 (setq backup-inhibited t
)))
551 (after-find-file error
(not nowarn
))))
554 (defun after-find-file (&optional error warn noauto
)
555 "Called after finding a file and by the default revert function.
556 Sets buffer mode, parses local variables.
557 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
558 error in reading the file. WARN non-nil means warn if there
559 exists an auto-save file more recent than the visited file.
560 NOAUTO means don't mess with auto-save mode.
561 Finishes by calling the functions in `find-file-hooks'."
562 (setq buffer-read-only
(not (file-writable-p buffer-file-name
)))
567 (cond ((and error
(file-attributes buffer-file-name
))
568 (setq buffer-read-only t
)
569 "File exists, but is read-protected.")
570 ((not buffer-read-only
)
572 (file-newer-than-file-p (make-auto-save-file-name)
574 "Auto save file is newer; consider M-x recover-file"
576 (if error
"(New file)" nil
)))
579 "Note: file is write protected")
580 ((file-attributes (directory-file-name default-directory
))
581 "File not found and directory write-protected")
582 ((file-exists-p (file-name-directory buffer-file-name
))
583 (setq buffer-read-only nil
))
585 (setq buffer-read-only nil
)
586 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name
))))
587 "Use M-x make-dir RET RET to create the directory"
588 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
592 (or not-serious
(sit-for 1 nil t
)))))
593 (if (and auto-save-default
(not noauto
))
596 (mapcar 'funcall find-file-hooks
))
598 (defun normal-mode (&optional find-file
)
599 "Choose the major mode for this buffer automatically.
600 Also sets up any specified local variables of the file.
601 Uses the visited file name, the -*- line, and the local variables spec.
603 This function is called automatically from `find-file'. In that case,
604 we may set up specified local variables depending on the value of
605 `enable-local-variables': if it is t, we do; if it is nil, we don't;
606 otherwise, we query. `enable-local-variables' is ignored if you
607 run `normal-mode' explicitly."
609 (or find-file
(funcall (or default-major-mode
'fundamental-mode
)))
612 (error (message "File mode specification error: %s"
613 (prin1-to-string err
))))
615 (let ((enable-local-variables (or (not find-file
)
616 enable-local-variables
)))
617 (hack-local-variables))
618 (error (message "File local-variables error: %s"
619 (prin1-to-string err
)))))
621 (defvar auto-mode-alist
(mapcar 'purecopy
622 '(("\\.text\\'" . text-mode
)
625 ("\\.tex\\'" . TeX-mode
)
626 ("\\.ltx\\'" . LaTeX-mode
)
627 ("\\.el\\'" . emacs-lisp-mode
)
628 ("\\.mm\\'" . nroff-mode
)
629 ("\\.me\\'" . nroff-mode
)
630 ("\\.ms\\'" . nroff-mode
)
631 ("\\.man\\'" . nroff-mode
)
632 ("\\.scm\\'" . scheme-mode
)
633 ("\\.l\\'" . lisp-mode
)
634 ("\\.lisp\\'" . lisp-mode
)
635 ("\\.f\\'" . fortran-mode
)
636 ("\\.for\\'" . fortran-mode
)
637 ("\\.mss\\'" . scribe-mode
)
638 ("\\.pl\\'" . prolog-mode
)
639 ("\\.cc\\'" . c
++-mode
)
640 ("\\.C\\'" . c
++-mode
)
641 ("\\.mk\\'" . makefile-mode
)
642 ("[Mm]akefile" . makefile-mode
)
643 ;;; Less common extensions come here
644 ;;; so more common ones above are found faster.
645 ("\\.s\\'" . asm-mode
)
646 ("ChangeLog\\'" . change-log-mode
)
647 ("ChangeLog.[0-9]+\\'" . change-log-mode
)
648 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode
)
649 ;; The following should come after the ChangeLog pattern
650 ;; for the sake of ChangeLog.1, etc.
651 ("\\.[12345678]\\'" . nroff-mode
)
652 ("\\.TeX\\'" . TeX-mode
)
653 ("\\.sty\\'" . LaTeX-mode
)
654 ("\\.bbl\\'" . LaTeX-mode
)
655 ("\\.bib\\'" . bibtex-mode
)
656 ("\\.article\\'" . text-mode
)
657 ("\\.letter\\'" . text-mode
)
658 ("\\.texinfo\\'" . texinfo-mode
)
659 ("\\.texi\\'" . texinfo-mode
)
660 ("\\.lsp\\'" . lisp-mode
)
661 ("\\.awk\\'" . awk-mode
)
662 ("\\.prolog\\'" . prolog-mode
)
663 ("\\.tar\\'" . tar-mode
)
664 ;; Mailer puts message to be edited in
665 ;; /tmp/Re.... or Message
666 ("^/tmp/Re" . text-mode
)
667 ("/Message[0-9]*\\'" . text-mode
)
668 ;; some news reader is reported to use this
669 ("^/tmp/fol/" . text-mode
)
671 ("\\.lex\\'" . c-mode
)
672 ("\\.oak\\'" . scheme-mode
)
673 ("\\.scm.[0-9]*\\'" . scheme-mode
)
674 ;; .emacs following a directory delimiter
675 ;; in either Unix or VMS syntax.
676 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode
)
677 ("\\.ml\\'" . lisp-mode
)))
679 Alist of filename patterns vs corresponding major mode functions.
680 Each element looks like (REGEXP . FUNCTION).
681 Visiting a file whose name matches REGEXP causes FUNCTION to be called.")
683 (defun set-auto-mode ()
684 "Select major mode appropriate for current buffer.
685 This checks for a -*- mode tag in the buffer's text, or
686 compares the filename against the entries in auto-mode-alist. It does
687 not check for the \"mode:\" local variable in the Local Variables
688 section of the file; for that, use `hack-local-variables'.
690 If `enable-local-variables' is nil, this function does not check for a
692 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
695 (goto-char (point-min))
696 (skip-chars-forward " \t\n")
697 (if (and enable-local-variables
698 (search-forward "-*-" (save-excursion
699 ;; If the file begins with "#!"
700 ;; (exec interpreter magic), look
701 ;; for mode frobs in the first two
702 ;; lines. You cannot necessarily
703 ;; put them in the first line of
704 ;; such a file without screwing up
705 ;; the interpreter invocation.
706 (end-of-line (and (looking-at "^#!") 2))
709 (skip-chars-forward " \t")
711 (search-forward "-*-"
712 (save-excursion (end-of-line) (point))
716 (skip-chars-backward " \t")
719 (if (search-forward ":" end t
)
722 (if (let ((case-fold-search t
))
723 (search-forward "mode:" end t
))
725 (skip-chars-forward " \t")
727 (if (search-forward ";" end t
)
730 (skip-chars-backward " \t")
731 (setq mode
(buffer-substring beg
(point))))))
732 (setq mode
(buffer-substring beg end
)))))
733 (setq mode
(intern (concat (downcase mode
) "-mode")))
734 (let ((alist auto-mode-alist
)
735 (name buffer-file-name
))
736 (let ((case-fold-search (eq system-type
'vax-vms
)))
737 ;; Remove backup-suffixes from file name.
738 (setq name
(file-name-sans-versions name
))
739 ;; Find first matching alist entry.
740 (while (and (not mode
) alist
)
741 (if (string-match (car (car alist
)) name
)
742 (setq mode
(cdr (car alist
))))
743 (setq alist
(cdr alist
)))))))
744 (if mode
(funcall mode
))))
746 (defun hack-local-variables-prop-line ()
747 ;; Set local variables specified in the -*- line.
748 ;; Returns t if mode was set.
750 (goto-char (point-min))
751 (skip-chars-forward " \t\n\r")
753 (end (save-excursion (end-of-line) (point)))
755 ;; Parse the -*- line into the `result' alist.
756 (cond ((not (search-forward "-*-" end t
))
759 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
760 ;; Simple form: "-*- MODENAME -*-".
763 (intern (buffer-substring
767 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
768 ;; (last ";" is optional).
770 (if (search-forward "-*-" end t
)
771 (setq end
(- (point) 3))
772 (error "-*- not terminated before end of line")))
773 (while (< (point) end
)
774 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
775 (error "malformed -*- line"))
776 (goto-char (match-end 0))
777 (let ((key (intern (downcase (buffer-substring
780 (val (save-restriction
781 (narrow-to-region (point) end
)
782 (read (current-buffer)))))
783 (setq result
(cons (cons key val
) result
))
784 (skip-chars-forward " \t;")))
785 (setq result
(nreverse result
))))
789 (while (setq mode
(assq 'mode result
))
790 (setq mode-p t result
(delq mode result
))
791 (funcall (intern (concat (downcase (symbol-name (cdr mode
)))
795 (or (eq enable-local-variables t
)
796 (and enable-local-variables
797 (save-window-excursion
798 (switch-to-buffer (current-buffer))
799 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
800 (file-name-nondirectory buffer-file-name
)))))))
802 (let ((key (car (car result
)))
803 (val (cdr (car result
))))
804 ;; 'mode has already been removed from this list.
805 (hack-one-local-variable key val
))
806 (setq result
(cdr result
))))
809 (defun hack-local-variables ()
810 "Parse and put into effect this buffer's local variables spec."
811 (hack-local-variables-prop-line)
812 ;; Look for "Local variables:" line in last page.
814 (goto-char (point-max))
815 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move
)
816 (if (let ((case-fold-search t
))
817 (and (search-forward "Local Variables:" nil t
)
818 (or (eq enable-local-variables t
)
819 (and enable-local-variables
820 (save-window-excursion
821 (switch-to-buffer (current-buffer))
824 (set-window-start (selected-window) (point)))
825 (y-or-n-p (format "Set local variables as specified at end of %s? "
826 (file-name-nondirectory buffer-file-name
))))))))
828 prefix prefixlen suffix beg
829 (enable-local-eval enable-local-eval
))
830 ;; The prefix is what comes before "local variables:" in its line.
831 ;; The suffix is what comes after "local variables:" in its line.
832 (skip-chars-forward " \t")
834 (setq suffix
(buffer-substring (point)
835 (progn (end-of-line) (point)))))
836 (goto-char (match-beginning 0))
839 (buffer-substring (point)
840 (progn (beginning-of-line) (point)))))
842 (if prefix
(setq prefixlen
(length prefix
)
843 prefix
(regexp-quote prefix
)))
844 (if suffix
(setq suffix
(concat (regexp-quote suffix
) "$")))
846 ;; Look at next local variable spec.
847 (if selective-display
(re-search-forward "[\n\C-m]")
849 ;; Skip the prefix, if any.
851 (if (looking-at prefix
)
852 (forward-char prefixlen
)
853 (error "Local variables entry is missing the prefix")))
854 ;; Find the variable name; strip whitespace.
855 (skip-chars-forward " \t")
857 (skip-chars-forward "^:\n")
858 (if (eolp) (error "Missing colon in local variables entry"))
859 (skip-chars-backward " \t")
860 (let* ((str (buffer-substring beg
(point)))
863 ;; Setting variable named "end" means end of list.
864 (if (string-equal (downcase str
) "end")
866 ;; Otherwise read the variable value.
867 (skip-chars-forward "^:")
869 (setq val
(read (current-buffer)))
870 (skip-chars-backward "\n")
871 (skip-chars-forward " \t")
872 (or (if suffix
(looking-at suffix
) (eolp))
873 (error "Local variables entry is terminated incorrectly"))
874 ;; Set the variable. "Variables" mode and eval are funny.
875 (hack-one-local-variable var val
))))))))
877 (defconst ignored-local-variables
879 "Variables to be ignored in a file's local variable spec.")
881 ;; "Set" one variable in a local variables spec.
882 ;; A few variable names are treated specially.
883 (defun hack-one-local-variable (var val
)
884 (cond ((eq var
'mode
)
885 (funcall (intern (concat (downcase (symbol-name val
))
887 ((memq var ignored-local-variables
)
889 ;; "Setting" eval means either eval it or do nothing.
891 (if (and (not (string= (user-login-name) "root"))
892 (or (eq enable-local-eval t
)
893 (and enable-local-eval
894 (save-window-excursion
895 (switch-to-buffer (current-buffer))
898 (set-window-start (selected-window) (point)))
899 (setq enable-local-eval
900 (y-or-n-p (format "Process `eval' local variable in file %s? "
901 (file-name-nondirectory buffer-file-name
))))))))
902 (save-excursion (eval val
))
903 (message "Ignoring `eval:' in file's local variables")))
904 ;; Ordinary variable, really set it.
905 (t (make-local-variable var
)
909 (defun set-visited-file-name (filename)
910 "Change name of file visited in current buffer to FILENAME.
911 The next time the buffer is saved it will go in the newly specified file.
912 nil or empty string as argument means make buffer not be visiting any file.
913 Remember to delete the initial contents of the minibuffer
914 if you wish to pass an empty string as the argument."
915 (interactive "FSet visited file name: ")
918 (if (string-equal filename
"")
920 (expand-file-name filename
))))
921 (or (equal filename buffer-file-name
)
924 (lock-buffer filename
)
926 (setq buffer-file-name filename
)
927 (if filename
; make buffer name reflect filename.
928 (let ((new-name (file-name-nondirectory buffer-file-name
)))
929 (if (string= new-name
"")
930 (error "Empty file name"))
931 (if (eq system-type
'vax-vms
)
932 (setq new-name
(downcase new-name
)))
933 (setq default-directory
(file-name-directory buffer-file-name
))
934 (rename-buffer new-name t
)))
935 (setq buffer-backed-up nil
)
936 (clear-visited-file-modtime)
939 (setq buffer-file-truename
940 (abbreviate-file-name (file-truename buffer-file-name
)))
941 (if find-file-visit-truename
942 (setq buffer-file-name buffer-file-truename
))
943 (setq buffer-file-number
(nth 10 (file-attributes buffer-file-name
))))
944 (setq buffer-file-truename nil buffer-file-number nil
))
945 ;; write-file-hooks is normally used for things like ftp-find-file
946 ;; that visit things that are not local files as if they were files.
947 ;; Changing to visit an ordinary local file instead should flush the hook.
948 (kill-local-variable 'write-file-hooks
)
949 (kill-local-variable 'local-write-file-hooks
)
950 (kill-local-variable 'revert-buffer-function
)
951 (kill-local-variable 'backup-inhibited
)
952 ;; Turn off backup files for certain file names.
953 ;; Since this is a permanent local, the major mode won't eliminate it.
954 (and (not (funcall backup-enable-predicate buffer-file-name
))
956 (make-local-variable 'backup-inhibited
)
957 (setq backup-inhibited t
)))
958 ;; If auto-save was not already on, turn it on if appropriate.
959 (if (not buffer-auto-save-file-name
)
960 (auto-save-mode (and buffer-file-name auto-save-default
))
961 ;; If auto save is on, start using a new name.
962 ;; We deliberately don't rename or delete the old auto save
963 ;; for the old visited file name. This is because perhaps
964 ;; the user wants to save the new state and then compare with the
965 ;; previous state from the auto save file.
966 (setq buffer-auto-save-file-name
967 (make-auto-save-file-name)))
969 (set-buffer-modified-p t
)))
971 (defun write-file (filename)
972 "Write current buffer into file FILENAME.
973 Makes buffer visit that file, and marks it not modified.
974 If the buffer is already visiting a file, you can specify
975 a directory name as FILENAME, to write a file of the same
976 old name in that directory."
977 ;; (interactive "FWrite file: ")
979 (list (if buffer-file-name
980 (read-file-name "Write file: "
982 (read-file-name "Write file: "
983 (cdr (assq 'default-directory
984 (buffer-local-variables)))
985 nil nil
(buffer-name)))))
986 (or (null filename
) (string-equal filename
"")
988 ;; If arg is just a directory,
989 ;; use same file name, but in that directory.
990 (if (and (file-directory-p filename
) buffer-file-name
)
991 (setq filename
(concat (file-name-as-directory filename
)
992 (file-name-nondirectory buffer-file-name
))))
993 (set-visited-file-name filename
)))
994 (set-buffer-modified-p t
)
997 (defun backup-buffer ()
998 "Make a backup of the disk file visited by the current buffer, if appropriate.
999 This is normally done before saving the buffer the first time.
1000 If the value is non-nil, it is the result of `file-modes' on the original
1001 file; this means that the caller, after saving the buffer, should change
1002 the modes of the new file to agree with the old modes."
1003 (if (and make-backup-files
(not backup-inhibited
)
1004 (not buffer-backed-up
)
1005 (file-exists-p buffer-file-name
)
1006 (memq (aref (elt (file-attributes buffer-file-name
) 8) 0)
1008 (let ((real-file-name buffer-file-name
)
1009 backup-info backupname targets setmodes
)
1010 ;; If specified name is a symbolic link, chase it to the target.
1011 ;; Thus we make the backups in the directory where the real file is.
1012 (while (let ((tem (file-symlink-p real-file-name
)))
1014 (setq real-file-name
1015 (expand-file-name tem
1016 (file-name-directory real-file-name
))))
1018 (setq backup-info
(find-backup-file-name real-file-name
)
1019 backupname
(car backup-info
)
1020 targets
(cdr backup-info
))
1021 ;;; (if (file-directory-p buffer-file-name)
1022 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1024 (let ((delete-old-versions
1025 ;; If have old versions to maybe delete,
1026 ;; ask the user to confirm now, before doing anything.
1027 ;; But don't actually delete til later.
1029 (or (eq trim-versions-without-asking t
) (eq trim-versions-without-asking nil
))
1030 (or trim-versions-without-asking
1031 (y-or-n-p (format "Delete excess backup versions of %s? "
1032 real-file-name
))))))
1033 ;; Actually write the back up file.
1035 (if (or file-precious-flag
1036 ; (file-symlink-p buffer-file-name)
1038 (and backup-by-copying-when-linked
1039 (> (file-nlinks real-file-name
) 1))
1040 (and backup-by-copying-when-mismatch
1041 (let ((attr (file-attributes real-file-name
)))
1043 (/= (nth 2 attr
) (user-uid))))))
1045 (copy-file real-file-name backupname t t
)
1047 ;; If copying fails because file BACKUPNAME
1048 ;; is not writable, delete that file and try again.
1049 (if (and (file-exists-p backupname
)
1050 (not (file-writable-p backupname
)))
1051 (delete-file backupname
))
1052 (copy-file real-file-name backupname t t
)))
1053 ;; rename-file should delete old backup.
1054 (rename-file real-file-name backupname t
)
1055 (setq setmodes
(file-modes backupname
)))
1057 ;; If trouble writing the backup, write it in ~.
1058 (setq backupname
(expand-file-name "~/%backup%~"))
1059 (message "Cannot write backup file; backing up in ~/%%backup%%~")
1062 (copy-file real-file-name backupname t t
)
1064 ;; If copying fails because file BACKUPNAME
1065 ;; is not writable, delete that file and try again.
1066 (if (and (file-exists-p backupname
)
1067 (not (file-writable-p backupname
)))
1068 (delete-file backupname
))
1069 (copy-file real-file-name backupname t t
)))))
1070 (setq buffer-backed-up t
)
1071 ;; Now delete the old versions, if desired.
1072 (if delete-old-versions
1075 (delete-file (car targets
))
1077 (setq targets
(cdr targets
))))
1079 (file-error nil
)))))
1081 (defun file-name-sans-versions (name &optional keep-backup-version
)
1082 "Return FILENAME sans backup versions or strings.
1083 This is a separate procedure so your site-init or startup file can
1085 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1086 we do not remove backup version numbers, only true file version numbers."
1087 (let ((handler (find-file-name-handler name
)))
1089 (funcall handler
'file-name-sans-versions name keep-backup-version
)
1091 (if (eq system-type
'vax-vms
)
1092 ;; VMS version number is (a) semicolon, optional
1093 ;; sign, zero or more digits or (b) period, option
1094 ;; sign, zero or more digits, provided this is the
1095 ;; second period encountered outside of the
1096 ;; device/directory part of the file name.
1097 (or (string-match ";[---+]?[0-9]*\\'" name
)
1098 (if (string-match "\\.[^]>:]*\\(\\.[---+]?[0-9]*\\)\\'"
1100 (match-beginning 1))
1102 (if keep-backup-version
1104 (or (string-match "\\.~[0-9]+~\\'" name
)
1105 (string-match "~\\'" name
)
1106 (length name
))))))))
1108 (defun make-backup-file-name (file)
1109 "Create the non-numeric backup file name for FILE.
1110 This is a separate function so you can redefine it for customization."
1113 (defun backup-file-name-p (file)
1114 "Return non-nil if FILE is a backup file name (numeric or not).
1115 This is a separate function so you can redefine it for customization.
1116 You may need to redefine `file-name-sans-versions' as well."
1117 (string-match "~$" file
))
1119 ;; This is used in various files.
1120 ;; The usage of bv-length is not very clean,
1121 ;; but I can't see a good alternative,
1122 ;; so as of now I am leaving it alone.
1123 (defun backup-extract-version (fn)
1124 "Given the name of a numeric backup file, return the backup number.
1125 Uses the free variable `bv-length', whose value should be
1126 the index in the name where the version number begins."
1127 (if (and (string-match "[0-9]+~$" fn bv-length
)
1128 (= (match-beginning 0) bv-length
))
1129 (string-to-int (substring fn bv-length -
1))
1132 ;; I believe there is no need to alter this behavior for VMS;
1133 ;; since backup files are not made on VMS, it should not get called.
1134 (defun find-backup-file-name (fn)
1135 "Find a file name for a backup file, and suggestions for deletions.
1136 Value is a list whose car is the name for the backup file
1137 and whose cdr is a list of old versions to consider deleting now."
1138 (if (eq version-control
'never
)
1139 (list (make-backup-file-name fn
))
1140 (let* ((base-versions (concat (file-name-nondirectory fn
) ".~"))
1141 (bv-length (length base-versions
))
1142 (possibilities (file-name-all-completions
1144 (file-name-directory fn
)))
1145 (versions (sort (mapcar
1146 (function backup-extract-version
)
1149 (high-water-mark (apply 'max
0 versions
))
1152 (> high-water-mark
0)))
1153 (number-to-delete (- (length versions
)
1154 kept-old-versions kept-new-versions -
1)))
1155 (if (not deserve-versions-p
)
1156 (list (make-backup-file-name fn
))
1157 (cons (concat fn
".~" (int-to-string (1+ high-water-mark
)) "~")
1158 (if (and (> number-to-delete
0)
1159 ;; Delete nothing if there is overflow
1160 ;; in the number of versions to keep.
1161 (>= (+ kept-new-versions kept-old-versions -
1) 0))
1162 (mapcar (function (lambda (n)
1163 (concat fn
".~" (int-to-string n
) "~")))
1164 (let ((v (nthcdr kept-old-versions versions
)))
1165 (rplacd (nthcdr (1- number-to-delete
) v
) ())
1168 (defun file-nlinks (filename)
1169 "Return number of names file FILENAME has."
1170 (car (cdr (file-attributes filename
))))
1172 (defun file-relative-name-1 (directory)
1173 (cond ((string= directory
"/")
1175 ((string-match (concat "^" (regexp-quote directory
))
1177 (substring filename
(match-end 0)))
1179 (file-relative-name-1
1180 (file-name-directory (substring directory
0 -
1))))))
1182 (defun file-relative-name (filename &optional directory
)
1183 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1184 (setq filename
(expand-file-name filename
)
1185 directory
(file-name-as-directory (if directory
1186 (expand-file-name directory
)
1187 default-directory
)))
1188 (file-relative-name-1 directory
))
1190 (defun save-buffer (&optional args
)
1191 "Save current buffer in visited file if modified. Versions described below.
1192 By default, makes the previous version into a backup file
1193 if previously requested or if this is the first save.
1194 With 1 or 3 \\[universal-argument]'s, marks this version
1195 to become a backup when the next save is done.
1196 With 2 or 3 \\[universal-argument]'s,
1197 unconditionally makes the previous version into a backup file.
1198 With argument of 0, never makes the previous version into a backup file.
1200 If a file's name is FOO, the names of its numbered backup versions are
1201 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1202 Numeric backups (rather than FOO~) will be made if value of
1203 `version-control' is not the atom `never' and either there are already
1204 numeric versions of the file being backed up, or `version-control' is
1206 We don't want excessive versions piling up, so there are variables
1207 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1208 and `kept-new-versions', which tells how many newest versions to keep.
1209 Defaults are 2 old versions and 2 new.
1210 `dired-kept-versions' controls dired's clean-directory (.) command.
1211 If `trim-versions-without-asking' is nil, system will query user
1212 before trimming versions. Otherwise it does it silently."
1214 (let ((modp (buffer-modified-p))
1215 (large (> (buffer-size) 50000))
1216 (make-backup-files (and make-backup-files
(not (eq args
0)))))
1217 (and modp
(memq args
'(16 64)) (setq buffer-backed-up nil
))
1218 (if (and modp large
) (message "Saving file %s..." (buffer-file-name)))
1220 (and modp
(memq args
'(4 64)) (setq buffer-backed-up nil
))))
1222 (defun delete-auto-save-file-if-necessary (&optional force
)
1223 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1224 Normally delete only if the file was written by this Emacs since
1225 the last real save, but optional arg FORCE non-nil means delete anyway."
1226 (and buffer-auto-save-file-name delete-auto-save-files
1227 (not (string= buffer-file-name buffer-auto-save-file-name
))
1228 (or force
(recent-auto-save-p))
1231 (delete-file buffer-auto-save-file-name
)
1233 (set-buffer-auto-saved))))
1235 (defun basic-save-buffer ()
1236 "Save the current buffer in its visited file, if it has been modified."
1238 (if (buffer-modified-p)
1239 (let ((recent-save (recent-auto-save-p))
1240 setmodes tempsetmodes
)
1241 ;; On VMS, rename file and buffer to get rid of version number.
1242 (if (and (eq system-type
'vax-vms
)
1243 (not (string= buffer-file-name
1244 (file-name-sans-versions buffer-file-name
))))
1245 (let (buffer-new-name)
1246 ;; Strip VMS version number before save.
1247 (setq buffer-file-name
1248 (file-name-sans-versions buffer-file-name
))
1249 ;; Construct a (unique) buffer name to correspond.
1250 (let ((buf (create-file-buffer (downcase buffer-file-name
))))
1251 (setq buffer-new-name
(buffer-name buf
))
1253 (rename-buffer buffer-new-name
)))
1254 ;; If buffer has no file name, ask user for one.
1255 (or buffer-file-name
1257 (setq buffer-file-name
1258 (expand-file-name (read-file-name "File to save in: ") nil
)
1259 default-directory
(file-name-directory buffer-file-name
))
1260 (auto-save-mode auto-save-default
)))
1261 (or (verify-visited-file-modtime (current-buffer))
1262 (not (file-exists-p buffer-file-name
))
1264 (format "%s has changed since visited or saved. Save anyway? "
1265 (file-name-nondirectory buffer-file-name
)))
1266 (error "Save not confirmed"))
1269 (and (> (point-max) 1)
1270 (/= (char-after (1- (point-max))) ?
\n)
1271 (or (eq require-final-newline t
)
1272 (and require-final-newline
1274 (format "Buffer %s does not end in newline. Add one? "
1277 (goto-char (point-max))
1279 (let ((hooks (append write-contents-hooks local-write-file-hooks
1283 (not (setq done
(funcall (car hooks
)))))
1284 (setq hooks
(cdr hooks
)))
1285 ;; If a hook returned t, file is already "written".
1287 (if (not (file-writable-p buffer-file-name
))
1288 (let ((dir (file-name-directory buffer-file-name
)))
1289 (if (not (file-directory-p dir
))
1290 (error "%s is not a directory" dir
)
1291 (if (not (file-exists-p buffer-file-name
))
1292 (error "Directory %s write-protected" dir
)
1294 (format "File %s is write-protected; try to save anyway? "
1295 (file-name-nondirectory
1297 (setq tempsetmodes t
)
1298 (error "Attempt to save to a file which you aren't allowed to write"))))))
1299 (or buffer-backed-up
1300 (setq setmodes
(backup-buffer)))
1301 (if file-precious-flag
1302 ;; If file is precious, write temp name, then rename it.
1303 (let ((dir (file-name-directory buffer-file-name
))
1304 (realname buffer-file-name
)
1305 tempname temp nogood i succeed
)
1308 ;; Find the temporary name to write under.
1310 (setq tempname
(format "%s#tmp#%d" dir i
))
1311 (setq nogood
(file-exists-p tempname
))
1314 (progn (clear-visited-file-modtime)
1315 (write-region (point-min) (point-max)
1316 tempname nil realname
)
1318 ;; If writing the temp file fails,
1319 ;; delete the temp file.
1320 (or succeed
(delete-file tempname
)))
1321 ;; Since we have created an entirely new file
1322 ;; and renamed it, make sure it gets the
1323 ;; right permission bits set.
1324 (setq setmodes
(file-modes buffer-file-name
))
1325 ;; We succeeded in writing the temp file,
1327 (rename-file tempname buffer-file-name t
))
1328 ;; If file not writable, see if we can make it writable
1329 ;; temporarily while we write it.
1330 ;; But no need to do so if we have just backed it up
1331 ;; (setmodes is set) because that says we're superseding.
1332 (cond ((and tempsetmodes
(not setmodes
))
1333 ;; Change the mode back, after writing.
1334 (setq setmodes
(file-modes buffer-file-name
))
1335 (set-file-modes buffer-file-name
511)))
1336 (write-region (point-min) (point-max)
1337 buffer-file-name nil t
)))))
1338 (setq buffer-file-number
(nth 10 (file-attributes buffer-file-name
)))
1341 (set-file-modes buffer-file-name setmodes
)
1343 ;; If the auto-save file was recent before this command,
1345 (delete-auto-save-file-if-necessary recent-save
)
1346 (run-hooks 'after-save-hooks
))
1347 (message "(No changes need to be saved)")))
1349 (defun save-some-buffers (&optional arg exiting
)
1350 "Save some modified file-visiting buffers. Asks user about each one.
1351 Optional argument (the prefix) non-nil means save all with no questions.
1352 Optional second argument EXITING means ask about certain non-file buffers
1353 as well as about file buffers."
1355 (save-window-excursion
1356 (if (zerop (map-y-or-n-p
1359 (and (buffer-modified-p buffer
)
1361 (buffer-file-name buffer
)
1365 (and buffer-offer-save
(> (buffer-size) 0)))))
1368 (if (buffer-file-name buffer
)
1369 (format "Save file %s? "
1370 (buffer-file-name buffer
))
1371 (format "Save buffer %s? "
1372 (buffer-name buffer
)))))))
1378 '("buffer" "buffers" "save")
1379 (list (list ?\C-r
(lambda (buf)
1381 (setq view-exit-action
1383 (exit-recursive-edit)))
1385 ;; Return nil to ask about BUF again.
1387 "display the current buffer"))
1389 (message "(No files need saving)"))))
1391 (defun not-modified (&optional arg
)
1392 "Mark current buffer as unmodified, not needing to be saved.
1393 With prefix arg, mark buffer as modified, so \\[save-buffer] will save."
1395 (message (if arg
"Modification-flag set"
1396 "Modification-flag cleared"))
1397 (set-buffer-modified-p arg
))
1399 (defun toggle-read-only (&optional arg
)
1400 "Change whether this buffer is visiting its file read-only.
1401 With arg, set read-only iff arg is positive."
1403 (setq buffer-read-only
1405 (not buffer-read-only
)
1406 (> (prefix-numeric-value arg
) 0)))
1407 ;; Force mode-line redisplay
1408 (set-buffer-modified-p (buffer-modified-p)))
1410 (defun insert-file (filename)
1411 "Insert contents of file FILENAME into buffer after point.
1412 Set mark after the inserted text.
1414 This function is meant for the user to run interactively.
1415 Don't call it from programs! Use `insert-file-contents' instead.
1416 \(Its calling sequence is different; see its documentation)."
1417 (interactive "fInsert file: ")
1418 (let ((tem (insert-file-contents filename
)))
1419 (push-mark (+ (point) (car (cdr tem
))))))
1421 (defun append-to-file (start end filename
)
1422 "Append the contents of the region to the end of file FILENAME.
1423 When called from a function, expects three arguments,
1424 START, END and FILENAME. START and END are buffer positions
1425 saying what text to write."
1426 (interactive "r\nFAppend to file: ")
1427 (write-region start end filename t
))
1429 (defun file-newest-backup (filename)
1430 "Return most recent backup file for FILENAME or nil if no backups exist."
1431 (let* ((filename (expand-file-name filename
))
1432 (file (file-name-nondirectory filename
))
1433 (dir (file-name-directory filename
))
1434 (comp (file-name-all-completions file dir
))
1437 (setq file
(concat dir
(car comp
))
1439 (if (and (backup-file-name-p file
)
1440 (or (null newest
) (file-newer-than-file-p file newest
)))
1441 (setq newest file
)))
1444 (defun rename-uniquely ()
1445 "Rename current buffer to a similar name not already taken.
1446 This function is useful for creating multiple shell process buffers
1447 or multiple mail buffers, etc."
1449 (let* ((new-buf (generate-new-buffer (buffer-name)))
1450 (name (buffer-name new-buf
)))
1451 (kill-buffer new-buf
)
1452 (rename-buffer name
)
1453 (set-buffer-modified-p (buffer-modified-p)))) ; force mode line update
1455 (defun make-directory (dir &optional parents
)
1456 "Create the directory DIR and any nonexistent parent dirs."
1457 (interactive "FMake directory: \nP")
1458 (let ((handler (find-file-name-handler dir
)))
1460 (funcall handler
'make-directory dir parents
)
1462 (make-directory-internal dir
)
1463 (let ((dir (directory-file-name (expand-file-name dir
)))
1465 (while (not (file-exists-p dir
))
1466 (setq create-list
(cons dir create-list
)
1467 dir
(directory-file-name (file-name-directory dir
))))
1469 (make-directory-internal (car create-list
))
1470 (setq create-list
(cdr create-list
))))))))
1472 (put 'revert-buffer-function
'permanent-local t
)
1473 (defvar revert-buffer-function nil
1474 "Function to use to revert this buffer, or nil to do the default.")
1476 (put 'revert-buffer-insert-file-contents-function
'permanent-local t
)
1477 (defvar revert-buffer-insert-file-contents-function nil
1478 "Function to use to insert contents when reverting this buffer.
1479 Gets two args, first the nominal file name to use,
1480 and second, t if reading the auto-save file.")
1482 (defun revert-buffer (&optional ignore-auto noconfirm
)
1483 "Replace the buffer text with the text of the visited file on disk.
1484 This undoes all changes since the file was visited or saved.
1485 With a prefix argument, offer to revert from latest auto-save file, if
1486 that is more recent than the visited file.
1488 When called from lisp, the first argument is IGNORE-AUTO; only offer
1489 to revert from the auto-save file when this is nil. Note that the
1490 sense of this argument is the reverse of the prefix argument, for the
1491 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
1494 Optional second argument NOCONFIRM means don't ask for confirmation at
1497 If the value of `revert-buffer-function' is non-nil, it is called to
1499 ;; I admit it's odd to reverse the sense of the prefix argument, but
1500 ;; there is a lot of code out there which assumes that the first
1501 ;; argument should be t to avoid consulting the auto-save file, and
1502 ;; there's no straightforward way to encourage authors to notice a
1503 ;; reversal of the argument sense. So I'm just changing the user
1504 ;; interface, but leaving the programmatic interface the same.
1505 (interactive (list (not prefix-arg
)))
1506 (if revert-buffer-function
1507 (funcall revert-buffer-function ignore-auto noconfirm
)
1508 (let* ((opoint (point))
1509 (auto-save-p (and (not ignore-auto
)
1510 (recent-auto-save-p)
1511 buffer-auto-save-file-name
1512 (file-readable-p buffer-auto-save-file-name
)
1514 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
1515 (file-name (if auto-save-p
1516 buffer-auto-save-file-name
1518 (cond ((null file-name
)
1519 (error "Buffer does not seem to be associated with any file"))
1521 (yes-or-no-p (format "Revert buffer from file %s? "
1523 ;; If file was backed up but has changed since,
1524 ;; we shd make another backup.
1525 (and (not auto-save-p
)
1526 (not (verify-visited-file-modtime (current-buffer)))
1527 (setq buffer-backed-up nil
))
1528 ;; Get rid of all undo records for this buffer.
1529 (or (eq buffer-undo-list t
)
1530 (setq buffer-undo-list nil
))
1531 (let ((buffer-read-only nil
)
1532 ;; Don't make undo records for the reversion.
1533 (buffer-undo-list t
))
1534 (if revert-buffer-insert-file-contents-function
1535 (funcall revert-buffer-insert-file-contents-function
1536 file-name auto-save-p
)
1537 (if (not (file-exists-p file-name
))
1538 (error "File %s no longer exists!" file-name
))
1539 ;; Bind buffer-file-name to nil
1540 ;; so that we don't try to lock the file.
1541 (let ((buffer-file-name nil
))
1545 (insert-file-contents file-name
(not auto-save-p
))))
1546 (goto-char (min opoint
(point-max)))
1547 (after-find-file nil nil t
)
1550 (defun recover-file (file)
1551 "Visit file FILE, but get contents from its last auto-save file."
1553 (let ((prompt-file buffer-file-name
)
1557 (setq file-name
(file-name-nondirectory prompt-file
)
1558 file-dir
(file-name-directory prompt-file
)))
1559 (list (read-file-name "Recover file: "
1560 file-dir nil nil file-name
))))
1561 (setq file
(expand-file-name file
))
1562 (if (auto-save-file-name-p file
) (error "%s is an auto-save file" file
))
1563 (let ((file-name (let ((buffer-file-name file
))
1564 (make-auto-save-file-name))))
1565 (cond ((not (file-newer-than-file-p file-name file
))
1566 (error "Auto-save file %s not current" file-name
))
1567 ((save-window-excursion
1568 (if (not (eq system-type
'vax-vms
))
1569 (with-output-to-temp-buffer "*Directory*"
1570 (buffer-disable-undo standard-output
)
1571 (call-process "ls" nil standard-output nil
1572 (if (file-symlink-p file
) "-lL" "-l")
1574 (yes-or-no-p (format "Recover auto save file %s? " file-name
)))
1575 (switch-to-buffer (find-file-noselect file t
))
1576 (let ((buffer-read-only nil
))
1578 (insert-file-contents file-name nil
))
1579 (after-find-file nil nil t
))
1580 (t (error "Recover-file cancelled.")))))
1582 (defun kill-some-buffers ()
1583 "For each buffer, ask whether to kill it."
1585 (let ((list (buffer-list)))
1587 (let* ((buffer (car list
))
1588 (name (buffer-name buffer
)))
1589 (and (not (string-equal name
""))
1590 (/= (aref name
0) ?
)
1592 (format "Buffer %s %s. Kill? "
1594 (if (buffer-modified-p buffer
)
1595 "HAS BEEN EDITED" "is unmodified")))
1596 (kill-buffer buffer
)))
1597 (setq list
(cdr list
)))))
1599 (defun auto-save-mode (arg)
1600 "Toggle auto-saving of contents of current buffer.
1601 With prefix argument ARG, turn auto-saving on if positive, else off."
1603 (setq buffer-auto-save-file-name
1605 (not buffer-auto-save-file-name
)
1606 (or (eq arg t
) (listp arg
) (and (integerp arg
) (> arg
0))))
1607 (if (and buffer-file-name auto-save-visited-file-name
1608 (not buffer-read-only
))
1610 (make-auto-save-file-name))))
1612 (message "Auto-save %s (in this buffer)"
1613 (if buffer-auto-save-file-name
"on" "off")))
1614 buffer-auto-save-file-name
)
1616 (defun rename-auto-save-file ()
1617 "Adjust current buffer's auto save file name for current conditions.
1618 Also rename any existing auto save file, if it was made in this session."
1619 (let ((osave buffer-auto-save-file-name
))
1620 (setq buffer-auto-save-file-name
1621 (make-auto-save-file-name))
1622 (if (and osave buffer-auto-save-file-name
1623 (not (string= buffer-auto-save-file-name buffer-file-name
))
1624 (not (string= buffer-auto-save-file-name osave
))
1625 (file-exists-p osave
)
1626 (recent-auto-save-p))
1627 (rename-file osave buffer-auto-save-file-name t
))))
1629 (defun make-auto-save-file-name ()
1630 "Return file name to use for auto-saves of current buffer.
1631 Does not consider `auto-save-visited-file-name' as that variable is checked
1632 before calling this function. You can redefine this for customization.
1633 See also `auto-save-file-name-p'."
1634 (if buffer-file-name
1635 (concat (file-name-directory buffer-file-name
)
1637 (file-name-nondirectory buffer-file-name
)
1639 ;; For non-file bfr, use bfr name and Emacs pid.
1640 (expand-file-name (format "#%s#%s#" (buffer-name) (make-temp-name "")))))
1642 (defun auto-save-file-name-p (filename)
1643 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
1644 FILENAME should lack slashes. You can redefine this for customization."
1645 (string-match "^#.*#$" filename
))
1647 (defconst list-directory-brief-switches
1648 (if (eq system-type
'vax-vms
) "" "-CF")
1649 "*Switches for list-directory to pass to `ls' for brief listing,")
1651 (defconst list-directory-verbose-switches
1652 (if (eq system-type
'vax-vms
)
1653 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
1655 "*Switches for list-directory to pass to `ls' for verbose listing,")
1657 (defun list-directory (dirname &optional verbose
)
1658 "Display a list of files in or matching DIRNAME, a la `ls'.
1659 DIRNAME is globbed by the shell if necessary.
1660 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
1661 Actions controlled by variables `list-directory-brief-switches'
1662 and `list-directory-verbose-switches'."
1663 (interactive (let ((pfx current-prefix-arg
))
1664 (list (read-file-name (if pfx
"List directory (verbose): "
1665 "List directory (brief): ")
1666 nil default-directory nil
)
1668 (let ((switches (if verbose list-directory-verbose-switches
1669 list-directory-brief-switches
)))
1670 (or dirname
(setq dirname default-directory
))
1671 (setq dirname
(expand-file-name dirname
))
1672 (with-output-to-temp-buffer "*Directory*"
1673 (buffer-disable-undo standard-output
)
1674 (princ "Directory ")
1678 (set-buffer "*Directory*")
1679 (let ((wildcard (not (file-directory-p dirname
))))
1680 (insert-directory dirname switches wildcard
(not wildcard
)))))))
1682 (defvar insert-directory-program
"ls"
1683 "Absolute or relative name of the `ls' program used by `insert-directory'.")
1686 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
1687 ;; FULL-DIRECTORY-P is nil.
1688 ;; The single line of output must display FILE's name as it was
1689 ;; given, namely, an absolute path name.
1690 ;; - must insert exactly one line for each file if WILDCARD or
1691 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
1692 ;; before the file lines, plus optional text after the file lines.
1693 ;; Lines are delimited by "\n", so filenames containing "\n" are not
1695 ;; File lines should display the basename.
1696 ;; - must be consistent with
1697 ;; - functions dired-move-to-filename, (these two define what a file line is)
1698 ;; dired-move-to-end-of-filename,
1699 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
1700 ;; dired-insert-headerline
1701 ;; dired-after-subdir-garbage (defines what a "total" line is)
1702 ;; - variable dired-subdir-regexp
1703 (defun insert-directory (file switches
&optional wildcard full-directory-p
)
1704 "Insert directory listing for of FILE, formatted according to SWITCHES.
1705 Leaves point after the inserted text.
1706 Optional third arg WILDCARD means treat FILE as shell wildcard.
1707 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
1708 switches do not contain `d', so that a full listing is expected.
1710 This works by running a directory listing program
1711 whose name is in the variable `insert-directory-program'.
1712 If WILDCARD, it also runs the shell specified by `shell-file-name'."
1713 (let ((handler (find-file-name-handler file
)))
1715 (funcall handler
'insert-directory file switches
1716 wildcard full-directory-p
)
1717 (if (eq system-type
'vax-vms
)
1718 (vms-read-directory file switches
(current-buffer))
1720 (let ((default-directory (file-name-directory file
)))
1721 (call-process shell-file-name nil t nil
1722 "-c" (concat insert-directory-program
1724 (file-name-nondirectory file
))))
1725 ;; Chase links till we reach a non-link.
1726 ;; This used to be commented out, but Barry Margolin says:
1727 ;; SunOS 4.1.3 (and SV and POSIX?) lists the link
1728 ;; if we give a link to a directory - yuck!
1730 (while (setq symlink
(file-symlink-p file
))
1731 (setq file symlink
)))
1732 (call-process insert-directory-program nil t nil switches file
))))))
1734 (defun save-buffers-kill-emacs (&optional arg
)
1735 "Offer to save each buffer, then kill this Emacs process.
1736 With prefix arg, silently save all file-visiting buffers, then kill."
1738 (save-some-buffers arg t
)
1739 (and (or (not (memq t
(mapcar (function
1740 (lambda (buf) (and (buffer-file-name buf
)
1741 (buffer-modified-p buf
))))
1743 (yes-or-no-p "Modified buffers exist; exit anyway? "))
1744 (or (not (fboundp 'process-list
))
1745 ;; process-list is not defined on VMS.
1746 (let ((processes (process-list))
1749 (and (memq (process-status (car processes
)) '(run stop open
))
1750 (let ((val (process-kill-without-query (car processes
))))
1751 (process-kill-without-query (car processes
) val
)
1754 (setq processes
(cdr processes
)))
1756 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
1759 (define-key ctl-x-map
"\C-f" 'find-file
)
1760 (define-key ctl-x-map
"\C-q" 'toggle-read-only
)
1761 (define-key ctl-x-map
"\C-r" 'find-file-read-only
)
1762 (define-key ctl-x-map
"\C-v" 'find-alternate-file
)
1763 (define-key ctl-x-map
"\C-s" 'save-buffer
)
1764 (define-key ctl-x-map
"s" 'save-some-buffers
)
1765 (define-key ctl-x-map
"\C-w" 'write-file
)
1766 (define-key ctl-x-map
"i" 'insert-file
)
1767 (define-key esc-map
"~" 'not-modified
)
1768 (define-key ctl-x-map
"\C-d" 'list-directory
)
1769 (define-key ctl-x-map
"\C-c" 'save-buffers-kill-emacs
)
1771 (define-key ctl-x-4-map
"f" 'find-file-other-window
)
1772 (define-key ctl-x-4-map
"r" 'find-file-read-only-other-window
)
1773 (define-key ctl-x-4-map
"\C-f" 'find-file-other-window
)
1774 (define-key ctl-x-4-map
"b" 'switch-to-buffer-other-window
)
1775 (define-key ctl-x-4-map
"\C-o" 'display-buffer
)
1777 (define-key ctl-x-5-map
"b" 'switch-to-buffer-other-frame
)
1778 (define-key ctl-x-5-map
"f" 'find-file-other-frame
)
1779 (define-key ctl-x-5-map
"\C-f" 'find-file-other-frame
)
1780 (define-key ctl-x-5-map
"r" 'find-file-read-only-other-frame
)
1782 ;;; files.el ends here