1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985, 86, 87, 92, 93,
4 ;; 94, 95, 1996 Free Software Foundation, Inc.
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; Defines most of Emacs's file- and directory-handling functions,
28 ;; including basic file visiting, backup generation, link handling,
29 ;; ITS-id version control, load- and write-hook handling, and the like.
33 (defvar delete-auto-save-files t
34 "*Non-nil means delete auto-save file when a buffer is saved or killed.")
36 (defvar directory-abbrev-alist
38 "*Alist of abbreviations for file directories.
39 A list of elements of the form (FROM . TO), each meaning to replace
40 FROM with TO when it appears in a directory name. This replacement is
41 done when setting up the default directory of a newly visited file.
42 *Every* FROM string should start with `^'.
44 Do not use `~' in the TO strings.
45 They should be ordinary absolute directory names.
47 Use this feature when you have directories which you normally refer to
48 via absolute symbolic links. Make TO the name of the link, and FROM
49 the name it is linked to.")
51 ;;; Turn off backup files on VMS since it has version numbers.
52 (defvar make-backup-files
(not (eq system-type
'vax-vms
))
53 "*Non-nil means make a backup of a file the first time it is saved.
54 This can be done by renaming the file or by copying.
56 Renaming means that Emacs renames the existing file so that it is a
57 backup file, then writes the buffer into a new file. Any other names
58 that the old file had will now refer to the backup file. The new file
59 is owned by you and its group is defaulted.
61 Copying means that Emacs copies the existing file into the backup
62 file, then writes the buffer on top of the existing file. Any other
63 names that the old file had will now refer to the new (edited) file.
64 The file's owner and group are unchanged.
66 The choice of renaming or copying is controlled by the variables
67 `backup-by-copying', `backup-by-copying-when-linked' and
68 `backup-by-copying-when-mismatch'. See also `backup-inhibited'.")
70 ;; Do this so that local variables based on the file name
71 ;; are not overridden by the major mode.
72 (defvar backup-inhibited nil
73 "Non-nil means don't make a backup, regardless of the other parameters.
74 This variable is intended for use by making it local to a buffer.
75 But it is local only if you make it local.")
76 (put 'backup-inhibited
'permanent-local t
)
78 (defvar backup-by-copying nil
79 "*Non-nil means always use copying to create backup files.
80 See documentation of variable `make-backup-files'.")
82 (defvar backup-by-copying-when-linked nil
83 "*Non-nil means use copying to create backups for files with multiple names.
84 This causes the alternate names to refer to the latest version as edited.
85 This variable is relevant only if `backup-by-copying' is nil.")
87 (defvar backup-by-copying-when-mismatch nil
88 "*Non-nil means create backups by copying if this preserves owner or group.
89 Renaming may still be used (subject to control of other variables)
90 when it would not result in changing the owner or group of the file;
91 that is, for files which are owned by you and whose group matches
92 the default for a new file created there by you.
93 This variable is relevant only if `backup-by-copying' is nil.")
95 (defvar backup-enable-predicate
97 (or (< (length name
) 5)
98 (not (string-equal "/tmp/" (substring name
0 5)))))
99 "Predicate that looks at a file name and decides whether to make backups.
100 Called with an absolute file name as argument, it returns t to enable backup.")
102 (defvar buffer-offer-save nil
103 "*Non-nil in a buffer means offer to save the buffer on exit
104 even if the buffer is not visiting a file.
105 Automatically local in all buffers.")
106 (make-variable-buffer-local 'buffer-offer-save
)
108 (defvar find-file-existing-other-name t
109 "*Non-nil means find a file under alternative names, in existing buffers.
110 This means if any existing buffer is visiting the file you want
111 under another name, you get the existing buffer instead of a new buffer.")
113 (defvar find-file-visit-truename nil
114 "*Non-nil means visit a file under its truename.
115 The truename of a file is found by chasing all links
116 both at the file level and at the levels of the containing directories.")
118 (defvar find-file-revert-without-query
120 "*Specify which files should be reverted without query.
121 The value is a list of regular expressions.
122 If the file name matches one of these regular expressions,
123 then `find-file' reverts the file without querying
124 if the file has changed on disk and you have not edited the buffer.")
126 (defvar buffer-file-number nil
127 "The device number and file number of the file visited in the current buffer.
128 The value is a list of the form (FILENUM DEVNUM).
129 This pair of numbers uniquely identifies the file.
130 If the buffer is visiting a new file, the value is nil.")
131 (make-variable-buffer-local 'buffer-file-number
)
132 (put 'buffer-file-number
'permanent-local t
)
134 (defvar buffer-file-numbers-unique
(not (memq system-type
'(windows-nt)))
135 "Non-nil means that buffer-file-number uniquely identifies files.")
137 (defvar file-precious-flag nil
138 "*Non-nil means protect against I/O errors while saving files.
139 Some modes set this non-nil in particular buffers.
141 This feature works by writing the new contents into a temporary file
142 and then renaming the temporary file to replace the original.
143 In this way, any I/O error in writing leaves the original untouched,
144 and there is never any instant where the file is nonexistent.
146 Note that this feature forces backups to be made by copying.
147 Yet, at the same time, saving a precious file
148 breaks any hard links between it and other files.")
150 (defvar version-control nil
151 "*Control use of version numbers for backup files.
152 t means make numeric backup versions unconditionally.
153 nil means make them for files that have some already.
154 `never' means do not make them.")
156 (defvar dired-kept-versions
2
157 "*When cleaning directory, number of versions to keep.")
159 (defvar delete-old-versions nil
160 "*If t, delete excess backup versions silently.
161 If nil, ask confirmation. Any other value prevents any trimming.")
163 (defvar kept-old-versions
2
164 "*Number of oldest versions to keep when a new numbered backup is made.")
166 (defvar kept-new-versions
2
167 "*Number of newest versions to keep when a new numbered backup is made.
168 Includes the new backup. Must be > 0")
170 (defvar require-final-newline nil
171 "*Value of t says silently ensure a file ends in a newline when it is saved.
172 Non-nil but not t says ask user whether to add a newline when there isn't one.
173 nil means don't add newlines.")
175 (defvar auto-save-default t
176 "*Non-nil says by default do auto-saving of every file-visiting buffer.")
178 (defvar auto-save-visited-file-name nil
179 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
180 Normally auto-save files are written under other names.")
182 (defvar save-abbrevs nil
183 "*Non-nil means save word abbrevs too when files are saved.
184 Loading an abbrev file sets this to t.")
186 (defvar find-file-run-dired t
187 "*Non-nil says run dired if `find-file' is given the name of a directory.")
189 ;;;It is not useful to make this a local variable.
190 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
191 (defvar find-file-not-found-hooks nil
192 "List of functions to be called for `find-file' on nonexistent file.
193 These functions are called as soon as the error is detected.
194 `buffer-file-name' is already set up.
195 The functions are called in the order given until one of them returns non-nil.")
197 ;;;It is not useful to make this a local variable.
198 ;;;(put 'find-file-hooks 'permanent-local t)
199 (defvar find-file-hooks nil
200 "List of functions to be called after a buffer is loaded from a file.
201 The buffer's local variables (if any) will have been processed before the
202 functions are called.")
204 (defvar write-file-hooks nil
205 "List of functions to be called before writing out a buffer to a file.
206 If one of them returns non-nil, the file is considered already written
207 and the rest are not called.
208 These hooks are considered to pertain to the visited file.
209 So this list is cleared if you change the visited file name.
211 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.
212 See also `write-contents-hooks'.")
213 ;;; However, in case someone does make it local...
214 (put 'write-file-hooks
'permanent-local t
)
216 (defvar local-write-file-hooks nil
217 "Just like `write-file-hooks', except intended for per-buffer use.
218 The functions in this list are called before the ones in
221 This variable is meant to be used for hooks that have to do with a
222 particular visited file. Therefore, it is a permanent local, so that
223 changing the major mode does not clear it. However, calling
224 `set-visited-file-name' does clear it.")
225 (make-variable-buffer-local 'local-write-file-hooks
)
226 (put 'local-write-file-hooks
'permanent-local t
)
228 (defvar write-contents-hooks nil
229 "List of functions to be called before writing out a buffer to a file.
230 If one of them returns non-nil, the file is considered already written
231 and the rest are not called.
233 This variable is meant to be used for hooks that pertain to the
234 buffer's contents, not to the particular visited file; thus,
235 `set-visited-file-name' does not clear this variable; but changing the
236 major mode does clear it.
238 This variable automatically becomes buffer-local whenever it is set.
239 If you use `add-hook' to add elements to the list, use nil for the
242 See also `write-file-hooks'.")
243 (make-variable-buffer-local 'write-contents-hooks
)
245 (defvar enable-local-variables t
246 "*Control use of local variables in files you visit.
247 The value can be t, nil or something else.
248 A value of t means file local variables specifications are obeyed;
249 nil means they are ignored; anything else means query.
251 The command \\[normal-mode] always obeys file local variable
252 specifications and ignores this variable.")
254 (defvar enable-local-eval
'maybe
255 "*Control processing of the \"variable\" `eval' in a file's local variables.
256 The value can be t, nil or something else.
257 A value of t means obey `eval' variables;
258 nil means ignore them; anything else means query.
260 The command \\[normal-mode] always obeys local-variables lists
261 and ignores this variable.")
263 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
264 (or (fboundp 'lock-buffer
)
265 (defalias 'lock-buffer
'ignore
))
266 (or (fboundp 'unlock-buffer
)
267 (defalias 'unlock-buffer
'ignore
))
268 (or (fboundp 'file-locked-p
)
269 (defalias 'file-locked-p
'ignore
))
271 ;; This hook function provides support for ange-ftp host name
272 ;; completion. It runs the usual ange-ftp hook, but only for
273 ;; completion operations. Having this here avoids the need
274 ;; to load ange-ftp when it's not really in use.
275 (defun ange-ftp-completion-hook-function (op &rest args
)
276 (if (memq op
'(file-name-completion file-name-all-completions
))
277 (apply 'ange-ftp-hook-function op args
)
278 (let ((inhibit-file-name-handlers
279 (cons 'ange-ftp-completion-hook-function
280 (and (eq inhibit-file-name-operation op
)
281 inhibit-file-name-handlers
)))
282 (inhibit-file-name-operation op
))
285 (defun convert-standard-filename (filename)
286 "Convert a standard file's name to something suitable for the current OS.
287 This function's standard definition is trivial; it just returns the argument.
288 However, on some systems, the function is redefined
289 with a definition that really does change some file names."
293 "Show the current default directory."
295 (message "Directory %s" default-directory
))
298 "Value of the CDPATH environment variable, as a list.
299 Not actually set up until the first time you you use it.")
301 (defvar path-separator
":"
302 "Character used to separate concatenated paths.")
304 (defun parse-colon-path (cd-path)
305 "Explode a colon-separated list of paths into a string list."
307 (let (cd-prefix cd-list
(cd-start 0) cd-colon
)
308 (setq cd-path
(concat cd-path path-separator
))
309 (while (setq cd-colon
(string-match path-separator cd-path cd-start
))
312 (list (if (= cd-start cd-colon
)
314 (substitute-in-file-name
315 (file-name-as-directory
316 (substring cd-path cd-start cd-colon
)))))))
317 (setq cd-start
(+ cd-colon
1)))
320 (defun cd-absolute (dir)
321 "Change current directory to given absolute file name DIR."
322 ;; Put the name into directory syntax now,
323 ;; because otherwise expand-file-name may give some bad results.
324 (if (not (eq system-type
'vax-vms
))
325 (setq dir
(file-name-as-directory dir
)))
326 (setq dir
(abbreviate-file-name (expand-file-name dir
)))
327 (if (not (file-directory-p dir
))
328 (error "%s is not a directory" dir
)
329 (if (file-executable-p dir
)
330 (setq default-directory dir
)
331 (error "Cannot cd to %s: Permission denied" dir
))))
334 "Make DIR become the current buffer's default directory.
335 If your environment includes a `CDPATH' variable, try each one of that
336 colon-separated list of directories when resolving a relative directory name."
338 (list (read-file-name "Change default directory: "
339 default-directory default-directory
340 (and (member cd-path
'(nil ("./")))
341 (null (getenv "CDPATH"))))))
342 (if (file-name-absolute-p dir
)
343 (cd-absolute (expand-file-name dir
))
345 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
346 (setq cd-path
(or trypath
(list "./")))))
347 (if (not (catch 'found
349 (function (lambda (x)
350 (let ((f (expand-file-name (concat x dir
))))
351 (if (file-directory-p f
)
354 (throw 'found t
))))))
357 (error "No such directory found via CDPATH environment variable"))))
359 (defun load-file (file)
360 "Load the Lisp file named FILE."
361 (interactive "fLoad file: ")
362 (load (expand-file-name file
) nil nil t
))
364 (defun load-library (library)
365 "Load the library named LIBRARY.
366 This is an interface to the function `load'."
367 (interactive "sLoad library: ")
370 (defun file-local-copy (file &optional buffer
)
371 "Copy the file FILE into a temporary file on this machine.
372 Returns the name of the local copy, or nil, if FILE is directly
374 (let ((handler (find-file-name-handler file
'file-local-copy
)))
376 (funcall handler
'file-local-copy file
)
379 (defun file-truename (filename &optional counter prev-dirs
)
380 "Return the truename of FILENAME, which should be absolute.
381 The truename of a file name is found by chasing symbolic links
382 both at the level of the file and at the level of the directories
383 containing it, until no links are left at any level.
385 The arguments COUNTER and PREV-DIRS are used only in recursive calls.
386 Do not specify them in other calls."
387 ;; COUNTER can be a cons cell whose car is the count of how many more links
388 ;; to chase before getting an error.
389 ;; PREV-DIRS can be a cons cell whose car is an alist
390 ;; of truenames we've just recently computed.
392 ;; The last test looks dubious, maybe `+' is meant here? --simon.
393 (if (or (string= filename
"") (string= filename
"~")
394 (and (string= (substring filename
0 1) "~")
395 (string-match "~[^/]*" filename
)))
397 (setq filename
(expand-file-name filename
))
398 (if (string= filename
"")
399 (setq filename
"/"))))
400 (or counter
(setq counter
(list 100)))
402 ;; For speed, remove the ange-ftp completion handler from the list.
403 ;; We know it's not needed here.
404 ;; For even more speed, do this only on the outermost call.
405 (file-name-handler-alist
406 (if prev-dirs file-name-handler-alist
407 (let ((tem (copy-sequence file-name-handler-alist
)))
408 (delq (rassq 'ange-ftp-completion-hook-function tem
) tem
)))))
409 (or prev-dirs
(setq prev-dirs
(list nil
)))
410 ;; If this file directly leads to a link, process that iteratively
411 ;; so that we don't use lots of stack.
413 (setcar counter
(1- (car counter
)))
414 (if (< (car counter
) 0)
415 (error "Apparent cycle of symbolic links for %s" filename
))
416 (let ((handler (find-file-name-handler filename
'file-truename
)))
417 ;; For file name that has a special handler, call handler.
418 ;; This is so that ange-ftp can save time by doing a no-op.
420 (setq filename
(funcall handler
'file-truename filename
)
422 (let ((dir (or (file-name-directory filename
) default-directory
))
424 ;; Get the truename of the directory.
425 (setq dirfile
(directory-file-name dir
))
426 ;; If these are equal, we have the (or a) root directory.
427 (or (string= dir dirfile
)
428 ;; If this is the same dir we last got the truename for,
429 ;; save time--don't recalculate.
430 (if (assoc dir
(car prev-dirs
))
431 (setq dir
(cdr (assoc dir
(car prev-dirs
))))
433 (new (file-name-as-directory (file-truename dirfile counter prev-dirs
))))
434 (setcar prev-dirs
(cons (cons old new
) (car prev-dirs
)))
436 (if (equal ".." (file-name-nondirectory filename
))
438 (directory-file-name (file-name-directory (directory-file-name dir
)))
440 (if (equal "." (file-name-nondirectory filename
))
441 (setq filename
(directory-file-name dir
)
443 ;; Put it back on the file name.
444 (setq filename
(concat dir
(file-name-nondirectory filename
)))
445 ;; Is the file name the name of a link?
446 (setq target
(file-symlink-p filename
))
448 ;; Yes => chase that link, then start all over
449 ;; since the link may point to a directory name that uses links.
450 ;; We can't safely use expand-file-name here
451 ;; since target might look like foo/../bar where foo
452 ;; is itself a link. Instead, we handle . and .. above.
454 (if (file-name-absolute-p target
)
462 (defun file-chase-links (filename)
463 "Chase links in FILENAME until a name that is not a link.
464 Does not examine containing directories for links,
465 unlike `file-truename'."
466 (let (tem (count 100) (newname filename
))
467 (while (setq tem
(file-symlink-p newname
))
469 (error "Apparent cycle of symbolic links for %s" filename
))
470 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
471 (while (string-match "//+" tem
)
472 (setq tem
(concat (substring tem
0 (1+ (match-beginning 0)))
473 (substring tem
(match-end 0)))))
474 ;; Handle `..' by hand, since it needs to work in the
475 ;; target of any directory symlink.
476 ;; This code is not quite complete; it does not handle
477 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
478 (while (string-match "\\`\\.\\./" tem
)
479 (setq tem
(substring tem
3))
480 (setq newname
(file-name-as-directory
481 ;; Do the .. by hand.
484 ;; Chase links in the default dir of the symlink.
487 (file-name-directory newname
))))))))
488 (setq newname
(expand-file-name tem
(file-name-directory newname
)))
489 (setq count
(1- count
)))
492 (defun switch-to-buffer-other-window (buffer &optional norecord
)
493 "Select buffer BUFFER in another window.
494 Optional second arg NORECORD non-nil means
495 do not put this buffer at the front of the list of recently selected ones."
496 (interactive "BSwitch to buffer in other window: ")
497 (let ((pop-up-windows t
))
498 (pop-to-buffer buffer t norecord
)))
500 (defun switch-to-buffer-other-frame (buffer &optional norecord
)
501 "Switch to buffer BUFFER in another frame.
502 Optional second arg NORECORD non-nil means
503 do not put this buffer at the front of the list of recently selected ones."
504 (interactive "BSwitch to buffer in other frame: ")
505 (let ((pop-up-frames t
))
506 (pop-to-buffer buffer t norecord
)
507 (raise-frame (window-frame (selected-window)))))
509 (defun find-file (filename)
511 Switch to a buffer visiting file FILENAME,
512 creating one if none already exists."
513 (interactive "FFind file: ")
514 (switch-to-buffer (find-file-noselect filename
)))
516 (defun find-file-other-window (filename)
517 "Edit file FILENAME, in another window.
518 May create a new window, or reuse an existing one.
519 See the function `display-buffer'."
520 (interactive "FFind file in other window: ")
521 (switch-to-buffer-other-window (find-file-noselect filename
)))
523 (defun find-file-other-frame (filename)
524 "Edit file FILENAME, in another frame.
525 May create a new frame, or reuse an existing one.
526 See the function `display-buffer'."
527 (interactive "FFind file in other frame: ")
528 (switch-to-buffer-other-frame (find-file-noselect filename
)))
530 (defun find-file-read-only (filename)
531 "Edit file FILENAME but don't allow changes.
532 Like \\[find-file] but marks buffer as read-only.
533 Use \\[toggle-read-only] to permit editing."
534 (interactive "fFind file read-only: ")
536 (setq buffer-read-only t
)
539 (defun find-file-read-only-other-window (filename)
540 "Edit file FILENAME in another window but don't allow changes.
541 Like \\[find-file-other-window] but marks buffer as read-only.
542 Use \\[toggle-read-only] to permit editing."
543 (interactive "fFind file read-only other window: ")
544 (find-file-other-window filename
)
545 (setq buffer-read-only t
)
548 (defun find-file-read-only-other-frame (filename)
549 "Edit file FILENAME in another frame but don't allow changes.
550 Like \\[find-file-other-frame] but marks buffer as read-only.
551 Use \\[toggle-read-only] to permit editing."
552 (interactive "fFind file read-only other frame: ")
553 (find-file-other-frame filename
)
554 (setq buffer-read-only t
)
557 (defun find-alternate-file-other-window (filename)
558 "Find file FILENAME as a replacement for the file in the next window.
559 This command does not select that window."
561 (save-selected-window
563 (let ((file buffer-file-name
)
567 (setq file-name
(file-name-nondirectory file
)
568 file-dir
(file-name-directory file
)))
569 (list (read-file-name
570 "Find alternate file: " file-dir nil nil file-name
)))))
572 (find-file-other-window filename
)
573 (save-selected-window
575 (find-alternate-file filename
))))
577 (defun find-alternate-file (filename)
578 "Find file FILENAME, select its buffer, kill previous buffer.
579 If the current buffer now contains an empty file that you just visited
580 \(presumably by mistake), use this command to visit the file you really want."
582 (let ((file buffer-file-name
)
586 (setq file-name
(file-name-nondirectory file
)
587 file-dir
(file-name-directory file
)))
588 (list (read-file-name
589 "Find alternate file: " file-dir nil nil file-name
))))
590 (and (buffer-modified-p) (buffer-file-name)
591 ;; (not buffer-read-only)
592 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
595 (let ((obuf (current-buffer))
596 (ofile buffer-file-name
)
597 (onum buffer-file-number
)
598 (otrue buffer-file-truename
)
599 (oname (buffer-name)))
600 (if (get-buffer " **lose**")
601 (kill-buffer " **lose**"))
602 (rename-buffer " **lose**")
606 (setq buffer-file-name nil
)
607 (setq buffer-file-number nil
)
608 (setq buffer-file-truename nil
)
609 (find-file filename
))
610 (cond ((eq obuf
(current-buffer))
611 (setq buffer-file-name ofile
)
612 (setq buffer-file-number onum
)
613 (setq buffer-file-truename otrue
)
615 (rename-buffer oname
))))
616 (or (eq (current-buffer) obuf
)
617 (kill-buffer obuf
))))
619 (defun create-file-buffer (filename)
620 "Create a suitably named buffer for visiting FILENAME, and return it.
621 FILENAME (sans directory) is used unchanged if that name is free;
622 otherwise a string <2> or <3> or ... is appended to get an unused name."
623 (let ((lastname (file-name-nondirectory filename
)))
624 (if (string= lastname
"")
625 (setq lastname filename
))
626 (generate-new-buffer lastname
)))
628 (defun generate-new-buffer (name)
629 "Create and return a buffer with a name based on NAME.
630 Choose the buffer's name using `generate-new-buffer-name'."
631 (get-buffer-create (generate-new-buffer-name name
)))
633 (defvar automount-dir-prefix
"^/tmp_mnt/"
634 "Regexp to match the automounter prefix in a directory name.")
636 (defvar abbreviated-home-dir nil
637 "The user's homedir abbreviated according to `directory-abbrev-list'.")
639 (defun abbreviate-file-name (filename)
640 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
641 This also substitutes \"~\" for the user's home directory.
642 Type \\[describe-variable] directory-abbrev-alist RET for more information."
643 ;; Get rid of the prefixes added by the automounter.
644 (if (and automount-dir-prefix
645 (string-match automount-dir-prefix filename
)
646 (file-exists-p (file-name-directory
647 (substring filename
(1- (match-end 0))))))
648 (setq filename
(substring filename
(1- (match-end 0)))))
649 (let ((tail directory-abbrev-alist
))
650 ;; If any elt of directory-abbrev-alist matches this name,
651 ;; abbreviate accordingly.
653 (if (string-match (car (car tail
)) filename
)
655 (concat (cdr (car tail
)) (substring filename
(match-end 0)))))
656 (setq tail
(cdr tail
)))
657 ;; Compute and save the abbreviated homedir name.
658 ;; We defer computing this until the first time it's needed, to
659 ;; give time for directory-abbrev-alist to be set properly.
660 ;; We include a slash at the end, to avoid spurious matches
661 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
662 (or abbreviated-home-dir
663 (setq abbreviated-home-dir
664 (let ((abbreviated-home-dir "$foo"))
665 (concat "^" (abbreviate-file-name (expand-file-name "~"))
668 ;; If FILENAME starts with the abbreviated homedir,
669 ;; make it start with `~' instead.
670 (if (and (string-match abbreviated-home-dir filename
)
671 ;; If the home dir is just /, don't change it.
672 (not (and (= (match-end 0) 1)
673 (= (aref filename
0) ?
/)))
674 ;; MS-DOS root directories can come with a drive letter;
675 ;; Novell Netware allows drive letters beyond `Z:'.
676 (not (and (or (eq system-type
'ms-dos
)
677 (eq system-type
'windows-nt
))
679 (string-match "^[a-zA-`]:/$" filename
)))))
682 (substring filename
(match-beginning 1) (match-end 1))
683 (substring filename
(match-end 0)))))
686 (defvar find-file-not-true-dirname-list nil
687 "*List of logical names for which visiting shouldn't save the true dirname.
688 On VMS, when you visit a file using a logical name that searches a path,
689 you may or may not want the visited file name to record the specific
690 directory where the file was found. If you *do not* want that, add the logical
691 name to this list as a string.")
693 (defun find-buffer-visiting (filename)
694 "Return the buffer visiting file FILENAME (a string).
695 This is like `get-file-buffer', except that it checks for any buffer
696 visiting the same file, possibly under a different name.
697 If there is no such live buffer, return nil."
698 (let ((buf (get-file-buffer filename
))
699 (truename (abbreviate-file-name (file-truename filename
))))
701 (let ((list (buffer-list)) found
)
702 (while (and (not found
) list
)
704 (set-buffer (car list
))
705 (if (and buffer-file-name
706 (string= buffer-file-truename truename
))
707 (setq found
(car list
))))
708 (setq list
(cdr list
)))
710 (let ((number (nthcdr 10 (file-attributes truename
)))
711 (list (buffer-list)) found
)
712 (and buffer-file-numbers-unique
714 (while (and (not found
) list
)
716 (set-buffer (car list
))
717 (if (and buffer-file-name
718 (equal buffer-file-number number
)
719 ;; Verify this buffer's file number
720 ;; still belongs to its file.
721 (file-exists-p buffer-file-name
)
722 (equal (nthcdr 10 (file-attributes buffer-file-name
))
724 (setq found
(car list
))))
725 (setq list
(cdr list
))))
728 (defun insert-file-contents-literally (filename &optional visit beg end replace
)
729 "Like `insert-file-contents', q.v., but only reads in the file.
730 A buffer may be modified in several ways after reading into the buffer due
731 to advanced Emacs features, such as file-name-handlers, format decoding,
732 find-file-hooks, etc.
733 This function ensures that none of these modifications will take place.
735 This function does not work for remote files, because it turns off
736 file name handlers and remote file access uses a file name handler."
737 (let ((file-name-handler-alist nil
)
739 (after-insert-file-functions nil
)
740 (find-buffer-file-type-function
741 (if (fboundp 'find-buffer-file-type
)
742 (symbol-function 'find-buffer-file-type
)
746 (fset 'find-buffer-file-type
(lambda (filename) t
))
747 (insert-file-contents filename visit beg end replace
))
748 (if find-buffer-file-type-function
749 (fset 'find-buffer-file-type find-buffer-file-type-function
)
750 (fmakunbound 'find-buffer-file-type
)))))
752 (defun find-file-noselect (filename &optional nowarn rawfile
)
753 "Read file FILENAME into a buffer and return the buffer.
754 If a buffer exists visiting FILENAME, return that one, but
755 verify that the file has not changed since visited or saved.
756 The buffer is not selected, just returned to the caller."
758 (abbreviate-file-name
759 (expand-file-name filename
)))
760 (if (file-directory-p filename
)
761 (if find-file-run-dired
762 (dired-noselect (if find-file-visit-truename
763 (abbreviate-file-name (file-truename filename
))
765 (error "%s is a directory" filename
))
766 (let* ((buf (get-file-buffer filename
))
767 (truename (abbreviate-file-name (file-truename filename
)))
768 (number (nthcdr 10 (file-attributes truename
)))
769 ;; Find any buffer for a file which has same truename.
770 (other (and (not buf
) (find-buffer-visiting filename
)))
772 ;; Let user know if there is a buffer with the same truename.
776 (string-equal filename
(buffer-file-name other
))
777 (message "%s and %s are the same file"
778 filename
(buffer-file-name other
)))
779 ;; Optionally also find that buffer.
780 (if (or find-file-existing-other-name find-file-visit-truename
)
784 (verify-visited-file-modtime buf
)
785 (cond ((not (file-exists-p filename
))
786 (error "File %s no longer exists!" filename
))
787 ;; Certain files should be reverted automatically
788 ;; if they have changed on disk and not in the buffer.
789 ((and (not (buffer-modified-p buf
))
790 (let ((tail find-file-revert-without-query
)
793 (if (string-match (car tail
) filename
)
795 (setq tail
(cdr tail
)))
797 (with-current-buffer buf
798 (message "Reverting file %s..." filename
)
800 (message "Reverting file %s...done" filename
)))
802 (if (string= (file-name-nondirectory filename
)
805 (if (buffer-modified-p buf
)
806 "File %s changed on disk. Discard your edits? "
807 "File %s changed on disk. Reread from disk? ")
808 (file-name-nondirectory filename
))
810 (if (buffer-modified-p buf
)
811 "File %s changed on disk. Discard your edits in %s? "
812 "File %s changed on disk. Reread from disk into %s? ")
813 (file-name-nondirectory filename
)
815 (with-current-buffer buf
816 (revert-buffer t t
)))))
818 ;;; The truename stuff makes this obsolete.
819 ;;; (let* ((link-name (car (file-attributes filename)))
820 ;;; (linked-buf (and (stringp link-name)
821 ;;; (get-file-buffer link-name))))
822 ;;; (if (bufferp linked-buf)
823 ;;; (message "Symbolic link to file in buffer %s"
824 ;;; (buffer-name linked-buf))))
825 (setq buf
(create-file-buffer filename
))
826 (set-buffer-major-mode buf
)
831 (insert-file-contents-literally filename t
)
833 ;; Unconditionally set error
836 (insert-file-contents filename t
)
838 ;; Run find-file-not-found-hooks until one returns non-nil.
839 (or (run-hook-with-args-until-success 'find-file-not-found-hooks
)
840 ;; If they fail too, set error.
842 ;; Find the file's truename, and maybe use that as visited name.
843 (setq buffer-file-truename truename
)
844 (setq buffer-file-number number
)
845 ;; On VMS, we may want to remember which directory in a search list
846 ;; the file was found in.
847 (and (eq system-type
'vax-vms
)
849 (if (string-match ":" (file-name-directory filename
))
850 (setq logical
(substring (file-name-directory filename
)
851 0 (match-beginning 0))))
852 (not (member logical find-file-not-true-dirname-list
)))
853 (setq buffer-file-name buffer-file-truename
))
854 (if find-file-visit-truename
855 (setq buffer-file-name
857 (expand-file-name buffer-file-truename
))))
858 ;; Set buffer's default directory to that of the file.
859 (setq default-directory
(file-name-directory filename
))
860 ;; Turn off backup files for certain file names. Since
861 ;; this is a permanent local, the major mode won't eliminate it.
862 (and (not (funcall backup-enable-predicate buffer-file-name
))
864 (make-local-variable 'backup-inhibited
)
865 (setq backup-inhibited t
)))
868 (after-find-file error
(not nowarn
))
869 (setq buf
(current-buffer)))))
872 (defvar after-find-file-from-revert-buffer nil
)
874 (defun after-find-file (&optional error warn noauto
875 after-find-file-from-revert-buffer
877 "Called after finding a file and by the default revert function.
878 Sets buffer mode, parses local variables.
879 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
880 error in reading the file. WARN non-nil means warn if there
881 exists an auto-save file more recent than the visited file.
882 NOAUTO means don't mess with auto-save mode.
883 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
884 means this call was from `revert-buffer'.
885 Fifth arg NOMODES non-nil means don't alter the file's modes.
886 Finishes by calling the functions in `find-file-hooks'
887 unless NOMODES is non-nil."
888 (setq buffer-read-only
(not (file-writable-p buffer-file-name
)))
893 (cond ((and error
(file-attributes buffer-file-name
))
894 (setq buffer-read-only t
)
895 "File exists, but cannot be read.")
896 ((not buffer-read-only
)
898 (file-newer-than-file-p (make-auto-save-file-name)
900 (format "%s has auto save data; consider M-x recover-file"
901 (file-name-nondirectory buffer-file-name
))
903 (if error
"(New file)" nil
)))
906 "Note: file is write protected")
907 ((file-attributes (directory-file-name default-directory
))
908 "File not found and directory write-protected")
909 ((file-exists-p (file-name-directory buffer-file-name
))
910 (setq buffer-read-only nil
))
912 (setq buffer-read-only nil
)
913 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name
))))
914 "Use M-x make-dir RET RET to create the directory"
915 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
919 (or not-serious
(sit-for 1 nil t
)))))
920 (if (and auto-save-default
(not noauto
))
925 (run-hooks 'find-file-hooks
)))
927 (defun normal-mode (&optional find-file
)
928 "Choose the major mode for this buffer automatically.
929 Also sets up any specified local variables of the file.
930 Uses the visited file name, the -*- line, and the local variables spec.
932 This function is called automatically from `find-file'. In that case,
933 we may set up specified local variables depending on the value of
934 `enable-local-variables': if it is t, we do; if it is nil, we don't;
935 otherwise, we query. `enable-local-variables' is ignored if you
936 run `normal-mode' explicitly."
938 (or find-file
(funcall (or default-major-mode
'fundamental-mode
)))
941 (error (message "File mode specification error: %s"
942 (prin1-to-string err
))))
944 (let ((enable-local-variables (or (not find-file
)
945 enable-local-variables
)))
946 (hack-local-variables))
947 (error (message "File local-variables error: %s"
948 (prin1-to-string err
)))))
950 (defvar auto-mode-alist
951 '(("\\.te?xt\\'" . text-mode
)
954 ("\\.tex\\'" . tex-mode
)
955 ("\\.ltx\\'" . latex-mode
)
956 ("\\.el\\'" . emacs-lisp-mode
)
957 ("\\.mm\\'" . nroff-mode
)
958 ("\\.me\\'" . nroff-mode
)
959 ("\\.ms\\'" . nroff-mode
)
960 ("\\.man\\'" . nroff-mode
)
961 ("\\.scm\\'" . scheme-mode
)
962 ("\\.l\\'" . lisp-mode
)
963 ("\\.lisp\\'" . lisp-mode
)
964 ("\\.f\\'" . fortran-mode
)
965 ("\\.F\\'" . fortran-mode
)
966 ("\\.for\\'" . fortran-mode
)
967 ("\\.p\\'" . pascal-mode
)
968 ("\\.pas\\'" . pascal-mode
)
969 ("\\.mss\\'" . scribe-mode
)
970 ("\\.ad[abs]\\'" . ada-mode
)
971 ("\\.icn\\'" . icon-mode
)
972 ("\\.pl\\'" . perl-mode
)
973 ("\\.pm\\'" . perl-mode
)
974 ("\\.cc\\'" . c
++-mode
)
975 ("\\.hh\\'" . c
++-mode
)
976 ("\\.hpp\\'" . c
++-mode
)
977 ("\\.C\\'" . c
++-mode
)
978 ("\\.H\\'" . c
++-mode
)
979 ("\\.cpp\\'" . c
++-mode
)
980 ("\\.cxx\\'" . c
++-mode
)
981 ("\\.hxx\\'" . c
++-mode
)
982 ("\\.c\\+\\+\\'" . c
++-mode
)
983 ("\\.h\\+\\+\\'" . c
++-mode
)
984 ("\\.m\\'" . objc-mode
)
985 ("\\.java\\'" . java-mode
)
986 ("\\.sim\\'" . simula-mode
)
987 ("\\.mk\\'" . makefile-mode
)
988 ("\\(M\\|m\\|GNUm\\)akefile\\(.in\\)?\\'" . makefile-mode
)
989 ;;; Less common extensions come here
990 ;;; so more common ones above are found faster.
991 ("\\.texinfo\\'" . texinfo-mode
)
992 ("\\.te?xi\\'" . texinfo-mode
)
993 ("\\.s\\'" . asm-mode
)
994 ("\\.S\\'" . asm-mode
)
995 ("\\.asm\\'" . asm-mode
)
996 ("ChangeLog\\'" . change-log-mode
)
997 ("change.log\\'" . change-log-mode
)
998 ("changelo\\'" . change-log-mode
)
999 ("ChangeLog.[0-9]+\\'" . change-log-mode
)
1000 ;; for MSDOS and MS-Windows (which are case-insensitive)
1001 ("changelog\\'" . change-log-mode
)
1002 ("changelog.[0-9]+\\'" . change-log-mode
)
1003 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode
)
1004 ("\\.scm\\.[0-9]*\\'" . scheme-mode
)
1005 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode
)
1006 ("/\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode
)
1007 ("/\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode
)
1008 ("/\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode
)
1009 ;;; The following should come after the ChangeLog pattern
1010 ;;; for the sake of ChangeLog.1, etc.
1011 ;;; and after the .scm.[0-9] pattern too.
1012 ("\\.[12345678]\\'" . nroff-mode
)
1013 ("\\.TeX\\'" . tex-mode
)
1014 ("\\.sty\\'" . latex-mode
)
1015 ("\\.cls\\'" . latex-mode
) ;LaTeX 2e class
1016 ("\\.bbl\\'" . latex-mode
)
1017 ("\\.bib\\'" . bibtex-mode
)
1018 ("\\.article\\'" . text-mode
)
1019 ("\\.letter\\'" . text-mode
)
1020 ("\\.tcl\\'" . tcl-mode
)
1021 ("\\.exp\\'" . tcl-mode
)
1022 ("\\.itcl\\'" . tcl-mode
)
1023 ("\\.itk\\'" . tcl-mode
)
1024 ("\\.f90\\'" . f90-mode
)
1025 ("\\.lsp\\'" . lisp-mode
)
1026 ("\\.awk\\'" . awk-mode
)
1027 ("\\.prolog\\'" . prolog-mode
)
1028 ("\\.tar\\'" . tar-mode
)
1029 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\)\\'" . archive-mode
)
1030 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\)\\'" . archive-mode
)
1031 ;; Mailer puts message to be edited in
1032 ;; /tmp/Re.... or Message
1033 ("\\`/tmp/Re" . text-mode
)
1034 ("/Message[0-9]*\\'" . text-mode
)
1035 ("/drafts/[0-9]+\\'" . mh-letter-mode
)
1036 ;; some news reader is reported to use this
1037 ("\\`/tmp/fol/" . text-mode
)
1038 ("\\.y\\'" . c-mode
)
1039 ("\\.lex\\'" . c-mode
)
1040 ("\\.oak\\'" . scheme-mode
)
1041 ("\\.sgml?\\'" . sgml-mode
)
1042 ("\\.dtd\\'" . sgml-mode
)
1043 ("\\.s?html?\\'" . html-mode
)
1044 ;; .emacs following a directory delimiter
1045 ;; in either Unix or VMS syntax.
1046 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode
)
1047 ;; _emacs following a directory delimiter
1049 ("[:/]_emacs\\'" . emacs-lisp-mode
)
1050 ("\\.ml\\'" . lisp-mode
))
1052 Alist of filename patterns vs corresponding major mode functions.
1053 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1054 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1055 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1056 mode function to use. FUNCTION will be called, unless it is nil.
1058 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1059 calling FUNCTION (if it's not nil), we delete the suffix that matched
1060 REGEXP and search the list again for another match.")
1062 (defvar interpreter-mode-alist
1063 '(("perl" . perl-mode
)
1064 ("perl5" . perl-mode
)
1066 ("wishx" . tcl-mode
)
1068 ("tclsh" . tcl-mode
)
1073 ("scm" . scheme-mode
)
1091 ("tail" . text-mode
)
1092 ("more" . text-mode
)
1093 ("less" . text-mode
)
1095 "Alist mapping interpreter names to major modes.
1096 This alist applies to files whose first line starts with `#!'.
1097 Each element looks like (INTERPRETER . MODE).
1098 The car of each element is compared with
1099 the name of the interpreter specified in the first line.
1100 If it matches, mode MODE is selected.")
1102 (defvar inhibit-first-line-modes-regexps
'("\\.tar\\'" "\\.tgz\\'")
1103 "List of regexps; if one matches a file name, don't look for `-*-'.")
1105 (defvar inhibit-first-line-modes-suffixes nil
1106 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1107 When checking `inhibit-first-line-modes-regexps', we first discard
1108 from the end of the file name anything that matches one of these regexps.")
1110 (defvar user-init-file
1111 "" ; set by command-line
1112 "File name including directory of user's initialization file.")
1114 (defun set-auto-mode ()
1115 "Select major mode appropriate for current buffer.
1116 This checks for a -*- mode tag in the buffer's text,
1117 compares the filename against the entries in `auto-mode-alist',
1118 or checks the interpreter that runs this file against
1119 `interpreter-mode-alist'.
1121 It does not check for the `mode:' local variable in the
1122 Local Variables section of the file; for that, use `hack-local-variables'.
1124 If `enable-local-variables' is nil, this function does not check for a
1126 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1127 (let (beg end done modes
)
1129 (goto-char (point-min))
1130 (skip-chars-forward " \t\n")
1131 (and enable-local-variables
1132 ;; Don't look for -*- if this file name matches any
1133 ;; of the regexps in inhibit-first-line-modes-regexps.
1134 (let ((temp inhibit-first-line-modes-regexps
)
1135 (name (if buffer-file-name
1136 (file-name-sans-versions buffer-file-name
)
1138 (while (let ((sufs inhibit-first-line-modes-suffixes
))
1139 (while (and sufs
(not (string-match (car sufs
) name
)))
1140 (setq sufs
(cdr sufs
)))
1142 (setq name
(substring name
0 (match-beginning 0))))
1144 (not (string-match (car temp
) name
)))
1145 (setq temp
(cdr temp
)))
1147 (search-forward "-*-" (save-excursion
1148 ;; If the file begins with "#!"
1149 ;; (exec interpreter magic), look
1150 ;; for mode frobs in the first two
1151 ;; lines. You cannot necessarily
1152 ;; put them in the first line of
1153 ;; such a file without screwing up
1154 ;; the interpreter invocation.
1155 (end-of-line (and (looking-at "^#!") 2))
1158 (skip-chars-forward " \t")
1160 (search-forward "-*-"
1161 (save-excursion (end-of-line) (point))
1165 (skip-chars-backward " \t")
1168 (if (save-excursion (search-forward ":" end t
))
1169 ;; Find all specifications for the `mode:' variable
1170 ;; and execute them left to right.
1171 (while (let ((case-fold-search t
))
1172 (or (and (looking-at "mode:")
1173 (goto-char (match-end 0)))
1174 (re-search-forward "[ \t;]mode:" end t
)))
1175 (skip-chars-forward " \t")
1177 (if (search-forward ";" end t
)
1180 (skip-chars-backward " \t")
1181 (setq modes
(cons (intern (concat (downcase (buffer-substring beg
(point))) "-mode"))
1183 ;; Simple -*-MODE-*- case.
1184 (setq modes
(cons (intern (concat (downcase (buffer-substring beg end
))
1187 ;; If we found modes to use, invoke them now,
1188 ;; outside the save-excursion.
1190 (progn (mapcar 'funcall
(nreverse modes
))
1192 ;; If we didn't find a mode from a -*- line, try using the file name.
1193 (if (and (not done
) buffer-file-name
)
1194 (let ((name buffer-file-name
)
1196 ;; Remove backup-suffixes from file name.
1197 (setq name
(file-name-sans-versions name
))
1199 (setq keep-going nil
)
1200 (let ((alist auto-mode-alist
)
1202 ;; Find first matching alist entry.
1203 (let ((case-fold-search
1204 (memq system-type
'(vax-vms windows-nt
))))
1205 (while (and (not mode
) alist
)
1206 (if (string-match (car (car alist
)) name
)
1207 (if (and (consp (cdr (car alist
)))
1208 (nth 2 (car alist
)))
1210 (setq mode
(car (cdr (car alist
)))
1211 name
(substring name
0 (match-beginning 0))
1213 (setq mode
(cdr (car alist
))
1215 (setq alist
(cdr alist
))))
1218 ;; If we can't deduce a mode from the file name,
1219 ;; look for an interpreter specified in the first line.
1220 ;; As a special case, allow for things like "#!/bin/env perl",
1221 ;; which finds the interpreter anywhere in $PATH.
1224 (goto-char (point-min))
1225 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1226 (buffer-substring (match-beginning 2)
1230 ;; Map interpreter name to a mode.
1231 (setq elt
(assoc (file-name-nondirectory interpreter
)
1232 interpreter-mode-alist
))
1234 (funcall (cdr elt
)))))))))))
1236 (defun hack-local-variables-prop-line ()
1237 ;; Set local variables specified in the -*- line.
1238 ;; Ignore any specification for `mode:';
1239 ;; set-auto-mode should already have handled that.
1241 (goto-char (point-min))
1243 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
1244 ;; Parse the -*- line into the `result' alist.
1245 (cond ((not (search-forward "-*-" end t
))
1246 ;; doesn't have one.
1248 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1249 ;; Simple form: "-*- MODENAME -*-". Already handled.
1252 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1253 ;; (last ";" is optional).
1255 (if (search-forward "-*-" end t
)
1256 (setq end
(- (point) 3))
1257 (error "-*- not terminated before end of line")))
1258 (while (< (point) end
)
1259 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1260 (error "malformed -*- line"))
1261 (goto-char (match-end 0))
1262 ;; There used to be a downcase here,
1263 ;; but the manual didn't say so,
1264 ;; and people want to set var names that aren't all lc.
1265 (let ((key (intern (buffer-substring
1268 (val (save-restriction
1269 (narrow-to-region (point) end
)
1270 (read (current-buffer)))))
1271 ;; It is traditional to ignore
1272 ;; case when checking for `mode' in set-auto-mode,
1273 ;; so we must do that here as well.
1274 ;; That is inconsistent, but we're stuck with it.
1275 (or (equal (downcase (symbol-name key
)) "mode")
1276 (setq result
(cons (cons key val
) result
)))
1277 (skip-chars-forward " \t;")))
1278 (setq result
(nreverse result
))))
1281 (or (eq enable-local-variables t
)
1282 (and enable-local-variables
1283 (save-window-excursion
1285 (switch-to-buffer (current-buffer))
1287 ;; If we fail to switch in the selected window,
1288 ;; it is probably a minibuffer.
1289 ;; So try another window.
1291 (switch-to-buffer-other-window (current-buffer))
1293 (switch-to-buffer-other-frame (current-buffer))))))
1294 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1295 (file-name-nondirectory buffer-file-name
)))))))
1296 (let ((enable-local-eval enable-local-eval
))
1298 (hack-one-local-variable (car (car result
)) (cdr (car result
)))
1299 (setq result
(cdr result
))))))))
1301 (defvar hack-local-variables-hook nil
1302 "Normal hook run after processing a file's local variables specs.
1303 Major modes can use this to examine user-specified local variables
1304 in order to initialize other data structure based on them.")
1306 (defun hack-local-variables ()
1307 "Parse and put into effect this buffer's local variables spec."
1308 (hack-local-variables-prop-line)
1309 ;; Look for "Local variables:" line in last page.
1311 (goto-char (point-max))
1312 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move
)
1313 (if (let ((case-fold-search t
))
1314 (and (search-forward "Local Variables:" nil t
)
1315 (or (eq enable-local-variables t
)
1316 (and enable-local-variables
1317 (save-window-excursion
1318 (switch-to-buffer (current-buffer))
1321 (set-window-start (selected-window) (point)))
1322 (y-or-n-p (format "Set local variables as specified at end of %s? "
1323 (if buffer-file-name
1324 (file-name-nondirectory
1327 (buffer-name))))))))))
1329 prefix prefixlen suffix beg
1330 (enable-local-eval enable-local-eval
))
1331 ;; The prefix is what comes before "local variables:" in its line.
1332 ;; The suffix is what comes after "local variables:" in its line.
1333 (skip-chars-forward " \t")
1335 (setq suffix
(buffer-substring (point)
1336 (progn (end-of-line) (point)))))
1337 (goto-char (match-beginning 0))
1340 (buffer-substring (point)
1341 (progn (beginning-of-line) (point)))))
1343 (if prefix
(setq prefixlen
(length prefix
)
1344 prefix
(regexp-quote prefix
)))
1345 (if suffix
(setq suffix
(concat (regexp-quote suffix
) "$")))
1347 ;; Look at next local variable spec.
1348 (if selective-display
(re-search-forward "[\n\C-m]")
1350 ;; Skip the prefix, if any.
1352 (if (looking-at prefix
)
1353 (forward-char prefixlen
)
1354 (error "Local variables entry is missing the prefix")))
1355 ;; Find the variable name; strip whitespace.
1356 (skip-chars-forward " \t")
1358 (skip-chars-forward "^:\n")
1359 (if (eolp) (error "Missing colon in local variables entry"))
1360 (skip-chars-backward " \t")
1361 (let* ((str (buffer-substring beg
(point)))
1364 ;; Setting variable named "end" means end of list.
1365 (if (string-equal (downcase str
) "end")
1367 ;; Otherwise read the variable value.
1368 (skip-chars-forward "^:")
1370 (setq val
(read (current-buffer)))
1371 (skip-chars-backward "\n")
1372 (skip-chars-forward " \t")
1373 (or (if suffix
(looking-at suffix
) (eolp))
1374 (error "Local variables entry is terminated incorrectly"))
1375 ;; Set the variable. "Variables" mode and eval are funny.
1376 (hack-one-local-variable var val
)))))))
1377 (run-hooks 'hack-local-variables-hook
))
1379 (defvar ignored-local-variables
1380 '(enable-local-eval)
1381 "Variables to be ignored in a file's local variable spec.")
1383 ;; Get confirmation before setting these variables as locals in a file.
1384 (put 'debugger
'risky-local-variable t
)
1385 (put 'enable-local-eval
'risky-local-variable t
)
1386 (put 'ignored-local-variables
'risky-local-variable t
)
1387 (put 'eval
'risky-local-variable t
)
1388 (put 'file-name-handler-alist
'risky-local-variable t
)
1389 (put 'minor-mode-map-alist
'risky-local-variable t
)
1390 (put 'after-load-alist
'risky-local-variable t
)
1391 (put 'buffer-file-name
'risky-local-variable t
)
1392 (put 'buffer-auto-save-file-name
'risky-local-variable t
)
1393 (put 'buffer-file-truename
'risky-local-variable t
)
1394 (put 'exec-path
'risky-local-variable t
)
1395 (put 'load-path
'risky-local-variable t
)
1396 (put 'exec-directory
'risky-local-variable t
)
1397 (put 'process-environment
'risky-local-variable t
)
1398 (put 'dabbrev-case-fold-search
'risky-local-variable t
)
1399 (put 'dabbrev-case-replace
'risky-local-variable t
)
1400 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1401 (put 'outline-level
'risky-local-variable t
)
1402 (put 'rmail-output-file-alist
'risky-local-variable t
)
1404 ;; This one is safe because the user gets to check it before it is used.
1405 (put 'compile-command
'safe-local-variable t
)
1407 (defun hack-one-local-variable-quotep (exp)
1408 (and (consp exp
) (eq (car exp
) 'quote
) (consp (cdr exp
))))
1410 ;; "Set" one variable in a local variables spec.
1411 ;; A few variable names are treated specially.
1412 (defun hack-one-local-variable (var val
)
1413 (cond ((eq var
'mode
)
1414 (funcall (intern (concat (downcase (symbol-name val
))
1416 ((memq var ignored-local-variables
)
1418 ;; "Setting" eval means either eval it or do nothing.
1419 ;; Likewise for setting hook variables.
1420 ((or (get var
'risky-local-variable
)
1422 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
1424 (not (get var
'safe-local-variable
))))
1425 ;; Permit evalling a put of a harmless property.
1426 ;; if the args do nothing tricky.
1427 (if (or (and (eq var
'eval
)
1430 (hack-one-local-variable-quotep (nth 1 val
))
1431 (hack-one-local-variable-quotep (nth 2 val
))
1432 ;; Only allow safe values of lisp-indent-hook;
1434 (or (numberp (nth 3 val
))
1435 (equal (nth 3 val
) ''defun
))
1436 (memq (nth 1 (nth 2 val
))
1437 '(lisp-indent-hook)))
1438 ;; Permit eval if not root and user says ok.
1439 (and (not (zerop (user-uid)))
1440 (or (eq enable-local-eval t
)
1441 (and enable-local-eval
1442 (save-window-excursion
1443 (switch-to-buffer (current-buffer))
1446 (set-window-start (selected-window) (point)))
1447 (setq enable-local-eval
1448 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1449 (file-name-nondirectory buffer-file-name
)))))))))
1451 (save-excursion (eval val
))
1452 (make-local-variable var
)
1454 (message "Ignoring `eval:' in file's local variables")))
1455 ;; Ordinary variable, really set it.
1456 (t (make-local-variable var
)
1460 (defun set-visited-file-name (filename &optional no-query
)
1461 "Change name of file visited in current buffer to FILENAME.
1462 The next time the buffer is saved it will go in the newly specified file.
1463 nil or empty string as argument means make buffer not be visiting any file.
1464 Remember to delete the initial contents of the minibuffer
1465 if you wish to pass an empty string as the argument.
1467 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1468 confirmation in the case where another buffer is already visiting FILENAME."
1469 (interactive "FSet visited file name: ")
1470 (if (buffer-base-buffer)
1471 (error "An indirect buffer cannot visit a file"))
1475 (if (string-equal filename
"")
1477 (expand-file-name filename
))))
1480 (setq truename
(file-truename filename
))
1481 (if find-file-visit-truename
1482 (setq filename truename
))))
1483 (let ((buffer (and filename
(find-buffer-visiting filename
))))
1484 (and buffer
(not (eq buffer
(current-buffer)))
1486 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1489 (or (equal filename buffer-file-name
)
1491 (and filename
(lock-buffer filename
))
1493 (setq buffer-file-name filename
)
1494 (if filename
; make buffer name reflect filename.
1495 (let ((new-name (file-name-nondirectory buffer-file-name
)))
1496 (if (string= new-name
"")
1497 (error "Empty file name"))
1498 (if (eq system-type
'vax-vms
)
1499 (setq new-name
(downcase new-name
)))
1500 (setq default-directory
(file-name-directory buffer-file-name
))
1501 (or (string= new-name
(buffer-name))
1502 (rename-buffer new-name t
))))
1503 (setq buffer-backed-up nil
)
1504 (clear-visited-file-modtime)
1505 ;; Abbreviate the file names of the buffer.
1508 (setq buffer-file-truename
(abbreviate-file-name truename
))
1509 (if find-file-visit-truename
1510 (setq buffer-file-name buffer-file-truename
))))
1511 (setq buffer-file-number
1513 (nthcdr 10 (file-attributes buffer-file-name
))
1515 ;; write-file-hooks is normally used for things like ftp-find-file
1516 ;; that visit things that are not local files as if they were files.
1517 ;; Changing to visit an ordinary local file instead should flush the hook.
1518 (kill-local-variable 'write-file-hooks
)
1519 (kill-local-variable 'local-write-file-hooks
)
1520 (kill-local-variable 'revert-buffer-function
)
1521 (kill-local-variable 'backup-inhibited
)
1522 ;; If buffer was read-only because of version control,
1523 ;; that reason is gone now, so make it writable.
1525 (setq buffer-read-only nil
))
1526 (kill-local-variable 'vc-mode
)
1527 ;; Turn off backup files for certain file names.
1528 ;; Since this is a permanent local, the major mode won't eliminate it.
1529 (and (not (funcall backup-enable-predicate buffer-file-name
))
1531 (make-local-variable 'backup-inhibited
)
1532 (setq backup-inhibited t
)))
1533 (let ((oauto buffer-auto-save-file-name
))
1534 ;; If auto-save was not already on, turn it on if appropriate.
1535 (if (not buffer-auto-save-file-name
)
1536 (and buffer-file-name auto-save-default
1538 ;; If auto save is on, start using a new name.
1539 ;; We deliberately don't rename or delete the old auto save
1540 ;; for the old visited file name. This is because perhaps
1541 ;; the user wants to save the new state and then compare with the
1542 ;; previous state from the auto save file.
1543 (setq buffer-auto-save-file-name
1544 (make-auto-save-file-name)))
1545 ;; Rename the old auto save file if any.
1546 (and oauto buffer-auto-save-file-name
1547 (file-exists-p oauto
)
1548 (rename-file oauto buffer-auto-save-file-name t
)))
1549 (if buffer-file-name
1550 (set-buffer-modified-p t
)))
1552 (defun write-file (filename &optional confirm
)
1553 "Write current buffer into file FILENAME.
1554 Makes buffer visit that file, and marks it not modified.
1555 If the buffer is already visiting a file, you can specify
1556 a directory name as FILENAME, to write a file of the same
1557 old name in that directory.
1559 If optional second arg CONFIRM is non-nil,
1560 ask for confirmation for overwriting an existing file.
1561 Interactively, confirmation is required unless you supply a prefix argument."
1562 ;; (interactive "FWrite file: ")
1564 (list (if buffer-file-name
1565 (read-file-name "Write file: "
1567 (read-file-name "Write file: "
1568 (cdr (assq 'default-directory
1569 (buffer-local-variables)))
1570 nil nil
(buffer-name)))
1571 (not current-prefix-arg
)))
1572 (or (null filename
) (string-equal filename
"")
1574 ;; If arg is just a directory,
1575 ;; use same file name, but in that directory.
1576 (if (and (file-directory-p filename
) buffer-file-name
)
1577 (setq filename
(concat (file-name-as-directory filename
)
1578 (file-name-nondirectory buffer-file-name
))))
1580 (file-exists-p filename
)
1581 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename
))
1582 (error "Canceled")))
1583 (set-visited-file-name filename
(not confirm
))))
1584 (set-buffer-modified-p t
)
1587 (defun backup-buffer ()
1588 "Make a backup of the disk file visited by the current buffer, if appropriate.
1589 This is normally done before saving the buffer the first time.
1590 If the value is non-nil, it is the result of `file-modes' on the original
1591 file; this means that the caller, after saving the buffer, should change
1592 the modes of the new file to agree with the old modes.
1594 A backup may be done by renaming or by copying; see documentation of
1595 variable `make-backup-files'. If it's done by renaming, then the file is
1596 no longer accessible under its old name."
1597 (if (and make-backup-files
(not backup-inhibited
)
1598 (not buffer-backed-up
)
1599 (file-exists-p buffer-file-name
)
1600 (memq (aref (elt (file-attributes buffer-file-name
) 8) 0)
1602 (let ((real-file-name buffer-file-name
)
1603 backup-info backupname targets setmodes
)
1604 ;; If specified name is a symbolic link, chase it to the target.
1605 ;; Thus we make the backups in the directory where the real file is.
1606 (setq real-file-name
(file-chase-links real-file-name
))
1607 (setq backup-info
(find-backup-file-name real-file-name
)
1608 backupname
(car backup-info
)
1609 targets
(cdr backup-info
))
1610 ;;; (if (file-directory-p buffer-file-name)
1611 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1614 (let ((delete-old-versions
1615 ;; If have old versions to maybe delete,
1616 ;; ask the user to confirm now, before doing anything.
1617 ;; But don't actually delete til later.
1619 (or (eq delete-old-versions t
) (eq delete-old-versions nil
))
1620 (or delete-old-versions
1621 (y-or-n-p (format "Delete excess backup versions of %s? "
1622 real-file-name
))))))
1623 ;; Actually write the back up file.
1625 (if (or file-precious-flag
1626 ; (file-symlink-p buffer-file-name)
1628 (and backup-by-copying-when-linked
1629 (> (file-nlinks real-file-name
) 1))
1630 (and backup-by-copying-when-mismatch
1631 (let ((attr (file-attributes real-file-name
)))
1633 (not (file-ownership-preserved-p real-file-name
))))))
1635 (copy-file real-file-name backupname t t
)
1637 ;; If copying fails because file BACKUPNAME
1638 ;; is not writable, delete that file and try again.
1639 (if (and (file-exists-p backupname
)
1640 (not (file-writable-p backupname
)))
1641 (delete-file backupname
))
1642 (copy-file real-file-name backupname t t
)))
1643 ;; rename-file should delete old backup.
1644 (rename-file real-file-name backupname t
)
1645 (setq setmodes
(file-modes backupname
)))
1647 ;; If trouble writing the backup, write it in ~.
1648 (setq backupname
(expand-file-name
1649 (convert-standard-filename
1651 (message "Cannot write backup file; backing up in %s"
1652 (file-name-nondirectory backupname
))
1655 (copy-file real-file-name backupname t t
)
1657 ;; If copying fails because file BACKUPNAME
1658 ;; is not writable, delete that file and try again.
1659 (if (and (file-exists-p backupname
)
1660 (not (file-writable-p backupname
)))
1661 (delete-file backupname
))
1662 (copy-file real-file-name backupname t t
)))))
1663 (setq buffer-backed-up t
)
1664 ;; Now delete the old versions, if desired.
1665 (if delete-old-versions
1668 (delete-file (car targets
))
1670 (setq targets
(cdr targets
))))
1672 (file-error nil
))))))
1674 (defun file-name-sans-versions (name &optional keep-backup-version
)
1675 "Return FILENAME sans backup versions or strings.
1676 This is a separate procedure so your site-init or startup file can
1678 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1679 we do not remove backup version numbers, only true file version numbers."
1680 (let ((handler (find-file-name-handler name
'file-name-sans-versions
)))
1682 (funcall handler
'file-name-sans-versions name keep-backup-version
)
1684 (if (eq system-type
'vax-vms
)
1685 ;; VMS version number is (a) semicolon, optional
1686 ;; sign, zero or more digits or (b) period, option
1687 ;; sign, zero or more digits, provided this is the
1688 ;; second period encountered outside of the
1689 ;; device/directory part of the file name.
1690 (or (string-match ";[-+]?[0-9]*\\'" name
)
1691 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1693 (match-beginning 1))
1695 (if keep-backup-version
1697 (or (string-match "\\.~[0-9.]+~\\'" name
)
1698 (string-match "~\\'" name
)
1699 (length name
))))))))
1701 (defun file-ownership-preserved-p (file)
1702 "Returns t if deleting FILE and rewriting it would preserve the owner."
1703 (let ((handler (find-file-name-handler file
'file-ownership-preserved-p
)))
1705 (funcall handler
'file-ownership-preserved-p file
)
1706 (let ((attributes (file-attributes file
)))
1707 ;; Return t if the file doesn't exist, since it's true that no
1708 ;; information would be lost by an (attempted) delete and create.
1709 (or (null attributes
)
1710 (= (nth 2 attributes
) (user-uid)))))))
1712 (defun file-name-sans-extension (filename)
1713 "Return FILENAME sans final \"extension\".
1714 The extension, in a file name, is the part that follows the last `.'."
1716 (let ((file (file-name-sans-versions (file-name-nondirectory filename
)))
1718 (if (string-match "\\.[^.]*\\'" file
)
1719 (if (setq directory
(file-name-directory filename
))
1720 (expand-file-name (substring file
0 (match-beginning 0))
1722 (substring file
0 (match-beginning 0)))
1725 (defun file-name-extension (filename &optional period
)
1726 "Return FILENAME's final \"extension\".
1727 The extension, in a file name, is the part that follows the last `.'.
1728 Return nil for extensionless file names such as `foo'.
1729 Return the empty string for file names such as `foo.'.
1731 If PERIOD is non-nil, then the returned value includes the period
1732 that delimits the extension, and if FILENAME has no extension,
1735 (let ((file (file-name-sans-versions (file-name-nondirectory filename
))))
1736 (if (string-match "\\.[^.]*\\'" file
)
1737 (substring file
(+ (match-beginning 0) (if period
0 1)))
1741 (defun make-backup-file-name (file)
1742 "Create the non-numeric backup file name for FILE.
1743 This is a separate function so you can redefine it for customization."
1744 (if (and (eq system-type
'ms-dos
)
1745 (not (msdos-long-file-names)))
1746 (let ((fn (file-name-nondirectory file
)))
1747 (concat (file-name-directory file
)
1749 (and (string-match "\\`[^.]+\\'" fn
)
1750 (concat (match-string 0 fn
) ".~"))
1751 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn
)
1752 (concat (match-string 0 fn
) "~")))))
1755 (defun backup-file-name-p (file)
1756 "Return non-nil if FILE is a backup file name (numeric or not).
1757 This is a separate function so you can redefine it for customization.
1758 You may need to redefine `file-name-sans-versions' as well."
1759 (string-match "~\\'" file
))
1761 ;; This is used in various files.
1762 ;; The usage of bv-length is not very clean,
1763 ;; but I can't see a good alternative,
1764 ;; so as of now I am leaving it alone.
1765 (defun backup-extract-version (fn)
1766 "Given the name of a numeric backup file, return the backup number.
1767 Uses the free variable `bv-length', whose value should be
1768 the index in the name where the version number begins."
1769 (if (and (string-match "[0-9]+~$" fn bv-length
)
1770 (= (match-beginning 0) bv-length
))
1771 (string-to-int (substring fn bv-length -
1))
1774 ;; I believe there is no need to alter this behavior for VMS;
1775 ;; since backup files are not made on VMS, it should not get called.
1776 (defun find-backup-file-name (fn)
1777 "Find a file name for a backup file, and suggestions for deletions.
1778 Value is a list whose car is the name for the backup file
1779 and whose cdr is a list of old versions to consider deleting now.
1780 If the value is nil, don't make a backup."
1781 (let ((handler (find-file-name-handler fn
'find-backup-file-name
)))
1782 ;; Run a handler for this function so that ange-ftp can refuse to do it.
1784 (funcall handler
'find-backup-file-name fn
)
1785 (if (eq version-control
'never
)
1786 (list (make-backup-file-name fn
))
1787 (let* ((base-versions (concat (file-name-nondirectory fn
) ".~"))
1788 (bv-length (length base-versions
))
1792 (deserve-versions-p nil
)
1793 (number-to-delete 0))
1795 (setq possibilities
(file-name-all-completions
1797 (file-name-directory fn
))
1798 versions
(sort (mapcar
1799 (function backup-extract-version
)
1802 high-water-mark
(apply 'max
0 versions
)
1803 deserve-versions-p
(or version-control
1804 (> high-water-mark
0))
1805 number-to-delete
(- (length versions
)
1806 kept-old-versions kept-new-versions -
1))
1808 (setq possibilities nil
)))
1809 (if (not deserve-versions-p
)
1810 (list (make-backup-file-name fn
))
1811 (cons (concat fn
".~" (int-to-string (1+ high-water-mark
)) "~")
1812 (if (and (> number-to-delete
0)
1813 ;; Delete nothing if there is overflow
1814 ;; in the number of versions to keep.
1815 (>= (+ kept-new-versions kept-old-versions -
1) 0))
1816 (mapcar (function (lambda (n)
1817 (concat fn
".~" (int-to-string n
) "~")))
1818 (let ((v (nthcdr kept-old-versions versions
)))
1819 (rplacd (nthcdr (1- number-to-delete
) v
) ())
1822 (defun file-nlinks (filename)
1823 "Return number of names file FILENAME has."
1824 (car (cdr (file-attributes filename
))))
1826 (defun file-relative-name (filename &optional directory
)
1827 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1828 (setq filename
(expand-file-name filename
)
1829 directory
(file-name-as-directory (expand-file-name
1830 (or directory default-directory
))))
1831 (let ((ancestor ""))
1832 (while (not (string-match (concat "^" (regexp-quote directory
)) filename
))
1833 (setq directory
(file-name-directory (substring directory
0 -
1))
1834 ancestor
(concat "../" ancestor
)))
1835 (concat ancestor
(substring filename
(match-end 0)))))
1837 (defun save-buffer (&optional args
)
1838 "Save current buffer in visited file if modified. Versions described below.
1839 By default, makes the previous version into a backup file
1840 if previously requested or if this is the first save.
1841 With 1 \\[universal-argument], marks this version
1842 to become a backup when the next save is done.
1843 With 2 \\[universal-argument]'s,
1844 unconditionally makes the previous version into a backup file.
1845 With 3 \\[universal-argument]'s, marks this version
1846 to become a backup when the next save is done,
1847 and unconditionally makes the previous version into a backup file.
1849 With argument of 0, never makes the previous version into a backup file.
1851 If a file's name is FOO, the names of its numbered backup versions are
1852 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1853 Numeric backups (rather than FOO~) will be made if value of
1854 `version-control' is not the atom `never' and either there are already
1855 numeric versions of the file being backed up, or `version-control' is
1857 We don't want excessive versions piling up, so there are variables
1858 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1859 and `kept-new-versions', which tells how many newest versions to keep.
1860 Defaults are 2 old versions and 2 new.
1861 `dired-kept-versions' controls dired's clean-directory (.) command.
1862 If `delete-old-versions' is nil, system will query user
1863 before trimming versions. Otherwise it does it silently."
1865 (let ((modp (buffer-modified-p))
1866 (large (> (buffer-size) 50000))
1867 (make-backup-files (or (and make-backup-files
(not (eq args
0)))
1868 (memq args
'(16 64)))))
1869 (and modp
(memq args
'(16 64)) (setq buffer-backed-up nil
))
1870 (if (and modp large
) (message "Saving file %s..." (buffer-file-name)))
1872 (and modp
(memq args
'(4 64)) (setq buffer-backed-up nil
))))
1874 (defun delete-auto-save-file-if-necessary (&optional force
)
1875 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1876 Normally delete only if the file was written by this Emacs since
1877 the last real save, but optional arg FORCE non-nil means delete anyway."
1878 (and buffer-auto-save-file-name delete-auto-save-files
1879 (not (string= buffer-file-name buffer-auto-save-file-name
))
1880 (or force
(recent-auto-save-p))
1883 (delete-file buffer-auto-save-file-name
)
1885 (set-buffer-auto-saved))))
1887 (defvar after-save-hook nil
1888 "Normal hook that is run after a buffer is saved to its file.")
1890 (defun basic-save-buffer ()
1891 "Save the current buffer in its visited file, if it has been modified.
1892 After saving the buffer, run `after-save-hook'."
1895 ;; In an indirect buffer, save its base buffer instead.
1896 (if (buffer-base-buffer)
1897 (set-buffer (buffer-base-buffer)))
1898 (if (buffer-modified-p)
1899 (let ((recent-save (recent-auto-save-p))
1900 setmodes tempsetmodes
)
1901 ;; On VMS, rename file and buffer to get rid of version number.
1902 (if (and (eq system-type
'vax-vms
)
1903 (not (string= buffer-file-name
1904 (file-name-sans-versions buffer-file-name
))))
1905 (let (buffer-new-name)
1906 ;; Strip VMS version number before save.
1907 (setq buffer-file-name
1908 (file-name-sans-versions buffer-file-name
))
1909 ;; Construct a (unique) buffer name to correspond.
1910 (let ((buf (create-file-buffer (downcase buffer-file-name
))))
1911 (setq buffer-new-name
(buffer-name buf
))
1913 (rename-buffer buffer-new-name
)))
1914 ;; If buffer has no file name, ask user for one.
1915 (or buffer-file-name
1918 (read-file-name "File to save in: ") nil
)))
1919 (and (file-exists-p filename
)
1920 (or (y-or-n-p (format "File `%s' exists; overwrite? "
1922 (error "Canceled")))
1923 (set-visited-file-name filename
)))
1924 (or (verify-visited-file-modtime (current-buffer))
1925 (not (file-exists-p buffer-file-name
))
1927 (format "%s has changed since visited or saved. Save anyway? "
1928 (file-name-nondirectory buffer-file-name
)))
1929 (error "Save not confirmed"))
1932 (and (> (point-max) 1)
1933 (/= (char-after (1- (point-max))) ?
\n)
1934 (not (and (eq selective-display t
)
1935 (= (char-after (1- (point-max))) ?
\r)))
1936 (or (eq require-final-newline t
)
1937 (and require-final-newline
1939 (format "Buffer %s does not end in newline. Add one? "
1942 (goto-char (point-max))
1944 (or (run-hook-with-args-until-success 'write-contents-hooks
)
1945 (run-hook-with-args-until-success 'local-write-file-hooks
)
1946 (run-hook-with-args-until-success 'write-file-hooks
)
1947 ;; If a hook returned t, file is already "written".
1948 ;; Otherwise, write it the usual way now.
1949 (setq setmodes
(basic-save-buffer-1)))
1950 (setq buffer-file-number
1951 (nthcdr 10 (file-attributes buffer-file-name
)))
1954 (set-file-modes buffer-file-name setmodes
)
1956 ;; If the auto-save file was recent before this command,
1958 (delete-auto-save-file-if-necessary recent-save
)
1959 ;; Support VC `implicit' locking.
1961 (run-hooks 'after-save-hook
))
1962 (message "(No changes need to be saved)"))))
1964 ;; This does the "real job" of writing a buffer into its visited file
1965 ;; and making a backup file. This is what is normally done
1966 ;; but inhibited if one of write-file-hooks returns non-nil.
1967 ;; It returns a value to store in setmodes.
1968 (defun basic-save-buffer-1 ()
1969 (let (tempsetmodes setmodes
)
1970 (if (not (file-writable-p buffer-file-name
))
1971 (let ((dir (file-name-directory buffer-file-name
)))
1972 (if (not (file-directory-p dir
))
1973 (error "%s is not a directory" dir
)
1974 (if (not (file-exists-p buffer-file-name
))
1975 (error "Directory %s write-protected" dir
)
1977 (format "File %s is write-protected; try to save anyway? "
1978 (file-name-nondirectory
1980 (setq tempsetmodes t
)
1981 (error "Attempt to save to a file which you aren't allowed to write"))))))
1982 (or buffer-backed-up
1983 (setq setmodes
(backup-buffer)))
1984 (let ((dir (file-name-directory buffer-file-name
)))
1985 (if (and file-precious-flag
1986 (file-writable-p dir
))
1987 ;; If file is precious, write temp name, then rename it.
1988 ;; This requires write access to the containing dir,
1989 ;; which is why we don't try it if we don't have that access.
1990 (let ((realname buffer-file-name
)
1991 tempname temp nogood i succeed
1992 (old-modtime (visited-file-modtime)))
1995 ;; Find the temporary name to write under.
1997 (setq tempname
(format
1998 (if (and (eq system-type
'ms-dos
)
1999 (not (msdos-long-file-names)))
2000 "%s#%d.tm#" ; MSDOS limits files to 8+3
2003 (setq nogood
(file-exists-p tempname
))
2006 (progn (clear-visited-file-modtime)
2007 (write-region (point-min) (point-max)
2008 tempname nil realname
2009 buffer-file-truename
)
2011 ;; If writing the temp file fails,
2012 ;; delete the temp file.
2015 (delete-file tempname
)
2016 (set-visited-file-modtime old-modtime
))))
2017 ;; Since we have created an entirely new file
2018 ;; and renamed it, make sure it gets the
2019 ;; right permission bits set.
2020 (setq setmodes
(file-modes buffer-file-name
))
2021 ;; We succeeded in writing the temp file,
2023 (rename-file tempname buffer-file-name t
))
2024 ;; If file not writable, see if we can make it writable
2025 ;; temporarily while we write it.
2026 ;; But no need to do so if we have just backed it up
2027 ;; (setmodes is set) because that says we're superseding.
2028 (cond ((and tempsetmodes
(not setmodes
))
2029 ;; Change the mode back, after writing.
2030 (setq setmodes
(file-modes buffer-file-name
))
2031 (set-file-modes buffer-file-name
511)))
2032 (write-region (point-min) (point-max)
2033 buffer-file-name nil t buffer-file-truename
)))
2036 (defun save-some-buffers (&optional arg exiting
)
2037 "Save some modified file-visiting buffers. Asks user about each one.
2038 Optional argument (the prefix) non-nil means save all with no questions.
2039 Optional second argument EXITING means ask about certain non-file buffers
2040 as well as about file buffers."
2042 (save-window-excursion
2043 (let* ((queried nil
)
2048 (and (buffer-modified-p buffer
)
2049 (not (buffer-base-buffer buffer
))
2051 (buffer-file-name buffer
)
2055 (and buffer-offer-save
(> (buffer-size) 0)))))
2059 (if (buffer-file-name buffer
)
2060 (format "Save file %s? "
2061 (buffer-file-name buffer
))
2062 (format "Save buffer %s? "
2063 (buffer-name buffer
)))))))
2069 '("buffer" "buffers" "save")
2070 (list (list ?\C-r
(lambda (buf)
2072 (setq view-exit-action
2074 (exit-recursive-edit)))
2076 ;; Return nil to ask about BUF again.
2078 "display the current buffer"))))
2080 (and save-abbrevs abbrevs-changed
2083 (y-or-n-p (format "Save abbrevs in %s? "
2085 (write-abbrev-file nil
))
2086 ;; Don't keep bothering user if he says no.
2087 (setq abbrevs-changed nil
)
2089 (or queried
(> files-done
0) abbrevs-done
2090 (message "(No files need saving)")))))
2092 (defun not-modified (&optional arg
)
2093 "Mark current buffer as unmodified, not needing to be saved.
2094 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2096 It is not a good idea to use this function in Lisp programs, because it
2097 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2099 (message (if arg
"Modification-flag set"
2100 "Modification-flag cleared"))
2101 (set-buffer-modified-p arg
))
2103 (defun toggle-read-only (&optional arg
)
2104 "Change whether this buffer is visiting its file read-only.
2105 With arg, set read-only iff arg is positive."
2107 (setq buffer-read-only
2109 (not buffer-read-only
)
2110 (> (prefix-numeric-value arg
) 0)))
2111 (force-mode-line-update))
2113 (defun insert-file (filename)
2114 "Insert contents of file FILENAME into buffer after point.
2115 Set mark after the inserted text.
2117 This function is meant for the user to run interactively.
2118 Don't call it from programs! Use `insert-file-contents' instead.
2119 \(Its calling sequence is different; see its documentation)."
2120 (interactive "*fInsert file: ")
2121 (if (file-directory-p filename
)
2122 (signal 'file-error
(list "Opening input file" "file is a directory"
2124 (let ((tem (insert-file-contents filename
)))
2125 (push-mark (+ (point) (car (cdr tem
))))))
2127 (defun append-to-file (start end filename
)
2128 "Append the contents of the region to the end of file FILENAME.
2129 When called from a function, expects three arguments,
2130 START, END and FILENAME. START and END are buffer positions
2131 saying what text to write."
2132 (interactive "r\nFAppend to file: ")
2133 (write-region start end filename t
))
2135 (defun file-newest-backup (filename)
2136 "Return most recent backup file for FILENAME or nil if no backups exist."
2137 (let* ((filename (expand-file-name filename
))
2138 (file (file-name-nondirectory filename
))
2139 (dir (file-name-directory filename
))
2140 (comp (file-name-all-completions file dir
))
2144 (setq tem
(car comp
)
2146 (cond ((and (backup-file-name-p tem
)
2147 (string= (file-name-sans-versions tem
) file
))
2148 (setq tem
(concat dir tem
))
2149 (if (or (null newest
)
2150 (file-newer-than-file-p tem newest
))
2151 (setq newest tem
)))))
2154 (defun rename-uniquely ()
2155 "Rename current buffer to a similar name not already taken.
2156 This function is useful for creating multiple shell process buffers
2157 or multiple mail buffers, etc."
2160 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2161 (not (and buffer-file-name
2162 (string= (buffer-name)
2163 (file-name-nondirectory
2164 buffer-file-name
)))))
2165 ;; If the existing buffer name has a <NNN>,
2166 ;; which isn't part of the file name (if any),
2167 ;; then get rid of that.
2168 (substring (buffer-name) 0 (match-beginning 0))
2170 (new-buf (generate-new-buffer base-name
))
2171 (name (buffer-name new-buf
)))
2172 (kill-buffer new-buf
)
2173 (rename-buffer name
)
2174 (force-mode-line-update))))
2176 (defun make-directory (dir &optional parents
)
2177 "Create the directory DIR and any nonexistent parent dirs.
2178 Interactively, the default choice of directory to create
2179 is the current default directory for file names.
2180 That is useful when you have visited a file in a nonexistent directory.
2182 Noninteractively, the second (optional) argument PARENTS says whether
2183 to create parent directories if they don't exist."
2185 (list (read-file-name "Make directory: " default-directory default-directory
2188 (let ((handler (find-file-name-handler dir
'make-directory
)))
2190 (funcall handler
'make-directory dir parents
)
2192 (make-directory-internal dir
)
2193 (let ((dir (directory-file-name (expand-file-name dir
)))
2195 (while (not (file-exists-p dir
))
2196 (setq create-list
(cons dir create-list
)
2197 dir
(directory-file-name (file-name-directory dir
))))
2199 (make-directory-internal (car create-list
))
2200 (setq create-list
(cdr create-list
))))))))
2202 (put 'revert-buffer-function
'permanent-local t
)
2203 (defvar revert-buffer-function nil
2204 "Function to use to revert this buffer, or nil to do the default.
2205 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2206 which are the arguments that `revert-buffer' received.")
2208 (put 'revert-buffer-insert-file-contents-function
'permanent-local t
)
2209 (defvar revert-buffer-insert-file-contents-function nil
2210 "Function to use to insert contents when reverting this buffer.
2211 Gets two args, first the nominal file name to use,
2212 and second, t if reading the auto-save file.")
2214 (defvar before-revert-hook nil
2215 "Normal hook for `revert-buffer' to run before reverting.
2216 If `revert-buffer-function' is used to override the normal revert
2217 mechanism, this hook is not used.")
2219 (defvar after-revert-hook nil
2220 "Normal hook for `revert-buffer' to run after reverting.
2221 Note that the hook value that it runs is the value that was in effect
2222 before reverting; that makes a difference if you have buffer-local
2225 If `revert-buffer-function' is used to override the normal revert
2226 mechanism, this hook is not used.")
2228 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes
)
2229 "Replace current buffer text with the text of the visited file on disk.
2230 This undoes all changes since the file was visited or saved.
2231 With a prefix argument, offer to revert from latest auto-save file, if
2232 that is more recent than the visited file.
2234 This command also works for special buffers that contain text which
2235 doesn't come from a file, but reflects some other data base instead:
2236 for example, Dired buffers and buffer-list buffers. In these cases,
2237 it reconstructs the buffer contents from the appropriate data base.
2239 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2240 to revert from the auto-save file when this is nil. Note that the
2241 sense of this argument is the reverse of the prefix argument, for the
2242 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2245 Optional second argument NOCONFIRM means don't ask for confirmation at
2248 Optional third argument PRESERVE-MODES non-nil means don't alter
2249 the files modes. Normally we reinitialize them using `normal-mode'.
2251 If the value of `revert-buffer-function' is non-nil, it is called to
2252 do all the work for this command. Otherwise, the hooks
2253 `before-revert-hook' and `after-revert-hook' are run at the beginning
2254 and the end, and if `revert-buffer-insert-file-contents-function' is
2255 non-nil, it is called instead of rereading visited file contents."
2257 ;; I admit it's odd to reverse the sense of the prefix argument, but
2258 ;; there is a lot of code out there which assumes that the first
2259 ;; argument should be t to avoid consulting the auto-save file, and
2260 ;; there's no straightforward way to encourage authors to notice a
2261 ;; reversal of the argument sense. So I'm just changing the user
2262 ;; interface, but leaving the programmatic interface the same.
2263 (interactive (list (not current-prefix-arg
)))
2264 (if revert-buffer-function
2265 (funcall revert-buffer-function ignore-auto noconfirm
)
2266 (let* ((opoint (point))
2267 (auto-save-p (and (not ignore-auto
)
2268 (recent-auto-save-p)
2269 buffer-auto-save-file-name
2270 (file-readable-p buffer-auto-save-file-name
)
2272 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2273 (file-name (if auto-save-p
2274 buffer-auto-save-file-name
2276 (cond ((null file-name
)
2277 (error "Buffer does not seem to be associated with any file"))
2279 (yes-or-no-p (format "Revert buffer from file %s? "
2281 (run-hooks 'before-revert-hook
)
2282 ;; If file was backed up but has changed since,
2283 ;; we shd make another backup.
2284 (and (not auto-save-p
)
2285 (not (verify-visited-file-modtime (current-buffer)))
2286 (setq buffer-backed-up nil
))
2287 ;; Get rid of all undo records for this buffer.
2288 (or (eq buffer-undo-list t
)
2289 (setq buffer-undo-list nil
))
2290 ;; Effectively copy the after-revert-hook status,
2291 ;; since after-find-file will clobber it.
2292 (let ((global-hook (default-value 'after-revert-hook
))
2293 (local-hook-p (local-variable-p 'after-revert-hook
))
2294 (local-hook (and (local-variable-p 'after-revert-hook
)
2295 after-revert-hook
)))
2296 (let (buffer-read-only
2297 ;; Don't make undo records for the reversion.
2298 (buffer-undo-list t
))
2299 (if revert-buffer-insert-file-contents-function
2300 (funcall revert-buffer-insert-file-contents-function
2301 file-name auto-save-p
)
2302 (if (not (file-exists-p file-name
))
2303 (error "File %s no longer exists!" file-name
))
2304 ;; Bind buffer-file-name to nil
2305 ;; so that we don't try to lock the file.
2306 (let ((buffer-file-name nil
))
2310 (insert-file-contents file-name
(not auto-save-p
)
2312 (goto-char (min opoint
(point-max)))
2313 ;; Recompute the truename in case changes in symlinks
2314 ;; have changed the truename.
2315 (setq buffer-file-truename
2316 (abbreviate-file-name (file-truename buffer-file-name
)))
2317 (after-find-file nil nil t t preserve-modes
)
2318 ;; Run after-revert-hook as it was before we reverted.
2319 (setq-default revert-buffer-internal-hook global-hook
)
2322 (make-local-variable 'revert-buffer-internal-hook
)
2323 (setq revert-buffer-internal-hook local-hook
))
2324 (kill-local-variable 'revert-buffer-internal-hook
))
2325 (run-hooks 'revert-buffer-internal-hook
))
2328 (defun recover-file (file)
2329 "Visit file FILE, but get contents from its last auto-save file."
2330 ;; Actually putting the file name in the minibuffer should be used
2332 ;; Not just because users often use the default.
2333 (interactive "FRecover file: ")
2334 (setq file
(expand-file-name file
))
2335 (if (auto-save-file-name-p (file-name-nondirectory file
))
2336 (error "%s is an auto-save file" file
))
2337 (let ((file-name (let ((buffer-file-name file
))
2338 (make-auto-save-file-name))))
2339 (cond ((if (file-exists-p file
)
2340 (not (file-newer-than-file-p file-name file
))
2341 (not (file-exists-p file-name
)))
2342 (error "Auto-save file %s not current" file-name
))
2343 ((save-window-excursion
2344 (if (not (eq system-type
'vax-vms
))
2345 (with-output-to-temp-buffer "*Directory*"
2346 (buffer-disable-undo standard-output
)
2347 (call-process "ls" nil standard-output nil
2348 (if (file-symlink-p file
) "-lL" "-l")
2350 (yes-or-no-p (format "Recover auto save file %s? " file-name
)))
2351 (switch-to-buffer (find-file-noselect file t
))
2352 (let ((buffer-read-only nil
))
2354 (insert-file-contents file-name nil
))
2355 (after-find-file nil nil t
))
2356 (t (error "Recover-file cancelled.")))))
2358 (defun recover-session ()
2359 "Recover auto save files from a previous Emacs session.
2360 This command first displays a Dired buffer showing you the
2361 previous sessions that you could recover from.
2362 To choose one, move point to the proper line and then type C-c C-c.
2363 Then you'll be asked about a number of files to recover."
2365 (if (null auto-save-list-file-prefix
)
2366 (error "You set `auto-save-list-file-prefix' to disable making session files"))
2367 (let ((ls-lisp-support-shell-wildcards t
))
2368 (dired (concat auto-save-list-file-prefix
"*")))
2369 (goto-char (point-min))
2370 (or (looking-at "Move to the session you want to recover,")
2371 (let ((inhibit-read-only t
))
2372 (insert "Move to the session you want to recover,\n"
2373 "then type C-c C-c to select it.\n\n"
2374 "You can also delete some of these files;\n"
2375 "type d on a line to mark that file for deletion.\n\n")))
2376 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2377 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish
))
2379 (defun recover-session-finish ()
2380 "Choose one saved session to recover auto-save files from.
2381 This command is used in the special Dired buffer created by
2382 \\[recover-session]."
2384 ;; Get the name of the session file to recover from.
2385 (let ((file (dired-get-filename))
2387 (buffer (get-buffer-create " *recover*")))
2388 (dired-do-flagged-delete t
)
2391 ;; Read in the auto-save-list file.
2394 (insert-file-contents file
)
2395 ;; Loop thru the text of that file
2396 ;; and get out the names of the files to recover.
2398 (let (thisfile autofile
)
2400 ;; This is a pair of lines for a non-file-visiting buffer.
2401 ;; Get the auto-save file name and manufacture
2402 ;; a "visited file name" from that.
2406 (buffer-substring-no-properties
2414 (file-name-nondirectory autofile
)
2416 (file-name-directory autofile
)))
2418 ;; This pair of lines is a file-visiting
2419 ;; buffer. Use the visited file name.
2422 (buffer-substring-no-properties
2423 (point) (progn (end-of-line) (point))))
2426 (buffer-substring-no-properties
2427 (point) (progn (end-of-line) (point))))
2429 ;; Ignore a file if its auto-save file does not exist now.
2430 (if (file-exists-p autofile
)
2431 (setq files
(cons thisfile files
)))))
2432 (setq files
(nreverse files
))
2433 ;; The file contains a pair of line for each auto-saved buffer.
2434 ;; The first line of the pair contains the visited file name
2435 ;; or is empty if the buffer was not visiting a file.
2436 ;; The second line is the auto-save file name.
2438 (map-y-or-n-p "Recover %s? "
2441 (save-excursion (recover-file file
))
2443 "Failed to recover `%s'" file
)))
2445 '("file" "files" "recover"))
2446 (message "No files can be recovered from this session now")))
2447 (kill-buffer buffer
))))
2449 (defun kill-some-buffers (&optional list
)
2450 "For each buffer in LIST, ask whether to kill it.
2451 LIST defaults to all existing live buffers."
2454 (setq list
(buffer-list)))
2456 (let* ((buffer (car list
))
2457 (name (buffer-name buffer
)))
2458 (and (not (string-equal name
""))
2459 (/= (aref name
0) ?
)
2461 (format "Buffer %s %s. Kill? "
2463 (if (buffer-modified-p buffer
)
2464 "HAS BEEN EDITED" "is unmodified")))
2465 (kill-buffer buffer
)))
2466 (setq list
(cdr list
))))
2468 (defun auto-save-mode (arg)
2469 "Toggle auto-saving of contents of current buffer.
2470 With prefix argument ARG, turn auto-saving on if positive, else off."
2472 (setq buffer-auto-save-file-name
2474 (or (not buffer-auto-save-file-name
)
2475 ;; If autosave is off because buffer has shrunk,
2476 ;; then toggling should turn it on.
2477 (< buffer-saved-size
0))
2478 (or (eq arg t
) (listp arg
) (and (integerp arg
) (> arg
0))))
2479 (if (and buffer-file-name auto-save-visited-file-name
2480 (not buffer-read-only
))
2482 (make-auto-save-file-name))))
2483 ;; If -1 was stored here, to temporarily turn off saving,
2485 (and (< buffer-saved-size
0)
2486 (setq buffer-saved-size
0))
2488 (message "Auto-save %s (in this buffer)"
2489 (if buffer-auto-save-file-name
"on" "off")))
2490 buffer-auto-save-file-name
)
2492 (defun rename-auto-save-file ()
2493 "Adjust current buffer's auto save file name for current conditions.
2494 Also rename any existing auto save file, if it was made in this session."
2495 (let ((osave buffer-auto-save-file-name
))
2496 (setq buffer-auto-save-file-name
2497 (make-auto-save-file-name))
2498 (if (and osave buffer-auto-save-file-name
2499 (not (string= buffer-auto-save-file-name buffer-file-name
))
2500 (not (string= buffer-auto-save-file-name osave
))
2501 (file-exists-p osave
)
2502 (recent-auto-save-p))
2503 (rename-file osave buffer-auto-save-file-name t
))))
2505 (defun make-auto-save-file-name ()
2506 "Return file name to use for auto-saves of current buffer.
2507 Does not consider `auto-save-visited-file-name' as that variable is checked
2508 before calling this function. You can redefine this for customization.
2509 See also `auto-save-file-name-p'."
2510 (if buffer-file-name
2511 (if (and (eq system-type
'ms-dos
)
2512 (not (msdos-long-file-names)))
2513 (let ((fn (file-name-nondirectory buffer-file-name
)))
2514 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn
)
2515 (concat (file-name-directory buffer-file-name
)
2516 "#" (match-string 1 fn
)
2517 "." (match-string 3 fn
) "#"))
2518 (concat (file-name-directory buffer-file-name
)
2520 (file-name-nondirectory buffer-file-name
)
2523 ;; Deal with buffers that don't have any associated files. (Mail
2524 ;; mode tends to create a good number of these.)
2526 (let ((buffer-name (buffer-name))
2528 ;; Use technique from Sebastian Kremer's auto-save
2529 ;; package to turn slashes into \\!. This ensures that
2530 ;; the auto-save buffer name is unique.
2532 (while (string-match "[/\\]" buffer-name limit
)
2533 (setq buffer-name
(concat (substring buffer-name
0 (match-beginning 0))
2534 (if (string= (substring buffer-name
2540 (substring buffer-name
(match-end 0))))
2541 (setq limit
(1+ (match-end 0))))
2542 ;; Generate the file name.
2544 (format "#%s#%s#" buffer-name
(make-temp-name ""))
2545 ;; Try a few alternative directories, to get one we can write it.
2547 ((file-writable-p default-directory
) default-directory
)
2548 ((file-writable-p "/var/tmp/") "/var/tmp/")
2551 (defun auto-save-file-name-p (filename)
2552 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2553 FILENAME should lack slashes. You can redefine this for customization."
2554 (string-match "^#.*#$" filename
))
2556 (defun wildcard-to-regexp (wildcard)
2557 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2558 The generated regexp will match a filename iff the filename
2559 matches that wildcard according to shell rules. Only wildcards known
2560 by `sh' are supported."
2561 (let* ((i (string-match "[[.*+\\^$?]" wildcard
))
2562 ;; Copy the initial run of non-special characters.
2563 (result (substring wildcard
0 i
))
2564 (len (length wildcard
)))
2565 ;; If no special characters, we're almost done.
2568 (let ((ch (aref wildcard i
))
2576 (eq (aref wildcard
(1+ i
)) ?\
]))
2578 ((eq ch ?\
[) ; [...] maps to regexp char class
2583 ((eq (aref wildcard i
) ?
!) ; [!...] -> [^...]
2586 (if (eq (aref wildcard i
) ?\
])
2591 ((eq (aref wildcard i
) ?^
)
2592 ;; Found "[^". Insert a `\0' character
2593 ;; (which cannot happen in a filename)
2594 ;; into the character class, so that `^'
2595 ;; is not the first character after `[',
2596 ;; and thus non-special in a regexp.
2600 ((eq (aref wildcard i
) ?\
])
2601 ;; I don't think `]' can appear in a
2602 ;; character class in a wildcard, but
2603 ;; let's be general here.
2608 (prog1 ; copy everything upto next `]'.
2611 (setq j
(string-match
2613 (setq i
(if j
(1- j
) (1- len
)))))))
2615 ((eq ch ?
*) "[^\000]*")
2619 ((eq ch ?
\\) "\\\\") ; probably cannot happen...
2620 ((eq ch ??
) "[^\000]")
2621 (t (char-to-string ch
)))))
2623 ;; Shell wildcards should match the entire filename,
2624 ;; not its part. Make the regexp say so.
2625 (concat "\\`" result
"\\'")))
2627 (defvar list-directory-brief-switches
2628 (if (eq system-type
'vax-vms
) "" "-CF")
2629 "*Switches for list-directory to pass to `ls' for brief listing,")
2631 (defvar list-directory-verbose-switches
2632 (if (eq system-type
'vax-vms
)
2633 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2635 "*Switches for list-directory to pass to `ls' for verbose listing,")
2637 (defun list-directory (dirname &optional verbose
)
2638 "Display a list of files in or matching DIRNAME, a la `ls'.
2639 DIRNAME is globbed by the shell if necessary.
2640 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2641 Actions controlled by variables `list-directory-brief-switches'
2642 and `list-directory-verbose-switches'."
2643 (interactive (let ((pfx current-prefix-arg
))
2644 (list (read-file-name (if pfx
"List directory (verbose): "
2645 "List directory (brief): ")
2646 nil default-directory nil
)
2648 (let ((switches (if verbose list-directory-verbose-switches
2649 list-directory-brief-switches
)))
2650 (or dirname
(setq dirname default-directory
))
2651 (setq dirname
(expand-file-name dirname
))
2652 (with-output-to-temp-buffer "*Directory*"
2653 (buffer-disable-undo standard-output
)
2654 (princ "Directory ")
2658 (set-buffer "*Directory*")
2659 (setq default-directory
2660 (if (file-directory-p dirname
)
2661 (file-name-as-directory dirname
)
2662 (file-name-directory dirname
)))
2663 (let ((wildcard (not (file-directory-p dirname
))))
2664 (insert-directory dirname switches wildcard
(not wildcard
)))))))
2666 (defvar insert-directory-program
"ls"
2667 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2670 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2671 ;; FULL-DIRECTORY-P is nil.
2672 ;; The single line of output must display FILE's name as it was
2673 ;; given, namely, an absolute path name.
2674 ;; - must insert exactly one line for each file if WILDCARD or
2675 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
2676 ;; before the file lines, plus optional text after the file lines.
2677 ;; Lines are delimited by "\n", so filenames containing "\n" are not
2679 ;; File lines should display the basename.
2680 ;; - must be consistent with
2681 ;; - functions dired-move-to-filename, (these two define what a file line is)
2682 ;; dired-move-to-end-of-filename,
2683 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2684 ;; dired-insert-headerline
2685 ;; dired-after-subdir-garbage (defines what a "total" line is)
2686 ;; - variable dired-subdir-regexp
2687 (defun insert-directory (file switches
&optional wildcard full-directory-p
)
2688 "Insert directory listing for FILE, formatted according to SWITCHES.
2689 Leaves point after the inserted text.
2690 SWITCHES may be a string of options, or a list of strings.
2691 Optional third arg WILDCARD means treat FILE as shell wildcard.
2692 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2693 switches do not contain `d', so that a full listing is expected.
2695 This works by running a directory listing program
2696 whose name is in the variable `insert-directory-program'.
2697 If WILDCARD, it also runs the shell specified by `shell-file-name'."
2698 ;; We need the directory in order to find the right handler.
2699 (let ((handler (find-file-name-handler (expand-file-name file
)
2700 'insert-directory
)))
2702 (funcall handler
'insert-directory file switches
2703 wildcard full-directory-p
)
2704 (if (eq system-type
'vax-vms
)
2705 (vms-read-directory file switches
(current-buffer))
2708 ;; Run ls in the directory of the file pattern we asked for.
2709 (let ((default-directory
2710 (if (file-name-absolute-p file
)
2711 (file-name-directory file
)
2712 (file-name-directory (expand-file-name file
))))
2713 (pattern (file-name-nondirectory file
))
2715 ;; Quote some characters that have special meanings in shells;
2716 ;; but don't quote the wildcards--we want them to be special.
2717 ;; We also currently don't quote the quoting characters
2718 ;; in case people want to use them explicitly to quote
2719 ;; wildcard characters.
2720 (while (string-match "[ \t\n;<>&|()#$]" pattern beg
)
2722 (concat (substring pattern
0 (match-beginning 0))
2724 (substring pattern
(match-beginning 0)))
2725 beg
(1+ (match-end 0))))
2726 (call-process shell-file-name nil t nil
2727 "-c" (concat "\\" ;; Disregard shell aliases!
2728 insert-directory-program
2730 (if (stringp switches
)
2732 (mapconcat 'identity switches
" "))
2735 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2736 ;; directory if FILE is a symbolic link.
2737 (apply 'call-process
2738 insert-directory-program nil t nil
2740 (if (listp switches
)
2741 (setq list switches
)
2742 (if (not (equal switches
""))
2744 ;; Split the switches at any spaces
2745 ;; so we can pass separate options as separate args.
2746 (while (string-match " " switches
)
2747 (setq list
(cons (substring switches
0 (match-beginning 0))
2749 switches
(substring switches
(match-end 0))))
2750 (setq list
(nreverse (cons switches list
))))))
2752 ;; Avoid lossage if FILE starts with `-'.
2755 (if full-directory-p
2756 (concat (file-name-as-directory file
) ".")
2758 ;; We get here if ls failed.
2759 ;; Access the file to get a suitable error.
2760 (access-file file
"Reading directory"))))))
2762 (defvar kill-emacs-query-functions nil
2763 "Functions to call with no arguments to query about killing Emacs.
2764 If any of these functions returns nil, killing Emacs is cancelled.
2765 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
2766 but `kill-emacs', the low level primitive, does not.
2767 See also `kill-emacs-hook'.")
2769 (defun save-buffers-kill-emacs (&optional arg
)
2770 "Offer to save each buffer, then kill this Emacs process.
2771 With prefix arg, silently save all file-visiting buffers, then kill."
2773 (save-some-buffers arg t
)
2774 (and (or (not (memq t
(mapcar (function
2775 (lambda (buf) (and (buffer-file-name buf
)
2776 (buffer-modified-p buf
))))
2778 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2779 (or (not (fboundp 'process-list
))
2780 ;; process-list is not defined on VMS.
2781 (let ((processes (process-list))
2784 (and (memq (process-status (car processes
)) '(run stop open
))
2785 (let ((val (process-kill-without-query (car processes
))))
2786 (process-kill-without-query (car processes
) val
)
2789 (setq processes
(cdr processes
)))
2791 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
2792 ;; Query the user for other things, perhaps.
2793 (run-hook-with-args-until-failure 'kill-emacs-query-functions
)
2796 ;; We use /: as a prefix to "quote" a file name
2797 ;; so that magic file name handlers will not apply to it.
2799 (setq file-name-handler-alist
2800 (cons '("\\`/:" . file-name-non-special
)
2801 file-name-handler-alist
))
2803 ;; We depend on being the last handler on the list,
2804 ;; so that anything else which does need handling
2805 ;; has been handled already.
2806 ;; So it is safe for us to inhibit *all* magic file name handlers.
2808 (defun file-name-non-special (operation &rest arguments
)
2809 (let ((file-name-handler-alist nil
)
2810 ;; Get a list of the indices of the args which are file names.
2812 (cdr (or (assq operation
2813 ;; The first four are special because they
2814 ;; return a file name. We want to include the /:
2815 ;; in the return value.
2816 ;; So just avoid stripping it in the first place.
2817 '((expand-file-name . nil
)
2818 (file-name-directory . nil
)
2819 (file-name-as-directory . nil
)
2820 (directory-file-name . nil
)
2823 (make-symbolic-link 0 1)
2824 (add-name-to-file 0 1)))
2825 ;; For all other operations, treat the first argument only
2826 ;; as the file name.
2828 ;; Copy ARGUMENTS so we can replace elements in it.
2829 (arguments (copy-sequence arguments
)))
2830 ;; Strip off the /: from the file names that have this handler.
2832 (while file-arg-indices
2833 (and (nth (car file-arg-indices
) arguments
)
2834 (string-match "\\`/:" (nth (car file-arg-indices
) arguments
))
2835 (setcar (nthcdr (car file-arg-indices
) arguments
)
2836 (substring (nth (car file-arg-indices
) arguments
) 2)))
2837 (setq file-arg-indices
(cdr file-arg-indices
))))
2838 (apply operation arguments
)))
2840 (define-key ctl-x-map
"\C-f" 'find-file
)
2841 (define-key ctl-x-map
"\C-q" 'toggle-read-only
)
2842 (define-key ctl-x-map
"\C-r" 'find-file-read-only
)
2843 (define-key ctl-x-map
"\C-v" 'find-alternate-file
)
2844 (define-key ctl-x-map
"\C-s" 'save-buffer
)
2845 (define-key ctl-x-map
"s" 'save-some-buffers
)
2846 (define-key ctl-x-map
"\C-w" 'write-file
)
2847 (define-key ctl-x-map
"i" 'insert-file
)
2848 (define-key esc-map
"~" 'not-modified
)
2849 (define-key ctl-x-map
"\C-d" 'list-directory
)
2850 (define-key ctl-x-map
"\C-c" 'save-buffers-kill-emacs
)
2852 (define-key ctl-x-4-map
"f" 'find-file-other-window
)
2853 (define-key ctl-x-4-map
"r" 'find-file-read-only-other-window
)
2854 (define-key ctl-x-4-map
"\C-f" 'find-file-other-window
)
2855 (define-key ctl-x-4-map
"b" 'switch-to-buffer-other-window
)
2856 (define-key ctl-x-4-map
"\C-o" 'display-buffer
)
2858 (define-key ctl-x-5-map
"b" 'switch-to-buffer-other-frame
)
2859 (define-key ctl-x-5-map
"f" 'find-file-other-frame
)
2860 (define-key ctl-x-5-map
"\C-f" 'find-file-other-frame
)
2861 (define-key ctl-x-5-map
"r" 'find-file-read-only-other-frame
)
2863 ;;; files.el ends here