(Fcommand_execute): New arg SPECIAL. All callers changed.
[emacs.git] / lisp / files.el
blob309410ba9923f080f8c1c4633ef75ab14d72ef67
1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985, 86, 87, 92, 93, 94, 1995 Free Software Foundation, Inc.
5 ;; Maintainer: FSF
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
24 ;;; Commentary:
26 ;; Defines most of Emacs's file- and directory-handling functions,
27 ;; including basic file visiting, backup generation, link handling,
28 ;; ITS-id version control, load- and write-hook handling, and the like.
30 ;;; Code:
32 (defconst delete-auto-save-files t
33 "*Non-nil means delete auto-save file when a buffer is saved or killed.")
35 (defconst directory-abbrev-alist
36 nil
37 "*Alist of abbreviations for file directories.
38 A list of elements of the form (FROM . TO), each meaning to replace
39 FROM with TO when it appears in a directory name. This replacement is
40 done when setting up the default directory of a newly visited file.
41 *Every* FROM string should start with `^'.
43 Do not use `~' in the TO strings.
44 They should be ordinary absolute directory names.
46 Use this feature when you have directories which you normally refer to
47 via absolute symbolic links. Make TO the name of the link, and FROM
48 the name it is linked to.")
50 ;;; Turn off backup files on VMS since it has version numbers.
51 (defconst make-backup-files (not (eq system-type 'vax-vms))
52 "*Non-nil means make a backup of a file the first time it is saved.
53 This can be done by renaming the file or by copying.
55 Renaming means that Emacs renames the existing file so that it is a
56 backup file, then writes the buffer into a new file. Any other names
57 that the old file had will now refer to the backup file. The new file
58 is owned by you and its group is defaulted.
60 Copying means that Emacs copies the existing file into the backup
61 file, then writes the buffer on top of the existing file. Any other
62 names that the old file had will now refer to the new (edited) file.
63 The file's owner and group are unchanged.
65 The choice of renaming or copying is controlled by the variables
66 `backup-by-copying', `backup-by-copying-when-linked' and
67 `backup-by-copying-when-mismatch'. See also `backup-inhibited'.")
69 ;; Do this so that local variables based on the file name
70 ;; are not overridden by the major mode.
71 (defvar backup-inhibited nil
72 "Non-nil means don't make a backup, regardless of the other parameters.
73 This variable is intended for use by making it local to a buffer.
74 But it is local only if you make it local.")
75 (put 'backup-inhibited 'permanent-local t)
77 (defconst backup-by-copying nil
78 "*Non-nil means always use copying to create backup files.
79 See documentation of variable `make-backup-files'.")
81 (defconst backup-by-copying-when-linked nil
82 "*Non-nil means use copying to create backups for files with multiple names.
83 This causes the alternate names to refer to the latest version as edited.
84 This variable is relevant only if `backup-by-copying' is nil.")
86 (defconst backup-by-copying-when-mismatch nil
87 "*Non-nil means create backups by copying if this preserves owner or group.
88 Renaming may still be used (subject to control of other variables)
89 when it would not result in changing the owner or group of the file;
90 that is, for files which are owned by you and whose group matches
91 the default for a new file created there by you.
92 This variable is relevant only if `backup-by-copying' is nil.")
94 (defvar backup-enable-predicate
95 '(lambda (name)
96 (or (< (length name) 5)
97 (not (string-equal "/tmp/" (substring name 0 5)))))
98 "Predicate that looks at a file name and decides whether to make backups.
99 Called with an absolute file name as argument, it returns t to enable backup.")
101 (defconst buffer-offer-save nil
102 "*Non-nil in a buffer means offer to save the buffer on exit
103 even if the buffer is not visiting a file.
104 Automatically local in all buffers.")
105 (make-variable-buffer-local 'buffer-offer-save)
107 (defconst find-file-existing-other-name nil
108 "*Non-nil means find a file under alternative names, in existing buffers.
109 This means if any existing buffer is visiting the file you want
110 under another name, you get the existing buffer instead of a new buffer.")
112 (defconst find-file-visit-truename nil
113 "*Non-nil means visit a file under its truename.
114 The truename of a file is found by chasing all links
115 both at the file level and at the levels of the containing directories.")
117 (defvar buffer-file-number nil
118 "The device number and file number of the file visited in the current buffer.
119 The value is a list of the form (FILENUM DEVNUM).
120 This pair of numbers uniquely identifies the file.
121 If the buffer is visiting a new file, the value is nil.")
122 (make-variable-buffer-local 'buffer-file-number)
123 (put 'buffer-file-number 'permanent-local t)
125 (defconst file-precious-flag nil
126 "*Non-nil means protect against I/O errors while saving files.
127 Some modes set this non-nil in particular buffers.
129 This feature works by writing the new contents into a temporary file
130 and then renaming the temporary file to replace the original.
131 In this way, any I/O error in writing leaves the original untouched,
132 and there is never any instant where the file is nonexistent.
134 Note that this feature forces backups to be made by copying.
135 Yet, at the same time, saving a precious file
136 breaks any hard links between it and other files.")
138 (defvar version-control nil
139 "*Control use of version numbers for backup files.
140 t means make numeric backup versions unconditionally.
141 nil means make them for files that have some already.
142 `never' means do not make them.")
144 (defvar dired-kept-versions 2
145 "*When cleaning directory, number of versions to keep.")
147 (defvar delete-old-versions nil
148 "*If t, delete excess backup versions silently.
149 If nil, ask confirmation. Any other value prevents any trimming.")
151 (defvar kept-old-versions 2
152 "*Number of oldest versions to keep when a new numbered backup is made.")
154 (defvar kept-new-versions 2
155 "*Number of newest versions to keep when a new numbered backup is made.
156 Includes the new backup. Must be > 0")
158 (defconst require-final-newline nil
159 "*Value of t says silently ensure a file ends in a newline when it is saved.
160 Non-nil but not t says ask user whether to add a newline when there isn't one.
161 nil means don't add newlines.")
163 (defconst auto-save-default t
164 "*Non-nil says by default do auto-saving of every file-visiting buffer.")
166 (defconst auto-save-visited-file-name nil
167 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
168 Normally auto-save files are written under other names.")
170 (defconst save-abbrevs nil
171 "*Non-nil means save word abbrevs too when files are saved.
172 Loading an abbrev file sets this to t.")
174 (defconst find-file-run-dired t
175 "*Non-nil says run dired if `find-file' is given the name of a directory.")
177 ;;;It is not useful to make this a local variable.
178 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
179 (defvar find-file-not-found-hooks nil
180 "List of functions to be called for `find-file' on nonexistent file.
181 These functions are called as soon as the error is detected.
182 `buffer-file-name' is already set up.
183 The functions are called in the order given until one of them returns non-nil.")
185 ;;;It is not useful to make this a local variable.
186 ;;;(put 'find-file-hooks 'permanent-local t)
187 (defvar find-file-hooks nil
188 "List of functions to be called after a buffer is loaded from a file.
189 The buffer's local variables (if any) will have been processed before the
190 functions are called.")
192 (defvar write-file-hooks nil
193 "List of functions to be called before writing out a buffer to a file.
194 If one of them returns non-nil, the file is considered already written
195 and the rest are not called.
196 These hooks are considered to pertain to the visited file.
197 So this list is cleared if you change the visited file name.
199 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.
200 See also `write-contents-hooks'.")
201 ;;; However, in case someone does make it local...
202 (put 'write-file-hooks 'permanent-local t)
204 (defvar local-write-file-hooks nil
205 "Just like `write-file-hooks', except intended for per-buffer use.
206 The functions in this list are called before the ones in
207 `write-file-hooks'.
209 This variable is meant to be used for hooks that have to do with a
210 particular visited file. Therefore, it is a permanent local, so that
211 changing the major mode does not clear it. However, calling
212 `set-visited-file-name' does clear it.")
213 (make-variable-buffer-local 'local-write-file-hooks)
214 (put 'local-write-file-hooks 'permanent-local t)
216 (defvar write-contents-hooks nil
217 "List of functions to be called before writing out a buffer to a file.
218 If one of them returns non-nil, the file is considered already written
219 and the rest are not called.
221 This variable is meant to be used for hooks that pertain to the
222 buffer's contents, not to the particular visited file; thus,
223 `set-visited-file-name' does not clear this variable; but changing the
224 major mode does clear it.
226 This variable automatically becomes buffer-local whenever it is set.
227 If you use `add-hooks' to add elements to the list, use nil for the
228 LOCAL argument.
230 See also `write-file-hooks'.")
231 (make-variable-buffer-local 'write-contents-hooks)
233 (defconst enable-local-variables t
234 "*Control use of local-variables lists in files you visit.
235 The value can be t, nil or something else.
236 A value of t means local-variables lists are obeyed;
237 nil means they are ignored; anything else means query.
239 The command \\[normal-mode] always obeys local-variables lists
240 and ignores this variable.")
242 (defconst enable-local-eval 'maybe
243 "*Control processing of the \"variable\" `eval' in a file's local variables.
244 The value can be t, nil or something else.
245 A value of t means obey `eval' variables;
246 nil means ignore them; anything else means query.
248 The command \\[normal-mode] always obeys local-variables lists
249 and ignores this variable.")
251 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
252 (or (fboundp 'lock-buffer)
253 (defalias 'lock-buffer 'ignore))
254 (or (fboundp 'unlock-buffer)
255 (defalias 'unlock-buffer 'ignore))
257 ;; This hook function provides support for ange-ftp host name
258 ;; completion. It runs the usual ange-ftp hook, but only for
259 ;; completion operations. Having this here avoids the need
260 ;; to load ange-ftp when it's not really in use.
261 (defun ange-ftp-completion-hook-function (op &rest args)
262 (if (memq op '(file-name-completion file-name-all-completions))
263 (apply 'ange-ftp-hook-function op args)
264 (let ((inhibit-file-name-handlers
265 (cons 'ange-ftp-completion-hook-function
266 (and (eq inhibit-file-name-operation op)
267 inhibit-file-name-handlers)))
268 (inhibit-file-name-operation op))
269 (apply op args))))
271 (defun convert-standard-filename (filename)
272 "Convert a standard file's name to something suitable for the current OS.
273 This function's standard definition is trivial; it just returns the argument.
274 However, on some systems, the function is redefined
275 with a definition that really does change some file names."
276 filename)
278 (defun pwd ()
279 "Show the current default directory."
280 (interactive nil)
281 (message "Directory %s" default-directory))
283 (defvar cd-path nil
284 "Value of the CDPATH environment variable, as a list.
285 Not actually set up until the first time you you use it.")
287 (defvar path-separator ":"
288 "Character used to separate concatenated paths.")
290 (defun parse-colon-path (cd-path)
291 "Explode a colon-separated list of paths into a string list."
292 (and cd-path
293 (let (cd-prefix cd-list (cd-start 0) cd-colon)
294 (setq cd-path (concat cd-path path-separator))
295 (while (setq cd-colon (string-match path-separator cd-path cd-start))
296 (setq cd-list
297 (nconc cd-list
298 (list (if (= cd-start cd-colon)
300 (substitute-in-file-name
301 (file-name-as-directory
302 (substring cd-path cd-start cd-colon)))))))
303 (setq cd-start (+ cd-colon 1)))
304 cd-list)))
306 (defun cd-absolute (dir)
307 "Change current directory to given absolute file name DIR."
308 ;; Put the name into directory syntax now,
309 ;; because otherwise expand-file-name may give some bad results.
310 (if (not (eq system-type 'vax-vms))
311 (setq dir (file-name-as-directory dir)))
312 (setq dir (abbreviate-file-name (expand-file-name dir)))
313 (if (not (file-directory-p dir))
314 (error "%s is not a directory" dir)
315 (if (file-executable-p dir)
316 (setq default-directory dir)
317 (error "Cannot cd to %s: Permission denied" dir))))
319 (defun cd (dir)
320 "Make DIR become the current buffer's default directory.
321 If your environment includes a `CDPATH' variable, try each one of that
322 colon-separated list of directories when resolving a relative directory name."
323 (interactive
324 (list (read-file-name "Change default directory: "
325 default-directory default-directory
326 (and (member cd-path '(nil ("./")))
327 (null (getenv "CDPATH"))))))
328 (if (file-name-absolute-p dir)
329 (cd-absolute (expand-file-name dir))
330 (if (null cd-path)
331 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
332 (setq cd-path (or trypath (list "./")))))
333 (if (not (catch 'found
334 (mapcar
335 (function (lambda (x)
336 (let ((f (expand-file-name (concat x dir))))
337 (if (file-directory-p f)
338 (progn
339 (cd-absolute f)
340 (throw 'found t))))))
341 cd-path)
342 nil))
343 (error "No such directory found via CDPATH environment variable"))))
345 (defun load-file (file)
346 "Load the Lisp file named FILE."
347 (interactive "fLoad file: ")
348 (load (expand-file-name file) nil nil t))
350 (defun load-library (library)
351 "Load the library named LIBRARY.
352 This is an interface to the function `load'."
353 (interactive "sLoad library: ")
354 (load library))
356 (defun file-local-copy (file &optional buffer)
357 "Copy the file FILE into a temporary file on this machine.
358 Returns the name of the local copy, or nil, if FILE is directly
359 accessible."
360 (let ((handler (find-file-name-handler file 'file-local-copy)))
361 (if handler
362 (funcall handler 'file-local-copy file)
363 nil)))
365 (defun file-truename (filename &optional counter prev-dirs)
366 "Return the truename of FILENAME, which should be absolute.
367 The truename of a file name is found by chasing symbolic links
368 both at the level of the file and at the level of the directories
369 containing it, until no links are left at any level.
371 The arguments COUNTER and PREV-DIRS are used only in recursive calls.
372 Do not specify them in other calls."
373 ;; COUNTER can be a cons cell whose car is the count of how many more links
374 ;; to chase before getting an error.
375 ;; PREV-DIRS can be a cons cell whose car is an alist
376 ;; of truenames we've just recently computed.
378 ;; The last test looks dubious, maybe `+' is meant here? --simon.
379 (if (or (string= filename "") (string= filename "~")
380 (and (string= (substring filename 0 1) "~")
381 (string-match "~[^/]*" filename)))
382 (progn
383 (setq filename (expand-file-name filename))
384 (if (string= filename "")
385 (setq filename "/"))))
386 (or counter (setq counter (list 100)))
387 (let (done
388 ;; For speed, remove the ange-ftp completion handler from the list.
389 ;; We know it's not needed here.
390 ;; For even more speed, do this only on the outermost call.
391 (file-name-handler-alist
392 (if prev-dirs file-name-handler-alist
393 (let ((tem (copy-sequence file-name-handler-alist)))
394 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
395 (or prev-dirs (setq prev-dirs (list nil)))
396 ;; If this file directly leads to a link, process that iteratively
397 ;; so that we don't use lots of stack.
398 (while (not done)
399 (setcar counter (1- (car counter)))
400 (if (< (car counter) 0)
401 (error "Apparent cycle of symbolic links for %s" filename))
402 (let ((handler (find-file-name-handler filename 'file-truename)))
403 ;; For file name that has a special handler, call handler.
404 ;; This is so that ange-ftp can save time by doing a no-op.
405 (if handler
406 (setq filename (funcall handler 'file-truename filename)
407 done t)
408 (let ((dir (or (file-name-directory filename) default-directory))
409 target dirfile)
410 ;; Get the truename of the directory.
411 (setq dirfile (directory-file-name dir))
412 ;; If these are equal, we have the (or a) root directory.
413 (or (string= dir dirfile)
414 ;; If this is the same dir we last got the truename for,
415 ;; save time--don't recalculate.
416 (if (assoc dir (car prev-dirs))
417 (setq dir (cdr (assoc dir (car prev-dirs))))
418 (let ((old dir)
419 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
420 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
421 (setq dir new))))
422 (if (equal ".." (file-name-nondirectory filename))
423 (setq filename
424 (directory-file-name (file-name-directory (directory-file-name dir)))
425 done t)
426 (if (equal "." (file-name-nondirectory filename))
427 (setq filename (directory-file-name dir)
428 done t)
429 ;; Put it back on the file name.
430 (setq filename (concat dir (file-name-nondirectory filename)))
431 ;; Is the file name the name of a link?
432 (setq target (file-symlink-p filename))
433 (if target
434 ;; Yes => chase that link, then start all over
435 ;; since the link may point to a directory name that uses links.
436 ;; We can't safely use expand-file-name here
437 ;; since target might look like foo/../bar where foo
438 ;; is itself a link. Instead, we handle . and .. above.
439 (setq filename
440 (if (file-name-absolute-p target)
441 target
442 (concat dir target))
443 done nil)
444 ;; No, we are done!
445 (setq done t))))))))
446 filename))
448 (defun file-chase-links (filename)
449 "Chase links in FILENAME until a name that is not a link.
450 Does not examine containing directories for links,
451 unlike `file-truename'."
452 (let (tem (count 100) (newname filename))
453 (while (setq tem (file-symlink-p newname))
454 (if (= count 0)
455 (error "Apparent cycle of symbolic links for %s" filename))
456 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
457 (while (string-match "//+" tem)
458 (setq tem (concat (substring tem 0 (1+ (match-beginning 0)))
459 (substring tem (match-end 0)))))
460 ;; Handle `..' by hand, since it needs to work in the
461 ;; target of any directory symlink.
462 ;; This code is not quite complete; it does not handle
463 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
464 (while (string-match "\\`\\.\\./" tem)
465 (setq tem (substring tem 3))
466 (setq newname (file-name-as-directory
467 ;; Do the .. by hand.
468 (directory-file-name
469 (file-name-directory
470 ;; Chase links in the default dir of the symlink.
471 (file-chase-links
472 (directory-file-name
473 (file-name-directory newname))))))))
474 (setq newname (expand-file-name tem (file-name-directory newname)))
475 (setq count (1- count)))
476 newname))
478 (defun switch-to-buffer-other-window (buffer)
479 "Select buffer BUFFER in another window."
480 (interactive "BSwitch to buffer in other window: ")
481 (let ((pop-up-windows t))
482 (pop-to-buffer buffer t)))
484 (defun switch-to-buffer-other-frame (buffer)
485 "Switch to buffer BUFFER in another frame."
486 (interactive "BSwitch to buffer in other frame: ")
487 (let ((pop-up-frames t))
488 (pop-to-buffer buffer t)
489 (raise-frame (window-frame (selected-window)))))
491 (defun find-file (filename)
492 "Edit file FILENAME.
493 Switch to a buffer visiting file FILENAME,
494 creating one if none already exists."
495 (interactive "FFind file: ")
496 (switch-to-buffer (find-file-noselect filename)))
498 (defun find-file-other-window (filename)
499 "Edit file FILENAME, in another window.
500 May create a new window, or reuse an existing one.
501 See the function `display-buffer'."
502 (interactive "FFind file in other window: ")
503 (switch-to-buffer-other-window (find-file-noselect filename)))
505 (defun find-file-other-frame (filename)
506 "Edit file FILENAME, in another frame.
507 May create a new frame, or reuse an existing one.
508 See the function `display-buffer'."
509 (interactive "FFind file in other frame: ")
510 (switch-to-buffer-other-frame (find-file-noselect filename)))
512 (defun find-file-read-only (filename)
513 "Edit file FILENAME but don't allow changes.
514 Like \\[find-file] but marks buffer as read-only.
515 Use \\[toggle-read-only] to permit editing."
516 (interactive "fFind file read-only: ")
517 (find-file filename)
518 (setq buffer-read-only t)
519 (current-buffer))
521 (defun find-file-read-only-other-window (filename)
522 "Edit file FILENAME in another window but don't allow changes.
523 Like \\[find-file-other-window] but marks buffer as read-only.
524 Use \\[toggle-read-only] to permit editing."
525 (interactive "fFind file read-only other window: ")
526 (find-file-other-window filename)
527 (setq buffer-read-only t)
528 (current-buffer))
530 (defun find-file-read-only-other-frame (filename)
531 "Edit file FILENAME in another frame but don't allow changes.
532 Like \\[find-file-other-frame] but marks buffer as read-only.
533 Use \\[toggle-read-only] to permit editing."
534 (interactive "fFind file read-only other frame: ")
535 (find-file-other-frame filename)
536 (setq buffer-read-only t)
537 (current-buffer))
539 (defun find-alternate-file-other-window (filename)
540 "Find file FILENAME as a replacement for the file in the next window.
541 This command does not select that window."
542 (interactive
543 (save-selected-window
544 (other-window 1)
545 (let ((file buffer-file-name)
546 (file-name nil)
547 (file-dir nil))
548 (and file
549 (setq file-name (file-name-nondirectory file)
550 file-dir (file-name-directory file)))
551 (list (read-file-name
552 "Find alternate file: " file-dir nil nil file-name)))))
553 (if (one-window-p)
554 (find-file-other-window filename)
555 (save-selected-window
556 (other-window 1)
557 (find-alternate-file filename))))
559 (defun find-alternate-file (filename)
560 "Find file FILENAME, select its buffer, kill previous buffer.
561 If the current buffer now contains an empty file that you just visited
562 \(presumably by mistake), use this command to visit the file you really want."
563 (interactive
564 (let ((file buffer-file-name)
565 (file-name nil)
566 (file-dir nil))
567 (and file
568 (setq file-name (file-name-nondirectory file)
569 file-dir (file-name-directory file)))
570 (list (read-file-name
571 "Find alternate file: " file-dir nil nil file-name))))
572 (and (buffer-modified-p) (buffer-file-name)
573 ;; (not buffer-read-only)
574 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
575 (buffer-name))))
576 (error "Aborted"))
577 (let ((obuf (current-buffer))
578 (ofile buffer-file-name)
579 (onum buffer-file-number)
580 (otrue buffer-file-truename)
581 (oname (buffer-name)))
582 (if (get-buffer " **lose**")
583 (kill-buffer " **lose**"))
584 (rename-buffer " **lose**")
585 (setq buffer-file-name nil)
586 (setq buffer-file-number nil)
587 (setq buffer-file-truename nil)
588 (unwind-protect
589 (progn
590 (unlock-buffer)
591 (find-file filename))
592 (cond ((eq obuf (current-buffer))
593 (setq buffer-file-name ofile)
594 (setq buffer-file-number onum)
595 (setq buffer-file-truename otrue)
596 (lock-buffer)
597 (rename-buffer oname))))
598 (or (eq (current-buffer) obuf)
599 (kill-buffer obuf))))
601 (defun create-file-buffer (filename)
602 "Create a suitably named buffer for visiting FILENAME, and return it.
603 FILENAME (sans directory) is used unchanged if that name is free;
604 otherwise a string <2> or <3> or ... is appended to get an unused name."
605 (let ((lastname (file-name-nondirectory filename)))
606 (if (string= lastname "")
607 (setq lastname filename))
608 (generate-new-buffer lastname)))
610 (defun generate-new-buffer (name)
611 "Create and return a buffer with a name based on NAME.
612 Choose the buffer's name using `generate-new-buffer-name'."
613 (get-buffer-create (generate-new-buffer-name name)))
615 (defconst automount-dir-prefix "^/tmp_mnt/"
616 "Regexp to match the automounter prefix in a directory name.")
618 (defvar abbreviated-home-dir nil
619 "The user's homedir abbreviated according to `directory-abbrev-list'.")
621 (defun abbreviate-file-name (filename)
622 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
623 This also substitutes \"~\" for the user's home directory.
624 Type \\[describe-variable] directory-abbrev-alist RET for more information."
625 ;; Get rid of the prefixes added by the automounter.
626 (if (and (string-match automount-dir-prefix filename)
627 (file-exists-p (file-name-directory
628 (substring filename (1- (match-end 0))))))
629 (setq filename (substring filename (1- (match-end 0)))))
630 (let ((tail directory-abbrev-alist))
631 ;; If any elt of directory-abbrev-alist matches this name,
632 ;; abbreviate accordingly.
633 (while tail
634 (if (string-match (car (car tail)) filename)
635 (setq filename
636 (concat (cdr (car tail)) (substring filename (match-end 0)))))
637 (setq tail (cdr tail)))
638 ;; Compute and save the abbreviated homedir name.
639 ;; We defer computing this until the first time it's needed, to
640 ;; give time for directory-abbrev-alist to be set properly.
641 ;; We include a slash at the end, to avoid spurious matches
642 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
643 (or abbreviated-home-dir
644 (setq abbreviated-home-dir
645 (let ((abbreviated-home-dir "$foo"))
646 (concat "^" (abbreviate-file-name (expand-file-name "~"))
647 "\\(/\\|$\\)"))))
649 ;; If FILENAME starts with the abbreviated homedir,
650 ;; make it start with `~' instead.
651 (if (and (string-match abbreviated-home-dir filename)
652 ;; If the home dir is just /, don't change it.
653 (not (and (= (match-end 0) 1)
654 (= (aref filename 0) ?/)))
655 ;; MS-DOS root directories can come with a drive letter;
656 ;; Novell Netware allows drive letters beyond `Z:'.
657 (not (and (or (eq system-type 'ms-dos)
658 (eq system-type 'windows-nt))
659 (save-match-data
660 (string-match "^[a-zA-`]:/$" filename)))))
661 (setq filename
662 (concat "~"
663 (substring filename (match-beginning 1) (match-end 1))
664 (substring filename (match-end 0)))))
665 filename))
667 (defvar find-file-not-true-dirname-list nil
668 "*List of logical names for which visiting shouldn't save the true dirname.
669 On VMS, when you visit a file using a logical name that searches a path,
670 you may or may not want the visited file name to record the specific
671 directory where the file was found. If you *do not* want that, add the logical
672 name to this list as a string.")
674 (defun find-buffer-visiting (filename)
675 "Return the buffer visiting file FILENAME (a string).
676 This is like `get-file-buffer', except that it checks for any buffer
677 visiting the same file, possibly under a different name.
678 If there is no such live buffer, return nil."
679 (let ((buf (get-file-buffer filename))
680 (truename (abbreviate-file-name (file-truename filename))))
681 (or buf
682 (let ((list (buffer-list)) found)
683 (while (and (not found) list)
684 (save-excursion
685 (set-buffer (car list))
686 (if (and buffer-file-name
687 (string= buffer-file-truename truename))
688 (setq found (car list))))
689 (setq list (cdr list)))
690 found)
691 (let ((number (nthcdr 10 (file-attributes truename)))
692 (list (buffer-list)) found)
693 (and number
694 (while (and (not found) list)
695 (save-excursion
696 (set-buffer (car list))
697 (if (and buffer-file-name
698 (equal buffer-file-number number)
699 ;; Verify this buffer's file number
700 ;; still belongs to its file.
701 (file-exists-p buffer-file-name)
702 (equal (nthcdr 10 (file-attributes buffer-file-name))
703 number))
704 (setq found (car list))))
705 (setq list (cdr list))))
706 found))))
708 (defun insert-file-contents-literally (filename &optional visit beg end replace)
709 "Like `insert-file-contents', q.v., but only reads in the file.
710 A buffer may be modified in several ways after reading into the buffer due
711 to advanced Emacs features, such as file-name-handlers, format decoding,
712 find-file-hooks, etc.
713 This function ensures that none of these modifications will take place."
714 (let ((file-name-handler-alist nil)
715 (format-alist nil)
716 (after-insert-file-functions nil)
717 (find-buffer-file-type-function
718 (if (fboundp 'find-buffer-file-type)
719 (symbol-function 'find-buffer-file-type)
720 nil)))
721 (unwind-protect
722 (progn
723 (fset 'find-buffer-file-type (lambda (filename) t))
724 (insert-file-contents filename visit beg end replace))
725 (if find-buffer-file-type-function
726 (fset 'find-buffer-file-type find-buffer-file-type-function)
727 (fmakunbound 'find-buffer-file-type)))))
729 (defun find-file-noselect (filename &optional nowarn rawfile)
730 "Read file FILENAME into a buffer and return the buffer.
731 If a buffer exists visiting FILENAME, return that one, but
732 verify that the file has not changed since visited or saved.
733 The buffer is not selected, just returned to the caller."
734 (setq filename
735 (abbreviate-file-name
736 (expand-file-name filename)))
737 (if (file-directory-p filename)
738 (if find-file-run-dired
739 (dired-noselect (if find-file-visit-truename
740 (abbreviate-file-name (file-truename filename))
741 filename))
742 (error "%s is a directory" filename))
743 (let* ((buf (get-file-buffer filename))
744 (truename (abbreviate-file-name (file-truename filename)))
745 (number (nthcdr 10 (file-attributes truename)))
746 ;; Find any buffer for a file which has same truename.
747 (other (and (not buf) (find-buffer-visiting filename)))
748 error)
749 ;; Let user know if there is a buffer with the same truename.
750 (if other
751 (progn
752 (or nowarn
753 (string-equal filename (buffer-file-name other))
754 (message "%s and %s are the same file"
755 filename (buffer-file-name other)))
756 ;; Optionally also find that buffer.
757 (if (or find-file-existing-other-name find-file-visit-truename)
758 (setq buf other))))
759 (if buf
760 (or nowarn
761 (verify-visited-file-modtime buf)
762 (cond ((not (file-exists-p filename))
763 (error "File %s no longer exists!" filename))
764 ((yes-or-no-p
765 (if (string= (file-name-nondirectory filename)
766 (buffer-name buf))
767 (format
768 (if (buffer-modified-p buf)
769 "File %s changed on disk. Discard your edits? "
770 "File %s changed on disk. Reread from disk? ")
771 (file-name-nondirectory filename))
772 (format
773 (if (buffer-modified-p buf)
774 "File %s changed on disk. Discard your edits in %s? "
775 "File %s changed on disk. Reread from disk into %s? ")
776 (file-name-nondirectory filename)
777 (buffer-name buf))))
778 (save-excursion
779 (set-buffer buf)
780 (revert-buffer t t)))))
781 (save-excursion
782 ;;; The truename stuff makes this obsolete.
783 ;;; (let* ((link-name (car (file-attributes filename)))
784 ;;; (linked-buf (and (stringp link-name)
785 ;;; (get-file-buffer link-name))))
786 ;;; (if (bufferp linked-buf)
787 ;;; (message "Symbolic link to file in buffer %s"
788 ;;; (buffer-name linked-buf))))
789 (setq buf (create-file-buffer filename))
790 (set-buffer-major-mode buf)
791 (set-buffer buf)
792 (erase-buffer)
793 (if rawfile
794 (condition-case ()
795 (insert-file-contents-literally filename t)
796 (file-error
797 ;; Unconditionally set error
798 (setq error t)))
799 (condition-case ()
800 (insert-file-contents filename t)
801 (file-error
802 ;; Run find-file-not-found-hooks until one returns non-nil.
803 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
804 ;; If they fail too, set error.
805 (setq error t)))))
806 ;; Find the file's truename, and maybe use that as visited name.
807 (setq buffer-file-truename truename)
808 (setq buffer-file-number number)
809 ;; On VMS, we may want to remember which directory in a search list
810 ;; the file was found in.
811 (and (eq system-type 'vax-vms)
812 (let (logical)
813 (if (string-match ":" (file-name-directory filename))
814 (setq logical (substring (file-name-directory filename)
815 0 (match-beginning 0))))
816 (not (member logical find-file-not-true-dirname-list)))
817 (setq buffer-file-name buffer-file-truename))
818 (if find-file-visit-truename
819 (setq buffer-file-name
820 (setq filename
821 (expand-file-name buffer-file-truename))))
822 ;; Set buffer's default directory to that of the file.
823 (setq default-directory (file-name-directory filename))
824 ;; Turn off backup files for certain file names. Since
825 ;; this is a permanent local, the major mode won't eliminate it.
826 (and (not (funcall backup-enable-predicate buffer-file-name))
827 (progn
828 (make-local-variable 'backup-inhibited)
829 (setq backup-inhibited t)))
830 (if rawfile
832 (after-find-file error (not nowarn))
833 (setq buf (current-buffer)))))
834 buf)))
836 (defvar after-find-file-from-revert-buffer nil)
838 (defun after-find-file (&optional error warn noauto
839 after-find-file-from-revert-buffer
840 nomodes)
841 "Called after finding a file and by the default revert function.
842 Sets buffer mode, parses local variables.
843 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
844 error in reading the file. WARN non-nil means warn if there
845 exists an auto-save file more recent than the visited file.
846 NOAUTO means don't mess with auto-save mode.
847 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
848 means this call was from `revert-buffer'.
849 Fifth arg NOMODES non-nil means don't alter the file's modes.
850 Finishes by calling the functions in `find-file-hooks'
851 unless NOMODES is non-nil."
852 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
853 (if noninteractive
855 (let* (not-serious
856 (msg
857 (cond ((and error (file-attributes buffer-file-name))
858 (setq buffer-read-only t)
859 "File exists, but cannot be read.")
860 ((not buffer-read-only)
861 (if (and warn
862 (file-newer-than-file-p (make-auto-save-file-name)
863 buffer-file-name))
864 "Auto save file is newer; consider M-x recover-file"
865 (setq not-serious t)
866 (if error "(New file)" nil)))
867 ((not error)
868 (setq not-serious t)
869 "Note: file is write protected")
870 ((file-attributes (directory-file-name default-directory))
871 "File not found and directory write-protected")
872 ((file-exists-p (file-name-directory buffer-file-name))
873 (setq buffer-read-only nil))
875 (setq buffer-read-only nil)
876 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
877 "Use M-x make-dir RET RET to create the directory"
878 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
879 (if msg
880 (progn
881 (message msg)
882 (or not-serious (sit-for 1 nil t)))))
883 (if (and auto-save-default (not noauto))
884 (auto-save-mode t)))
885 (if nomodes
887 (normal-mode t)
888 (run-hooks 'find-file-hooks)))
890 (defun normal-mode (&optional find-file)
891 "Choose the major mode for this buffer automatically.
892 Also sets up any specified local variables of the file.
893 Uses the visited file name, the -*- line, and the local variables spec.
895 This function is called automatically from `find-file'. In that case,
896 we may set up specified local variables depending on the value of
897 `enable-local-variables': if it is t, we do; if it is nil, we don't;
898 otherwise, we query. `enable-local-variables' is ignored if you
899 run `normal-mode' explicitly."
900 (interactive)
901 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
902 (condition-case err
903 (set-auto-mode)
904 (error (message "File mode specification error: %s"
905 (prin1-to-string err))))
906 (condition-case err
907 (let ((enable-local-variables (or (not find-file)
908 enable-local-variables)))
909 (hack-local-variables))
910 (error (message "File local-variables error: %s"
911 (prin1-to-string err)))))
913 (defvar auto-mode-alist
914 '(("\\.te?xt\\'" . text-mode)
915 ("\\.c\\'" . c-mode)
916 ("\\.h\\'" . c-mode)
917 ("\\.tex\\'" . tex-mode)
918 ("\\.ltx\\'" . latex-mode)
919 ("\\.el\\'" . emacs-lisp-mode)
920 ("\\.mm\\'" . nroff-mode)
921 ("\\.me\\'" . nroff-mode)
922 ("\\.ms\\'" . nroff-mode)
923 ("\\.man\\'" . nroff-mode)
924 ("\\.scm\\'" . scheme-mode)
925 ("\\.l\\'" . lisp-mode)
926 ("\\.lisp\\'" . lisp-mode)
927 ("\\.f\\'" . fortran-mode)
928 ("\\.for\\'" . fortran-mode)
929 ("\\.p\\'" . pascal-mode)
930 ("\\.pas\\'" . pascal-mode)
931 ("\\.mss\\'" . scribe-mode)
932 ("\\.ad[abs]\\'" . ada-mode)
933 ("\\.icn\\'" . icon-mode)
934 ("\\.pl\\'" . perl-mode)
935 ("\\.cc\\'" . c++-mode)
936 ("\\.hh\\'" . c++-mode)
937 ("\\.C\\'" . c++-mode)
938 ("\\.H\\'" . c++-mode)
939 ("\\.cpp\\'" . c++-mode)
940 ("\\.cxx\\'" . c++-mode)
941 ("\\.hxx\\'" . c++-mode)
942 ("\\.c\\+\\+\\'" . c++-mode)
943 ("\\.h\\+\\+\\'" . c++-mode)
944 ("\\.mk\\'" . makefile-mode)
945 ("\\(M\\|m\\|GNUm\\)akefile\\(.in\\)?\\'" . makefile-mode)
946 ;;; Less common extensions come here
947 ;;; so more common ones above are found faster.
948 ("\\.texinfo\\'" . texinfo-mode)
949 ("\\.te?xi\\'" . texinfo-mode)
950 ("\\.s\\'" . asm-mode)
951 ("\\.S\\'" . asm-mode)
952 ("\\.asm\\'" . asm-mode)
953 ("ChangeLog\\'" . change-log-mode)
954 ("change.log\\'" . change-log-mode)
955 ("changelo\\'" . change-log-mode)
956 ("ChangeLog.[0-9]+\\'" . change-log-mode)
957 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
958 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
959 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
960 ("/\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
961 ("/\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
962 ("/\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
963 ;;; The following should come after the ChangeLog pattern
964 ;;; for the sake of ChangeLog.1, etc.
965 ;;; and after the .scm.[0-9] pattern too.
966 ("\\.[12345678]\\'" . nroff-mode)
967 ("\\.TeX\\'" . tex-mode)
968 ("\\.sty\\'" . latex-mode)
969 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
970 ("\\.bbl\\'" . latex-mode)
971 ("\\.bib\\'" . bibtex-mode)
972 ("\\.article\\'" . text-mode)
973 ("\\.letter\\'" . text-mode)
974 ("\\.tcl\\'" . tcl-mode)
975 ("\\.exp\\'" . tcl-mode)
976 ("\\.itcl\\'" . tcl-mode)
977 ("\\.itk\\'" . tcl-mode)
978 ("\\.f90\\'" . f90-mode)
979 ("\\.lsp\\'" . lisp-mode)
980 ("\\.awk\\'" . awk-mode)
981 ("\\.prolog\\'" . prolog-mode)
982 ("\\.tar\\'" . tar-mode)
983 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\)\\'" . archive-mode)
984 ;; Mailer puts message to be edited in
985 ;; /tmp/Re.... or Message
986 ("\\`/tmp/Re" . text-mode)
987 ("/Message[0-9]*\\'" . text-mode)
988 ("/drafts/[0-9]+\\'" . mh-letter-mode)
989 ;; some news reader is reported to use this
990 ("\\`/tmp/fol/" . text-mode)
991 ("\\.y\\'" . c-mode)
992 ("\\.lex\\'" . c-mode)
993 ("\\.oak\\'" . scheme-mode)
994 ("\\.sgml?\\'" . sgml-mode)
995 ("\\.dtd\\'" . sgml-mode)
996 ("\\.s?html?\\'" . html-mode)
997 ;; .emacs following a directory delimiter
998 ;; in either Unix or VMS syntax.
999 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
1000 ;; _emacs following a directory delimiter
1001 ;; in MsDos syntax
1002 ("[:/]_emacs\\'" . emacs-lisp-mode)
1003 ("\\.ml\\'" . lisp-mode))
1005 Alist of filename patterns vs corresponding major mode functions.
1006 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1007 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1008 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1009 mode function to use. FUNCTION will be called, unless it is nil.
1011 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1012 calling FUNCTION (if it's not nil), we delete the suffix that matched
1013 REGEXP and search the list again for another match.")
1015 (defconst interpreter-mode-alist
1016 '(("perl" . perl-mode)
1017 ("wish" . tcl-mode)
1018 ("wishx" . tcl-mode)
1019 ("tcl" . tcl-mode)
1020 ("tclsh" . tcl-mode)
1021 ("awk" . awk-mode)
1022 ("mawk" . awk-mode)
1023 ("nawk" . awk-mode)
1024 ("gawk" . awk-mode)
1025 ("scm" . scheme-mode)
1026 ("ash" . sh-mode)
1027 ("bash" . sh-mode)
1028 ("csh" . sh-mode)
1029 ("dtksh" . sh-mode)
1030 ("es" . sh-mode)
1031 ("itcsh" . sh-mode)
1032 ("jsh" . sh-mode)
1033 ("ksh" . sh-mode)
1034 ("oash" . sh-mode)
1035 ("pdksh" . sh-mode)
1036 ("rc" . sh-mode)
1037 ("sh" . sh-mode)
1038 ("sh5" . sh-mode)
1039 ("tcsh" . sh-mode)
1040 ("wksh" . sh-mode)
1041 ("wsh" . sh-mode)
1042 ("zsh" . sh-mode)
1043 ("tail" . text-mode)
1044 ("more" . text-mode)
1045 ("less" . text-mode)
1046 ("pg" . text-mode))
1047 "Alist mapping interpreter names to major modes.
1048 This alist applies to files whose first line starts with `#!'.
1049 Each element looks like (INTERPRETER . MODE).
1050 The car of each element is compared with
1051 the name of the interpreter specified in the first line.
1052 If it matches, mode MODE is selected.")
1054 (defconst inhibit-first-line-modes-regexps '("\\.tar\\'")
1055 "List of regexps; if one matches a file name, don't look for `-*-'.")
1057 (defconst inhibit-first-line-modes-suffixes nil
1058 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1059 When checking `inhibit-first-line-modes-regexps', we first discard
1060 from the end of the file name anything that matches one of these regexps.")
1062 (defvar user-init-file
1063 "" ; set by command-line
1064 "File name including directory of user's initialization file.")
1066 (defun set-auto-mode ()
1067 "Select major mode appropriate for current buffer.
1068 This checks for a -*- mode tag in the buffer's text,
1069 compares the filename against the entries in `auto-mode-alist',
1070 or checks the interpreter that runs this file against
1071 `interpreter-mode-alist'.
1073 It does not check for the `mode:' local variable in the
1074 Local Variables section of the file; for that, use `hack-local-variables'.
1076 If `enable-local-variables' is nil, this function does not check for a
1077 -*- mode tag."
1078 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1079 (let (beg end done modes)
1080 (save-excursion
1081 (goto-char (point-min))
1082 (skip-chars-forward " \t\n")
1083 (and enable-local-variables
1084 ;; Don't look for -*- if this file name matches any
1085 ;; of the regexps in inhibit-first-line-modes-regexps.
1086 (let ((temp inhibit-first-line-modes-regexps)
1087 (name (if buffer-file-name
1088 (file-name-sans-versions buffer-file-name)
1089 (buffer-name))))
1090 (while (let ((sufs inhibit-first-line-modes-suffixes))
1091 (while (and sufs (not (string-match (car sufs) name)))
1092 (setq sufs (cdr sufs)))
1093 sufs)
1094 (setq name (substring name 0 (match-beginning 0))))
1095 (while (and temp
1096 (not (string-match (car temp) name)))
1097 (setq temp (cdr temp)))
1098 (not temp))
1099 (search-forward "-*-" (save-excursion
1100 ;; If the file begins with "#!"
1101 ;; (exec interpreter magic), look
1102 ;; for mode frobs in the first two
1103 ;; lines. You cannot necessarily
1104 ;; put them in the first line of
1105 ;; such a file without screwing up
1106 ;; the interpreter invocation.
1107 (end-of-line (and (looking-at "^#!") 2))
1108 (point)) t)
1109 (progn
1110 (skip-chars-forward " \t")
1111 (setq beg (point))
1112 (search-forward "-*-"
1113 (save-excursion (end-of-line) (point))
1115 (progn
1116 (forward-char -3)
1117 (skip-chars-backward " \t")
1118 (setq end (point))
1119 (goto-char beg)
1120 (if (save-excursion (search-forward ":" end t))
1121 ;; Find all specifications for the `mode:' variable
1122 ;; and execute them left to right.
1123 (while (let ((case-fold-search t))
1124 (or (and (looking-at "mode:")
1125 (goto-char (match-end 0)))
1126 (re-search-forward "[ \t;]mode:" end t)))
1127 (skip-chars-forward " \t")
1128 (setq beg (point))
1129 (if (search-forward ";" end t)
1130 (forward-char -1)
1131 (goto-char end))
1132 (skip-chars-backward " \t")
1133 (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1134 modes)))
1135 ;; Simple -*-MODE-*- case.
1136 (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
1137 "-mode"))
1138 modes))))))
1139 ;; If we found modes to use, invoke them now,
1140 ;; outside the save-excursion.
1141 (if modes
1142 (progn (mapcar 'funcall modes)
1143 (setq done t)))
1144 ;; If we didn't find a mode from a -*- line, try using the file name.
1145 (if (and (not done) buffer-file-name)
1146 (let ((name buffer-file-name)
1147 (keep-going t))
1148 ;; Remove backup-suffixes from file name.
1149 (setq name (file-name-sans-versions name))
1150 (while keep-going
1151 (setq keep-going nil)
1152 (let ((alist auto-mode-alist)
1153 (mode nil))
1154 ;; Find first matching alist entry.
1155 (let ((case-fold-search
1156 (memq system-type '(vax-vms windows-nt))))
1157 (while (and (not mode) alist)
1158 (if (string-match (car (car alist)) name)
1159 (if (and (consp (cdr (car alist)))
1160 (nth 2 (car alist)))
1161 (progn
1162 (setq mode (car (cdr (car alist)))
1163 name (substring name 0 (match-beginning 0))
1164 keep-going t))
1165 (setq mode (cdr (car alist))
1166 keep-going nil)))
1167 (setq alist (cdr alist))))
1168 (if mode
1169 (funcall mode)
1170 ;; If we can't deduce a mode from the file name,
1171 ;; look for an interpreter specified in the first line.
1172 ;; As a special case, allow for things like "#!/bin/env perl",
1173 ;; which finds the interpreter anywhere in $PATH.
1174 (let ((interpreter
1175 (save-excursion
1176 (goto-char (point-min))
1177 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1178 (buffer-substring (match-beginning 2)
1179 (match-end 2))
1180 "")))
1181 elt)
1182 ;; Map interpreter name to a mode.
1183 (setq elt (assoc (file-name-nondirectory interpreter)
1184 interpreter-mode-alist))
1185 (if elt
1186 (funcall (cdr elt)))))))))))
1188 (defun hack-local-variables-prop-line ()
1189 ;; Set local variables specified in the -*- line.
1190 ;; Ignore any specification for `mode:';
1191 ;; set-auto-mode should already have handled that.
1192 (save-excursion
1193 (goto-char (point-min))
1194 (let ((result nil)
1195 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
1196 ;; Parse the -*- line into the `result' alist.
1197 (cond ((not (search-forward "-*-" end t))
1198 ;; doesn't have one.
1199 nil)
1200 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1201 ;; Simple form: "-*- MODENAME -*-". Already handled.
1202 nil)
1204 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1205 ;; (last ";" is optional).
1206 (save-excursion
1207 (if (search-forward "-*-" end t)
1208 (setq end (- (point) 3))
1209 (error "-*- not terminated before end of line")))
1210 (while (< (point) end)
1211 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1212 (error "malformed -*- line"))
1213 (goto-char (match-end 0))
1214 ;; There used to be a downcase here,
1215 ;; but the manual didn't say so,
1216 ;; and people want to set var names that aren't all lc.
1217 (let ((key (intern (buffer-substring
1218 (match-beginning 1)
1219 (match-end 1))))
1220 (val (save-restriction
1221 (narrow-to-region (point) end)
1222 (read (current-buffer)))))
1223 (or (eq key 'mode)
1224 (setq result (cons (cons key val) result)))
1225 (skip-chars-forward " \t;")))
1226 (setq result (nreverse result))))
1228 (if (and result
1229 (or (eq enable-local-variables t)
1230 (and enable-local-variables
1231 (save-window-excursion
1232 (condition-case nil
1233 (switch-to-buffer (current-buffer))
1234 (error
1235 ;; If we fail to switch in the selected window,
1236 ;; it is probably a minibuffer.
1237 ;; So try another window.
1238 (condition-case nil
1239 (switch-to-buffer-other-window (current-buffer))
1240 (error
1241 (switch-to-buffer-other-frame (current-buffer))))))
1242 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1243 (file-name-nondirectory buffer-file-name)))))))
1244 (while result
1245 (hack-one-local-variable (car (car result)) (cdr (car result)))
1246 (setq result (cdr result)))))))
1248 (defvar hack-local-variables-hook nil
1249 "Normal hook run after processing a file's local variables specs.
1250 Major modes can use this to examine user-specified local variables
1251 in order to initialize other data structure based on them.")
1253 (defun hack-local-variables ()
1254 "Parse and put into effect this buffer's local variables spec."
1255 (hack-local-variables-prop-line)
1256 ;; Look for "Local variables:" line in last page.
1257 (save-excursion
1258 (goto-char (point-max))
1259 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1260 (if (let ((case-fold-search t))
1261 (and (search-forward "Local Variables:" nil t)
1262 (or (eq enable-local-variables t)
1263 (and enable-local-variables
1264 (save-window-excursion
1265 (switch-to-buffer (current-buffer))
1266 (save-excursion
1267 (beginning-of-line)
1268 (set-window-start (selected-window) (point)))
1269 (y-or-n-p (format "Set local variables as specified at end of %s? "
1270 (if buffer-file-name
1271 (file-name-nondirectory
1272 buffer-file-name)
1273 (concat "buffer "
1274 (buffer-name))))))))))
1275 (let ((continue t)
1276 prefix prefixlen suffix beg
1277 (enable-local-eval enable-local-eval))
1278 ;; The prefix is what comes before "local variables:" in its line.
1279 ;; The suffix is what comes after "local variables:" in its line.
1280 (skip-chars-forward " \t")
1281 (or (eolp)
1282 (setq suffix (buffer-substring (point)
1283 (progn (end-of-line) (point)))))
1284 (goto-char (match-beginning 0))
1285 (or (bolp)
1286 (setq prefix
1287 (buffer-substring (point)
1288 (progn (beginning-of-line) (point)))))
1290 (if prefix (setq prefixlen (length prefix)
1291 prefix (regexp-quote prefix)))
1292 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1293 (while continue
1294 ;; Look at next local variable spec.
1295 (if selective-display (re-search-forward "[\n\C-m]")
1296 (forward-line 1))
1297 ;; Skip the prefix, if any.
1298 (if prefix
1299 (if (looking-at prefix)
1300 (forward-char prefixlen)
1301 (error "Local variables entry is missing the prefix")))
1302 ;; Find the variable name; strip whitespace.
1303 (skip-chars-forward " \t")
1304 (setq beg (point))
1305 (skip-chars-forward "^:\n")
1306 (if (eolp) (error "Missing colon in local variables entry"))
1307 (skip-chars-backward " \t")
1308 (let* ((str (buffer-substring beg (point)))
1309 (var (read str))
1310 val)
1311 ;; Setting variable named "end" means end of list.
1312 (if (string-equal (downcase str) "end")
1313 (setq continue nil)
1314 ;; Otherwise read the variable value.
1315 (skip-chars-forward "^:")
1316 (forward-char 1)
1317 (setq val (read (current-buffer)))
1318 (skip-chars-backward "\n")
1319 (skip-chars-forward " \t")
1320 (or (if suffix (looking-at suffix) (eolp))
1321 (error "Local variables entry is terminated incorrectly"))
1322 ;; Set the variable. "Variables" mode and eval are funny.
1323 (hack-one-local-variable var val)))))))
1324 (run-hooks 'hack-local-variables-hook))
1326 (defconst ignored-local-variables
1327 '(enable-local-eval)
1328 "Variables to be ignored in a file's local variable spec.")
1330 ;; Get confirmation before setting these variables as locals in a file.
1331 (put 'debugger 'risky-local-variable t)
1332 (put 'enable-local-eval 'risky-local-variable t)
1333 (put 'ignored-local-variables 'risky-local-variable t)
1334 (put 'eval 'risky-local-variable t)
1335 (put 'file-name-handler-alist 'risky-local-variable t)
1336 (put 'minor-mode-map-alist 'risky-local-variable t)
1337 (put 'after-load-alist 'risky-local-variable t)
1338 (put 'buffer-file-name 'risky-local-variable t)
1339 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1340 (put 'buffer-file-truename 'risky-local-variable t)
1341 (put 'exec-path 'risky-local-variable t)
1342 (put 'load-path 'risky-local-variable t)
1343 (put 'exec-directory 'risky-local-variable t)
1344 (put 'process-environment 'risky-local-variable t)
1345 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1346 (put 'outline-level 'risky-local-variable t)
1347 (put 'rmail-output-file-alist 'risky-local-variable t)
1349 ;; This one is safe because the user gets to check it before it is used.
1350 (put 'compile-command 'safe-local-variable t)
1352 (defun hack-one-local-variable-quotep (exp)
1353 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1355 ;; "Set" one variable in a local variables spec.
1356 ;; A few variable names are treated specially.
1357 (defun hack-one-local-variable (var val)
1358 (cond ((eq var 'mode)
1359 (funcall (intern (concat (downcase (symbol-name val))
1360 "-mode"))))
1361 ((memq var ignored-local-variables)
1362 nil)
1363 ;; "Setting" eval means either eval it or do nothing.
1364 ;; Likewise for setting hook variables.
1365 ((or (get var 'risky-local-variable)
1366 (and
1367 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
1368 (symbol-name var))
1369 (not (get var 'safe-local-variable))))
1370 ;; Permit evalling a put of a harmless property.
1371 ;; if the args do nothing tricky.
1372 (if (or (and (eq var 'eval)
1373 (consp val)
1374 (eq (car val) 'put)
1375 (hack-one-local-variable-quotep (nth 1 val))
1376 (hack-one-local-variable-quotep (nth 2 val))
1377 ;; Only allow safe values of lisp-indent-hook;
1378 ;; not functions.
1379 (or (numberp (nth 3 val))
1380 (equal (nth 3 val) ''defun))
1381 (memq (nth 1 (nth 2 val))
1382 '(lisp-indent-hook)))
1383 ;; Permit eval if not root and user says ok.
1384 (and (not (zerop (user-uid)))
1385 (or (eq enable-local-eval t)
1386 (and enable-local-eval
1387 (save-window-excursion
1388 (switch-to-buffer (current-buffer))
1389 (save-excursion
1390 (beginning-of-line)
1391 (set-window-start (selected-window) (point)))
1392 (setq enable-local-eval
1393 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1394 (file-name-nondirectory buffer-file-name)))))))))
1395 (if (eq var 'eval)
1396 (save-excursion (eval val))
1397 (make-local-variable var)
1398 (set var val))
1399 (message "Ignoring `eval:' in file's local variables")))
1400 ;; Ordinary variable, really set it.
1401 (t (make-local-variable var)
1402 (set var val))))
1405 (defun set-visited-file-name (filename)
1406 "Change name of file visited in current buffer to FILENAME.
1407 The next time the buffer is saved it will go in the newly specified file.
1408 nil or empty string as argument means make buffer not be visiting any file.
1409 Remember to delete the initial contents of the minibuffer
1410 if you wish to pass an empty string as the argument."
1411 (interactive "FSet visited file name: ")
1412 (if (buffer-base-buffer)
1413 (error "An indirect buffer cannot visit a file"))
1414 (let (truename)
1415 (if filename
1416 (setq filename
1417 (if (string-equal filename "")
1419 (expand-file-name filename))))
1420 (if filename
1421 (progn
1422 (setq truename (file-truename filename))
1423 (if find-file-visit-truename
1424 (setq filename truename))))
1425 (or (equal filename buffer-file-name)
1426 (progn
1427 (and filename (lock-buffer filename))
1428 (unlock-buffer)))
1429 (setq buffer-file-name filename)
1430 (if filename ; make buffer name reflect filename.
1431 (let ((new-name (file-name-nondirectory buffer-file-name)))
1432 (if (string= new-name "")
1433 (error "Empty file name"))
1434 (if (eq system-type 'vax-vms)
1435 (setq new-name (downcase new-name)))
1436 (setq default-directory (file-name-directory buffer-file-name))
1437 (or (string= new-name (buffer-name))
1438 (rename-buffer new-name t))))
1439 (setq buffer-backed-up nil)
1440 (clear-visited-file-modtime)
1441 ;; Abbreviate the file names of the buffer.
1442 (if truename
1443 (progn
1444 (setq buffer-file-truename (abbreviate-file-name truename))
1445 (if find-file-visit-truename
1446 (setq buffer-file-name buffer-file-truename))))
1447 (setq buffer-file-number
1448 (if filename
1449 (nthcdr 10 (file-attributes buffer-file-name))
1450 nil)))
1451 ;; write-file-hooks is normally used for things like ftp-find-file
1452 ;; that visit things that are not local files as if they were files.
1453 ;; Changing to visit an ordinary local file instead should flush the hook.
1454 (kill-local-variable 'write-file-hooks)
1455 (kill-local-variable 'local-write-file-hooks)
1456 (kill-local-variable 'revert-buffer-function)
1457 (kill-local-variable 'backup-inhibited)
1458 ;; If buffer was read-only because of version control,
1459 ;; that reason is gone now, so make it writable.
1460 (if vc-mode
1461 (setq buffer-read-only nil))
1462 (kill-local-variable 'vc-mode)
1463 ;; Turn off backup files for certain file names.
1464 ;; Since this is a permanent local, the major mode won't eliminate it.
1465 (and (not (funcall backup-enable-predicate buffer-file-name))
1466 (progn
1467 (make-local-variable 'backup-inhibited)
1468 (setq backup-inhibited t)))
1469 (let ((oauto buffer-auto-save-file-name))
1470 ;; If auto-save was not already on, turn it on if appropriate.
1471 (if (not buffer-auto-save-file-name)
1472 (and buffer-file-name auto-save-default
1473 (auto-save-mode t))
1474 ;; If auto save is on, start using a new name.
1475 ;; We deliberately don't rename or delete the old auto save
1476 ;; for the old visited file name. This is because perhaps
1477 ;; the user wants to save the new state and then compare with the
1478 ;; previous state from the auto save file.
1479 (setq buffer-auto-save-file-name
1480 (make-auto-save-file-name)))
1481 ;; Rename the old auto save file if any.
1482 (and oauto buffer-auto-save-file-name
1483 (file-exists-p oauto)
1484 (rename-file oauto buffer-auto-save-file-name t)))
1485 (if buffer-file-name
1486 (set-buffer-modified-p t)))
1488 (defun write-file (filename &optional confirm)
1489 "Write current buffer into file FILENAME.
1490 Makes buffer visit that file, and marks it not modified.
1491 If the buffer is already visiting a file, you can specify
1492 a directory name as FILENAME, to write a file of the same
1493 old name in that directory.
1495 If optional second arg CONFIRM is non-nil,
1496 ask for confirmation for overwriting an existing file.
1497 Interactively, confirmation is required unless you supply a prefix argument."
1498 ;; (interactive "FWrite file: ")
1499 (interactive
1500 (list (if buffer-file-name
1501 (read-file-name "Write file: "
1502 nil nil nil nil)
1503 (read-file-name "Write file: "
1504 (cdr (assq 'default-directory
1505 (buffer-local-variables)))
1506 nil nil (buffer-name)))
1507 (not current-prefix-arg)))
1508 (or (null filename) (string-equal filename "")
1509 (progn
1510 ;; If arg is just a directory,
1511 ;; use same file name, but in that directory.
1512 (if (and (file-directory-p filename) buffer-file-name)
1513 (setq filename (concat (file-name-as-directory filename)
1514 (file-name-nondirectory buffer-file-name))))
1515 (and confirm
1516 (file-exists-p filename)
1517 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1518 (error "Canceled")))
1519 (set-visited-file-name filename)))
1520 (set-buffer-modified-p t)
1521 (save-buffer))
1523 (defun backup-buffer ()
1524 "Make a backup of the disk file visited by the current buffer, if appropriate.
1525 This is normally done before saving the buffer the first time.
1526 If the value is non-nil, it is the result of `file-modes' on the original
1527 file; this means that the caller, after saving the buffer, should change
1528 the modes of the new file to agree with the old modes."
1529 (if (and make-backup-files (not backup-inhibited)
1530 (not buffer-backed-up)
1531 (file-exists-p buffer-file-name)
1532 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1533 '(?- ?l)))
1534 (let ((real-file-name buffer-file-name)
1535 backup-info backupname targets setmodes)
1536 ;; If specified name is a symbolic link, chase it to the target.
1537 ;; Thus we make the backups in the directory where the real file is.
1538 (setq real-file-name (file-chase-links real-file-name))
1539 (setq backup-info (find-backup-file-name real-file-name)
1540 backupname (car backup-info)
1541 targets (cdr backup-info))
1542 ;;; (if (file-directory-p buffer-file-name)
1543 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1544 (if backup-info
1545 (condition-case ()
1546 (let ((delete-old-versions
1547 ;; If have old versions to maybe delete,
1548 ;; ask the user to confirm now, before doing anything.
1549 ;; But don't actually delete til later.
1550 (and targets
1551 (or (eq delete-old-versions t) (eq delete-old-versions nil))
1552 (or delete-old-versions
1553 (y-or-n-p (format "Delete excess backup versions of %s? "
1554 real-file-name))))))
1555 ;; Actually write the back up file.
1556 (condition-case ()
1557 (if (or file-precious-flag
1558 ; (file-symlink-p buffer-file-name)
1559 backup-by-copying
1560 (and backup-by-copying-when-linked
1561 (> (file-nlinks real-file-name) 1))
1562 (and backup-by-copying-when-mismatch
1563 (let ((attr (file-attributes real-file-name)))
1564 (or (nth 9 attr)
1565 (not (file-ownership-preserved-p real-file-name))))))
1566 (condition-case ()
1567 (copy-file real-file-name backupname t t)
1568 (file-error
1569 ;; If copying fails because file BACKUPNAME
1570 ;; is not writable, delete that file and try again.
1571 (if (and (file-exists-p backupname)
1572 (not (file-writable-p backupname)))
1573 (delete-file backupname))
1574 (copy-file real-file-name backupname t t)))
1575 ;; rename-file should delete old backup.
1576 (rename-file real-file-name backupname t)
1577 (setq setmodes (file-modes backupname)))
1578 (file-error
1579 ;; If trouble writing the backup, write it in ~.
1580 (setq backupname (expand-file-name
1581 (convert-standard-filename
1582 "~/%backup%~")))
1583 (message "Cannot write backup file; backing up in %s"
1584 (file-name-nondirectory backupname))
1585 (sleep-for 1)
1586 (condition-case ()
1587 (copy-file real-file-name backupname t t)
1588 (file-error
1589 ;; If copying fails because file BACKUPNAME
1590 ;; is not writable, delete that file and try again.
1591 (if (and (file-exists-p backupname)
1592 (not (file-writable-p backupname)))
1593 (delete-file backupname))
1594 (copy-file real-file-name backupname t t)))))
1595 (setq buffer-backed-up t)
1596 ;; Now delete the old versions, if desired.
1597 (if delete-old-versions
1598 (while targets
1599 (condition-case ()
1600 (delete-file (car targets))
1601 (file-error nil))
1602 (setq targets (cdr targets))))
1603 setmodes)
1604 (file-error nil))))))
1606 (defun file-name-sans-versions (name &optional keep-backup-version)
1607 "Return FILENAME sans backup versions or strings.
1608 This is a separate procedure so your site-init or startup file can
1609 redefine it.
1610 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1611 we do not remove backup version numbers, only true file version numbers."
1612 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1613 (if handler
1614 (funcall handler 'file-name-sans-versions name keep-backup-version)
1615 (substring name 0
1616 (if (eq system-type 'vax-vms)
1617 ;; VMS version number is (a) semicolon, optional
1618 ;; sign, zero or more digits or (b) period, option
1619 ;; sign, zero or more digits, provided this is the
1620 ;; second period encountered outside of the
1621 ;; device/directory part of the file name.
1622 (or (string-match ";[-+]?[0-9]*\\'" name)
1623 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1624 name)
1625 (match-beginning 1))
1626 (length name))
1627 (if keep-backup-version
1628 (length name)
1629 (or (string-match "\\.~[0-9.]+~\\'" name)
1630 (string-match "~\\'" name)
1631 (length name))))))))
1633 (defun file-ownership-preserved-p (file)
1634 "Returns t if deleting FILE and rewriting it would preserve the owner."
1635 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1636 (if handler
1637 (funcall handler 'file-ownership-preserved-p file)
1638 (let ((attributes (file-attributes file)))
1639 ;; Return t if the file doesn't exist, since it's true that no
1640 ;; information would be lost by an (attempted) delete and create.
1641 (or (null attributes)
1642 (= (nth 2 attributes) (user-uid)))))))
1644 (defun file-name-sans-extension (filename)
1645 "Return FILENAME sans final \"extension\".
1646 The extension, in a file name, is the part that follows the last `.'."
1647 (save-match-data
1648 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1649 directory)
1650 (if (string-match "\\.[^.]*\\'" file)
1651 (if (setq directory (file-name-directory filename))
1652 (expand-file-name (substring file 0 (match-beginning 0))
1653 directory)
1654 (substring file 0 (match-beginning 0)))
1655 filename))))
1657 (defun make-backup-file-name (file)
1658 "Create the non-numeric backup file name for FILE.
1659 This is a separate function so you can redefine it for customization."
1660 (if (eq system-type 'ms-dos)
1661 (let ((fn (file-name-nondirectory file)))
1662 (concat (file-name-directory file)
1664 (and (string-match "\\`[^.]+\\'" fn)
1665 (concat (match-string 0 fn) ".~"))
1666 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
1667 (concat (match-string 0 fn) "~")))))
1668 (concat file "~")))
1670 (defun backup-file-name-p (file)
1671 "Return non-nil if FILE is a backup file name (numeric or not).
1672 This is a separate function so you can redefine it for customization.
1673 You may need to redefine `file-name-sans-versions' as well."
1674 (string-match "~\\'" file))
1676 ;; This is used in various files.
1677 ;; The usage of bv-length is not very clean,
1678 ;; but I can't see a good alternative,
1679 ;; so as of now I am leaving it alone.
1680 (defun backup-extract-version (fn)
1681 "Given the name of a numeric backup file, return the backup number.
1682 Uses the free variable `bv-length', whose value should be
1683 the index in the name where the version number begins."
1684 (if (and (string-match "[0-9]+~$" fn bv-length)
1685 (= (match-beginning 0) bv-length))
1686 (string-to-int (substring fn bv-length -1))
1689 ;; I believe there is no need to alter this behavior for VMS;
1690 ;; since backup files are not made on VMS, it should not get called.
1691 (defun find-backup-file-name (fn)
1692 "Find a file name for a backup file, and suggestions for deletions.
1693 Value is a list whose car is the name for the backup file
1694 and whose cdr is a list of old versions to consider deleting now.
1695 If the value is nil, don't make a backup."
1696 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
1697 ;; Run a handler for this function so that ange-ftp can refuse to do it.
1698 (if handler
1699 (funcall handler 'find-backup-file-name fn)
1700 (if (eq version-control 'never)
1701 (list (make-backup-file-name fn))
1702 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1703 (bv-length (length base-versions))
1704 possibilities
1705 (versions nil)
1706 (high-water-mark 0)
1707 (deserve-versions-p nil)
1708 (number-to-delete 0))
1709 (condition-case ()
1710 (setq possibilities (file-name-all-completions
1711 base-versions
1712 (file-name-directory fn))
1713 versions (sort (mapcar
1714 (function backup-extract-version)
1715 possibilities)
1717 high-water-mark (apply 'max 0 versions)
1718 deserve-versions-p (or version-control
1719 (> high-water-mark 0))
1720 number-to-delete (- (length versions)
1721 kept-old-versions kept-new-versions -1))
1722 (file-error
1723 (setq possibilities nil)))
1724 (if (not deserve-versions-p)
1725 (list (make-backup-file-name fn))
1726 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
1727 (if (and (> number-to-delete 0)
1728 ;; Delete nothing if there is overflow
1729 ;; in the number of versions to keep.
1730 (>= (+ kept-new-versions kept-old-versions -1) 0))
1731 (mapcar (function (lambda (n)
1732 (concat fn ".~" (int-to-string n) "~")))
1733 (let ((v (nthcdr kept-old-versions versions)))
1734 (rplacd (nthcdr (1- number-to-delete) v) ())
1735 v))))))))))
1737 (defun file-nlinks (filename)
1738 "Return number of names file FILENAME has."
1739 (car (cdr (file-attributes filename))))
1741 (defun file-relative-name (filename &optional directory)
1742 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1743 (setq filename (expand-file-name filename)
1744 directory (file-name-as-directory (expand-file-name
1745 (or directory default-directory))))
1746 (let ((ancestor ""))
1747 (while (not (string-match (concat "^" (regexp-quote directory)) filename))
1748 (setq directory (file-name-directory (substring directory 0 -1))
1749 ancestor (concat "../" ancestor)))
1750 (concat ancestor (substring filename (match-end 0)))))
1752 (defun save-buffer (&optional args)
1753 "Save current buffer in visited file if modified. Versions described below.
1754 By default, makes the previous version into a backup file
1755 if previously requested or if this is the first save.
1756 With 1 \\[universal-argument], marks this version
1757 to become a backup when the next save is done.
1758 With 2 \\[universal-argument]'s,
1759 unconditionally makes the previous version into a backup file.
1760 With 3 \\[universal-argument]'s, marks this version
1761 to become a backup when the next save is done,
1762 and unconditionally makes the previous version into a backup file.
1764 With argument of 0, never makes the previous version into a backup file.
1766 If a file's name is FOO, the names of its numbered backup versions are
1767 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1768 Numeric backups (rather than FOO~) will be made if value of
1769 `version-control' is not the atom `never' and either there are already
1770 numeric versions of the file being backed up, or `version-control' is
1771 non-nil.
1772 We don't want excessive versions piling up, so there are variables
1773 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1774 and `kept-new-versions', which tells how many newest versions to keep.
1775 Defaults are 2 old versions and 2 new.
1776 `dired-kept-versions' controls dired's clean-directory (.) command.
1777 If `delete-old-versions' is nil, system will query user
1778 before trimming versions. Otherwise it does it silently."
1779 (interactive "p")
1780 (let ((modp (buffer-modified-p))
1781 (large (> (buffer-size) 50000))
1782 (make-backup-files (or (and make-backup-files (not (eq args 0)))
1783 (memq args '(16 64)))))
1784 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
1785 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
1786 (basic-save-buffer)
1787 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
1789 (defun delete-auto-save-file-if-necessary (&optional force)
1790 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1791 Normally delete only if the file was written by this Emacs since
1792 the last real save, but optional arg FORCE non-nil means delete anyway."
1793 (and buffer-auto-save-file-name delete-auto-save-files
1794 (not (string= buffer-file-name buffer-auto-save-file-name))
1795 (or force (recent-auto-save-p))
1796 (progn
1797 (condition-case ()
1798 (delete-file buffer-auto-save-file-name)
1799 (file-error nil))
1800 (set-buffer-auto-saved))))
1802 (defvar after-save-hook nil
1803 "Normal hook that is run after a buffer is saved to its file.")
1805 (defun basic-save-buffer ()
1806 "Save the current buffer in its visited file, if it has been modified.
1807 After saving the buffer, run `after-save-hook'."
1808 (interactive)
1809 (save-excursion
1810 ;; In an indirect buffer, save its base buffer instead.
1811 (if (buffer-base-buffer)
1812 (set-buffer (buffer-base-buffer)))
1813 (if (buffer-modified-p)
1814 (let ((recent-save (recent-auto-save-p))
1815 setmodes tempsetmodes)
1816 ;; On VMS, rename file and buffer to get rid of version number.
1817 (if (and (eq system-type 'vax-vms)
1818 (not (string= buffer-file-name
1819 (file-name-sans-versions buffer-file-name))))
1820 (let (buffer-new-name)
1821 ;; Strip VMS version number before save.
1822 (setq buffer-file-name
1823 (file-name-sans-versions buffer-file-name))
1824 ;; Construct a (unique) buffer name to correspond.
1825 (let ((buf (create-file-buffer (downcase buffer-file-name))))
1826 (setq buffer-new-name (buffer-name buf))
1827 (kill-buffer buf))
1828 (rename-buffer buffer-new-name)))
1829 ;; If buffer has no file name, ask user for one.
1830 (or buffer-file-name
1831 (let ((filename
1832 (expand-file-name
1833 (read-file-name "File to save in: ") nil)))
1834 (and (file-exists-p filename)
1835 (or (y-or-n-p (format "File `%s' exists; overwrite? "
1836 filename))
1837 (error "Canceled")))
1838 (set-visited-file-name filename)))
1839 (or (verify-visited-file-modtime (current-buffer))
1840 (not (file-exists-p buffer-file-name))
1841 (yes-or-no-p
1842 (format "%s has changed since visited or saved. Save anyway? "
1843 (file-name-nondirectory buffer-file-name)))
1844 (error "Save not confirmed"))
1845 (save-restriction
1846 (widen)
1847 (and (> (point-max) 1)
1848 (/= (char-after (1- (point-max))) ?\n)
1849 (not (and (eq selective-display t)
1850 (= (char-after (1- (point-max))) ?\r)))
1851 (or (eq require-final-newline t)
1852 (and require-final-newline
1853 (y-or-n-p
1854 (format "Buffer %s does not end in newline. Add one? "
1855 (buffer-name)))))
1856 (save-excursion
1857 (goto-char (point-max))
1858 (insert ?\n)))
1859 (or (run-hook-with-args-until-success 'write-contents-hooks)
1860 (run-hook-with-args-until-success 'local-write-file-hooks)
1861 (run-hook-with-args-until-success 'write-file-hooks)
1862 ;; If a hook returned t, file is already "written".
1863 ;; Otherwise, write it the usual way now.
1864 (setq setmodes (basic-save-buffer-1)))
1865 (setq buffer-file-number
1866 (nthcdr 10 (file-attributes buffer-file-name)))
1867 (if setmodes
1868 (condition-case ()
1869 (set-file-modes buffer-file-name setmodes)
1870 (error nil))))
1871 ;; If the auto-save file was recent before this command,
1872 ;; delete it now.
1873 (delete-auto-save-file-if-necessary recent-save)
1874 ;; Support VC `implicit' locking.
1875 (vc-after-save)
1876 (run-hooks 'after-save-hook))
1877 (message "(No changes need to be saved)"))))
1879 ;; This does the "real job" of writing a buffer into its visited file
1880 ;; and making a backup file. This is what is normally done
1881 ;; but inhibited if one of write-file-hooks returns non-nil.
1882 ;; It returns a value to store in setmodes.
1883 (defun basic-save-buffer-1 ()
1884 (let (tempsetmodes setmodes)
1885 (if (not (file-writable-p buffer-file-name))
1886 (let ((dir (file-name-directory buffer-file-name)))
1887 (if (not (file-directory-p dir))
1888 (error "%s is not a directory" dir)
1889 (if (not (file-exists-p buffer-file-name))
1890 (error "Directory %s write-protected" dir)
1891 (if (yes-or-no-p
1892 (format "File %s is write-protected; try to save anyway? "
1893 (file-name-nondirectory
1894 buffer-file-name)))
1895 (setq tempsetmodes t)
1896 (error "Attempt to save to a file which you aren't allowed to write"))))))
1897 (or buffer-backed-up
1898 (setq setmodes (backup-buffer)))
1899 (let ((dir (file-name-directory buffer-file-name)))
1900 (if (and file-precious-flag
1901 (file-writable-p dir))
1902 ;; If file is precious, write temp name, then rename it.
1903 ;; This requires write access to the containing dir,
1904 ;; which is why we don't try it if we don't have that access.
1905 (let ((realname buffer-file-name)
1906 tempname temp nogood i succeed
1907 (old-modtime (visited-file-modtime)))
1908 (setq i 0)
1909 (setq nogood t)
1910 ;; Find the temporary name to write under.
1911 (while nogood
1912 (setq tempname (format
1913 (if (eq system-type 'ms-dos)
1914 "%s#%d.tm#" ; MSDOS limits files to 8+3
1915 "%s#tmp#%d")
1916 dir i))
1917 (setq nogood (file-exists-p tempname))
1918 (setq i (1+ i)))
1919 (unwind-protect
1920 (progn (clear-visited-file-modtime)
1921 (write-region (point-min) (point-max)
1922 tempname nil realname
1923 buffer-file-truename)
1924 (setq succeed t))
1925 ;; If writing the temp file fails,
1926 ;; delete the temp file.
1927 (or succeed
1928 (progn
1929 (delete-file tempname)
1930 (set-visited-file-modtime old-modtime))))
1931 ;; Since we have created an entirely new file
1932 ;; and renamed it, make sure it gets the
1933 ;; right permission bits set.
1934 (setq setmodes (file-modes buffer-file-name))
1935 ;; We succeeded in writing the temp file,
1936 ;; so rename it.
1937 (rename-file tempname buffer-file-name t))
1938 ;; If file not writable, see if we can make it writable
1939 ;; temporarily while we write it.
1940 ;; But no need to do so if we have just backed it up
1941 ;; (setmodes is set) because that says we're superseding.
1942 (cond ((and tempsetmodes (not setmodes))
1943 ;; Change the mode back, after writing.
1944 (setq setmodes (file-modes buffer-file-name))
1945 (set-file-modes buffer-file-name 511)))
1946 (write-region (point-min) (point-max)
1947 buffer-file-name nil t buffer-file-truename)))
1948 setmodes))
1950 (defun save-some-buffers (&optional arg exiting)
1951 "Save some modified file-visiting buffers. Asks user about each one.
1952 Optional argument (the prefix) non-nil means save all with no questions.
1953 Optional second argument EXITING means ask about certain non-file buffers
1954 as well as about file buffers."
1955 (interactive "P")
1956 (save-window-excursion
1957 (let* ((queried nil)
1958 (files-done
1959 (map-y-or-n-p
1960 (function
1961 (lambda (buffer)
1962 (and (buffer-modified-p buffer)
1963 (not (buffer-base-buffer buffer))
1965 (buffer-file-name buffer)
1966 (and exiting
1967 (progn
1968 (set-buffer buffer)
1969 (and buffer-offer-save (> (buffer-size) 0)))))
1970 (if arg
1972 (setq queried t)
1973 (if (buffer-file-name buffer)
1974 (format "Save file %s? "
1975 (buffer-file-name buffer))
1976 (format "Save buffer %s? "
1977 (buffer-name buffer)))))))
1978 (function
1979 (lambda (buffer)
1980 (set-buffer buffer)
1981 (save-buffer)))
1982 (buffer-list)
1983 '("buffer" "buffers" "save")
1984 (list (list ?\C-r (lambda (buf)
1985 (view-buffer buf)
1986 (setq view-exit-action
1987 '(lambda (ignore)
1988 (exit-recursive-edit)))
1989 (recursive-edit)
1990 ;; Return nil to ask about BUF again.
1991 nil)
1992 "display the current buffer"))))
1993 (abbrevs-done
1994 (and save-abbrevs abbrevs-changed
1995 (progn
1996 (if (or arg
1997 (y-or-n-p (format "Save abbrevs in %s? "
1998 abbrev-file-name)))
1999 (write-abbrev-file nil))
2000 ;; Don't keep bothering user if he says no.
2001 (setq abbrevs-changed nil)
2002 t))))
2003 (or queried (> files-done 0) abbrevs-done
2004 (message "(No files need saving)")))))
2006 (defun not-modified (&optional arg)
2007 "Mark current buffer as unmodified, not needing to be saved.
2008 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2010 It is not a good idea to use this function in Lisp programs, because it
2011 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2012 (interactive "P")
2013 (message (if arg "Modification-flag set"
2014 "Modification-flag cleared"))
2015 (set-buffer-modified-p arg))
2017 (defun toggle-read-only (&optional arg)
2018 "Change whether this buffer is visiting its file read-only.
2019 With arg, set read-only iff arg is positive."
2020 (interactive "P")
2021 (setq buffer-read-only
2022 (if (null arg)
2023 (not buffer-read-only)
2024 (> (prefix-numeric-value arg) 0)))
2025 (force-mode-line-update))
2027 (defun insert-file (filename)
2028 "Insert contents of file FILENAME into buffer after point.
2029 Set mark after the inserted text.
2031 This function is meant for the user to run interactively.
2032 Don't call it from programs! Use `insert-file-contents' instead.
2033 \(Its calling sequence is different; see its documentation)."
2034 (interactive "*fInsert file: ")
2035 (if (file-directory-p filename)
2036 (signal 'file-error (list "Opening input file" "file is a directory"
2037 filename)))
2038 (let ((tem (insert-file-contents filename)))
2039 (push-mark (+ (point) (car (cdr tem))))))
2041 (defun append-to-file (start end filename)
2042 "Append the contents of the region to the end of file FILENAME.
2043 When called from a function, expects three arguments,
2044 START, END and FILENAME. START and END are buffer positions
2045 saying what text to write."
2046 (interactive "r\nFAppend to file: ")
2047 (write-region start end filename t))
2049 (defun file-newest-backup (filename)
2050 "Return most recent backup file for FILENAME or nil if no backups exist."
2051 (let* ((filename (expand-file-name filename))
2052 (file (file-name-nondirectory filename))
2053 (dir (file-name-directory filename))
2054 (comp (file-name-all-completions file dir))
2055 newest)
2056 (while comp
2057 (setq file (concat dir (car comp))
2058 comp (cdr comp))
2059 (if (and (backup-file-name-p file)
2060 (or (null newest) (file-newer-than-file-p file newest)))
2061 (setq newest file)))
2062 newest))
2064 (defun rename-uniquely ()
2065 "Rename current buffer to a similar name not already taken.
2066 This function is useful for creating multiple shell process buffers
2067 or multiple mail buffers, etc."
2068 (interactive)
2069 (save-match-data
2070 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2071 (not (and buffer-file-name
2072 (string= (buffer-name)
2073 (file-name-nondirectory
2074 buffer-file-name)))))
2075 ;; If the existing buffer name has a <NNN>,
2076 ;; which isn't part of the file name (if any),
2077 ;; then get rid of that.
2078 (substring (buffer-name) 0 (match-beginning 0))
2079 (buffer-name)))
2080 (new-buf (generate-new-buffer base-name))
2081 (name (buffer-name new-buf)))
2082 (kill-buffer new-buf)
2083 (rename-buffer name)
2084 (force-mode-line-update))))
2086 (defun make-directory (dir &optional parents)
2087 "Create the directory DIR and any nonexistent parent dirs.
2088 Interactively, the default choice of directory to create
2089 is the current default directory for file names.
2090 That is useful when you have visited a file in a nonexistent directory.
2092 Noninteractively, the second (optional) argument PARENTS says whether
2093 to create parent directories if they don't exist."
2094 (interactive
2095 (list (read-file-name "Make directory: " default-directory default-directory
2096 nil nil)
2098 (let ((handler (find-file-name-handler dir 'make-directory)))
2099 (if handler
2100 (funcall handler 'make-directory dir parents)
2101 (if (not parents)
2102 (make-directory-internal dir)
2103 (let ((dir (directory-file-name (expand-file-name dir)))
2104 create-list)
2105 (while (not (file-exists-p dir))
2106 (setq create-list (cons dir create-list)
2107 dir (directory-file-name (file-name-directory dir))))
2108 (while create-list
2109 (make-directory-internal (car create-list))
2110 (setq create-list (cdr create-list))))))))
2112 (put 'revert-buffer-function 'permanent-local t)
2113 (defvar revert-buffer-function nil
2114 "Function to use to revert this buffer, or nil to do the default.
2115 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2116 which are the arguments that `revert-buffer' received.")
2118 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2119 (defvar revert-buffer-insert-file-contents-function nil
2120 "Function to use to insert contents when reverting this buffer.
2121 Gets two args, first the nominal file name to use,
2122 and second, t if reading the auto-save file.")
2124 (defvar before-revert-hook nil
2125 "Normal hook for `revert-buffer' to run before reverting.
2126 If `revert-buffer-function' is used to override the normal revert
2127 mechanism, this hook is not used.")
2129 (defvar after-revert-hook nil
2130 "Normal hook for `revert-buffer' to run after reverting.
2131 Note that the hook value that it runs is the value that was in effect
2132 before reverting; that makes a difference if you have buffer-local
2133 hook functions.
2135 If `revert-buffer-function' is used to override the normal revert
2136 mechanism, this hook is not used.")
2138 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2139 "Replace the buffer text with the text of the visited file on disk.
2140 This undoes all changes since the file was visited or saved.
2141 With a prefix argument, offer to revert from latest auto-save file, if
2142 that is more recent than the visited file.
2144 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2145 to revert from the auto-save file when this is nil. Note that the
2146 sense of this argument is the reverse of the prefix argument, for the
2147 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2148 to nil.
2150 Optional second argument NOCONFIRM means don't ask for confirmation at
2151 all.
2153 If the value of `revert-buffer-function' is non-nil, it is called to
2154 do the work.
2156 The default revert function runs the hook `before-revert-hook' at the
2157 beginning and `after-revert-hook' at the end."
2158 ;; I admit it's odd to reverse the sense of the prefix argument, but
2159 ;; there is a lot of code out there which assumes that the first
2160 ;; argument should be t to avoid consulting the auto-save file, and
2161 ;; there's no straightforward way to encourage authors to notice a
2162 ;; reversal of the argument sense. So I'm just changing the user
2163 ;; interface, but leaving the programmatic interface the same.
2164 (interactive (list (not current-prefix-arg)))
2165 (if revert-buffer-function
2166 (funcall revert-buffer-function ignore-auto noconfirm)
2167 (let* ((opoint (point))
2168 (auto-save-p (and (not ignore-auto)
2169 (recent-auto-save-p)
2170 buffer-auto-save-file-name
2171 (file-readable-p buffer-auto-save-file-name)
2172 (y-or-n-p
2173 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2174 (file-name (if auto-save-p
2175 buffer-auto-save-file-name
2176 buffer-file-name)))
2177 (cond ((null file-name)
2178 (error "Buffer does not seem to be associated with any file"))
2179 ((or noconfirm
2180 (yes-or-no-p (format "Revert buffer from file %s? "
2181 file-name)))
2182 (run-hooks 'before-revert-hook)
2183 ;; If file was backed up but has changed since,
2184 ;; we shd make another backup.
2185 (and (not auto-save-p)
2186 (not (verify-visited-file-modtime (current-buffer)))
2187 (setq buffer-backed-up nil))
2188 ;; Get rid of all undo records for this buffer.
2189 (or (eq buffer-undo-list t)
2190 (setq buffer-undo-list nil))
2191 ;; Effectively copy the after-revert-hook status,
2192 ;; since after-find-file will clobber it.
2193 (let ((global-hook (default-value 'after-revert-hook))
2194 (local-hook-p (local-variable-p 'after-revert-hook))
2195 (local-hook (and (local-variable-p 'after-revert-hook)
2196 after-revert-hook)))
2197 (let (buffer-read-only
2198 ;; Don't make undo records for the reversion.
2199 (buffer-undo-list t))
2200 (if revert-buffer-insert-file-contents-function
2201 (funcall revert-buffer-insert-file-contents-function
2202 file-name auto-save-p)
2203 (if (not (file-exists-p file-name))
2204 (error "File %s no longer exists!" file-name))
2205 ;; Bind buffer-file-name to nil
2206 ;; so that we don't try to lock the file.
2207 (let ((buffer-file-name nil))
2208 (or auto-save-p
2209 (unlock-buffer)))
2210 (widen)
2211 (insert-file-contents file-name (not auto-save-p)
2212 nil nil t)))
2213 (goto-char (min opoint (point-max)))
2214 ;; Recompute the truename in case changes in symlinks
2215 ;; have changed the truename.
2216 (setq buffer-file-truename
2217 (abbreviate-file-name (file-truename buffer-file-name)))
2218 (after-find-file nil nil t t preserve-modes)
2219 ;; Run after-revert-hook as it was before we reverted.
2220 (setq-default revert-buffer-internal-hook global-hook)
2221 (if local-hook-p
2222 (progn
2223 (make-local-variable 'revert-buffer-internal-hook)
2224 (setq revert-buffer-internal-hook local-hook))
2225 (kill-local-variable 'revert-buffer-internal-hook))
2226 (run-hooks 'revert-buffer-internal-hook))
2227 t)))))
2229 (defun recover-file (file)
2230 "Visit file FILE, but get contents from its last auto-save file."
2231 ;; Actually putting the file name in the minibuffer should be used
2232 ;; only rarely.
2233 ;; Not just because users often use the default.
2234 (interactive "FRecover file: ")
2235 (setq file (expand-file-name file))
2236 (if (auto-save-file-name-p (file-name-nondirectory file))
2237 (error "%s is an auto-save file" file))
2238 (let ((file-name (let ((buffer-file-name file))
2239 (make-auto-save-file-name))))
2240 (cond ((if (file-exists-p file)
2241 (not (file-newer-than-file-p file-name file))
2242 (not (file-exists-p file-name)))
2243 (error "Auto-save file %s not current" file-name))
2244 ((save-window-excursion
2245 (if (not (eq system-type 'vax-vms))
2246 (with-output-to-temp-buffer "*Directory*"
2247 (buffer-disable-undo standard-output)
2248 (call-process "ls" nil standard-output nil
2249 (if (file-symlink-p file) "-lL" "-l")
2250 file file-name)))
2251 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2252 (switch-to-buffer (find-file-noselect file t))
2253 (let ((buffer-read-only nil))
2254 (erase-buffer)
2255 (insert-file-contents file-name nil))
2256 (after-find-file nil nil t))
2257 (t (error "Recover-file cancelled.")))))
2259 (defun recover-session ()
2260 "Recover auto save files from a previous Emacs session.
2261 This command first displays a Dired buffer showing you the
2262 previous sessions that you could recover from.
2263 To choose one, move point to the proper line and then type C-c C-c.
2264 Then you'll be asked about a number of files to recover."
2265 (interactive)
2266 (let ((ls-lisp-support-shell-wildcards t))
2267 (dired (concat auto-save-list-file-prefix "*")))
2268 (goto-char (point-min))
2269 (or (looking-at "Move to the session you want to recover,")
2270 (let ((inhibit-read-only t))
2271 (insert "Move to the session you want to recover,\n"
2272 "then type C-c C-c to select it.\n\n"
2273 "You can also delete some of these files;\n"
2274 "type d on a line to mark that file for deletion.\n\n")))
2275 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2276 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
2278 (defun recover-session-finish ()
2279 "Choose one saved session to recover auto-save files from.
2280 This command is used in the special Dired buffer created by
2281 \\[recover-session]."
2282 (interactive)
2283 ;; Get the name of the session file to recover from.
2284 (let ((file (dired-get-filename))
2285 files
2286 (buffer (get-buffer-create " *recover*")))
2287 (dired-do-flagged-delete t)
2288 (unwind-protect
2289 (save-excursion
2290 ;; Read in the auto-save-list file.
2291 (set-buffer buffer)
2292 (erase-buffer)
2293 (insert-file-contents file)
2294 ;; Loop thru the text of that file
2295 ;; and get out the names of the files to recover.
2296 (while (not (eobp))
2297 (let (thisfile autofile)
2298 (if (eolp)
2299 ;; This is a pair of lines for a non-file-visiting buffer.
2300 ;; Get the auto-save file name and manufacture
2301 ;; a "visited file name" from that.
2302 (progn
2303 (forward-line 1)
2304 (setq autofile
2305 (buffer-substring-no-properties
2306 (point)
2307 (save-excursion
2308 (end-of-line)
2309 (point))))
2310 (setq thisfile
2311 (expand-file-name
2312 (substring
2313 (file-name-nondirectory autofile)
2314 1 -1)
2315 (file-name-directory autofile)))
2316 (forward-line 1))
2317 ;; This pair of lines is a file-visiting
2318 ;; buffer. Use the visited file name.
2319 (progn
2320 (setq thisfile
2321 (buffer-substring-no-properties
2322 (point) (progn (end-of-line) (point))))
2323 (forward-line 1)
2324 (setq autofile
2325 (buffer-substring-no-properties
2326 (point) (progn (end-of-line) (point))))
2327 (forward-line 1)))
2328 ;; Ignore a file if its auto-save file does not exist now.
2329 (if (file-exists-p autofile)
2330 (setq files (cons thisfile files)))))
2331 (setq files (nreverse files))
2332 ;; The file contains a pair of line for each auto-saved buffer.
2333 ;; The first line of the pair contains the visited file name
2334 ;; or is empty if the buffer was not visiting a file.
2335 ;; The second line is the auto-save file name.
2336 (if files
2337 (map-y-or-n-p "Recover %s? "
2338 (lambda (file)
2339 (condition-case nil
2340 (save-excursion (recover-file file))
2341 (error
2342 "Failed to recover `%s'" file)))
2343 files
2344 '("file" "files" "recover"))
2345 (message "No files can be recovered from this session now")))
2346 (kill-buffer buffer))))
2348 (defun kill-some-buffers ()
2349 "For each buffer, ask whether to kill it."
2350 (interactive)
2351 (let ((list (buffer-list)))
2352 (while list
2353 (let* ((buffer (car list))
2354 (name (buffer-name buffer)))
2355 (and (not (string-equal name ""))
2356 (/= (aref name 0) ? )
2357 (yes-or-no-p
2358 (format "Buffer %s %s. Kill? "
2359 name
2360 (if (buffer-modified-p buffer)
2361 "HAS BEEN EDITED" "is unmodified")))
2362 (kill-buffer buffer)))
2363 (setq list (cdr list)))))
2365 (defun auto-save-mode (arg)
2366 "Toggle auto-saving of contents of current buffer.
2367 With prefix argument ARG, turn auto-saving on if positive, else off."
2368 (interactive "P")
2369 (setq buffer-auto-save-file-name
2370 (and (if (null arg)
2371 (or (not buffer-auto-save-file-name)
2372 ;; If autosave is off because buffer has shrunk,
2373 ;; then toggling should turn it on.
2374 (< buffer-saved-size 0))
2375 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2376 (if (and buffer-file-name auto-save-visited-file-name
2377 (not buffer-read-only))
2378 buffer-file-name
2379 (make-auto-save-file-name))))
2380 ;; If -1 was stored here, to temporarily turn off saving,
2381 ;; turn it back on.
2382 (and (< buffer-saved-size 0)
2383 (setq buffer-saved-size 0))
2384 (if (interactive-p)
2385 (message "Auto-save %s (in this buffer)"
2386 (if buffer-auto-save-file-name "on" "off")))
2387 buffer-auto-save-file-name)
2389 (defun rename-auto-save-file ()
2390 "Adjust current buffer's auto save file name for current conditions.
2391 Also rename any existing auto save file, if it was made in this session."
2392 (let ((osave buffer-auto-save-file-name))
2393 (setq buffer-auto-save-file-name
2394 (make-auto-save-file-name))
2395 (if (and osave buffer-auto-save-file-name
2396 (not (string= buffer-auto-save-file-name buffer-file-name))
2397 (not (string= buffer-auto-save-file-name osave))
2398 (file-exists-p osave)
2399 (recent-auto-save-p))
2400 (rename-file osave buffer-auto-save-file-name t))))
2402 (defun make-auto-save-file-name ()
2403 "Return file name to use for auto-saves of current buffer.
2404 Does not consider `auto-save-visited-file-name' as that variable is checked
2405 before calling this function. You can redefine this for customization.
2406 See also `auto-save-file-name-p'."
2407 (if buffer-file-name
2408 (if (eq system-type 'ms-dos)
2409 (let ((fn (file-name-nondirectory buffer-file-name)))
2410 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
2411 (concat (file-name-directory buffer-file-name)
2412 "#" (match-string 1 fn)
2413 "." (match-string 3 fn) "#"))
2414 (concat (file-name-directory buffer-file-name)
2416 (file-name-nondirectory buffer-file-name)
2417 "#"))
2419 ;; Deal with buffers that don't have any associated files. (Mail
2420 ;; mode tends to create a good number of these.)
2422 (let ((buffer-name (buffer-name))
2423 (limit 0))
2424 ;; Use technique from Sebastian Kremer's auto-save
2425 ;; package to turn slashes into \\!. This ensures that
2426 ;; the auto-save buffer name is unique.
2428 (while (string-match "[/\\]" buffer-name limit)
2429 (setq buffer-name (concat (substring buffer-name 0 (match-beginning 0))
2430 (if (string= (substring buffer-name
2431 (match-beginning 0)
2432 (match-end 0))
2433 "/")
2434 "\\!"
2435 "\\\\")
2436 (substring buffer-name (match-end 0))))
2437 (setq limit (1+ (match-end 0))))
2439 (expand-file-name (format "#%s#%s#" buffer-name (make-temp-name ""))))))
2441 (defun auto-save-file-name-p (filename)
2442 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2443 FILENAME should lack slashes. You can redefine this for customization."
2444 (string-match "^#.*#$" filename))
2446 (defun wildcard-to-regexp (wildcard)
2447 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2448 The generated regexp will match a filename iff the filename
2449 matches that wildcard according to shell rules. Only wildcards known
2450 by `sh' are supported."
2451 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
2452 ;; Copy the initial run of non-special characters.
2453 (result (substring wildcard 0 i))
2454 (len (length wildcard)))
2455 ;; If no special characters, we're almost done.
2456 (if i
2457 (while (< i len)
2458 (let ((ch (aref wildcard i))
2460 (setq
2461 result
2462 (concat result
2463 (cond
2464 ((eq ch ?\[) ; [...] maps to regexp char class
2465 (progn
2466 (setq i (1+ i))
2467 (concat
2468 (cond
2469 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
2470 (progn
2471 (setq i (1+ i))
2472 (if (eq (aref wildcard i) ?\])
2473 (progn
2474 (setq i (1+ i))
2475 "[^]")
2476 "[^")))
2477 ((eq (aref wildcard i) ?^)
2478 ;; Found "[^". Insert a `\0' character
2479 ;; (which cannot happen in a filename)
2480 ;; into the character class, so that `^'
2481 ;; is not the first character after `[',
2482 ;; and thus non-special in a regexp.
2483 (progn
2484 (setq i (1+ i))
2485 "[\000^"))
2486 ((eq (aref wildcard i) ?\])
2487 ;; I don't think `]' can appear in a
2488 ;; character class in a wildcard, but
2489 ;; let's be general here.
2490 (progn
2491 (setq i (1+ i))
2492 "[]"))
2493 (t "["))
2494 (prog1 ; copy everything upto next `]'.
2495 (substring wildcard
2497 (setq j (string-match
2498 "]" wildcard i)))
2499 (setq i (if j (1- j) (1- len)))))))
2500 ((eq ch ?.) "\\.")
2501 ((eq ch ?*) "[^\000]*")
2502 ((eq ch ?+) "\\+")
2503 ((eq ch ?^) "\\^")
2504 ((eq ch ?$) "\\$")
2505 ((eq ch ?\\) "\\\\") ; probably cannot happen...
2506 ((eq ch ??) "[^\000]")
2507 (t (char-to-string ch)))))
2508 (setq i (1+ i)))))
2509 ;; Shell wildcards should match the entire filename,
2510 ;; not its part. Make the regexp say so.
2511 (concat "\\`" result "\\'")))
2513 (defconst list-directory-brief-switches
2514 (if (eq system-type 'vax-vms) "" "-CF")
2515 "*Switches for list-directory to pass to `ls' for brief listing,")
2517 (defconst list-directory-verbose-switches
2518 (if (eq system-type 'vax-vms)
2519 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2520 "-l")
2521 "*Switches for list-directory to pass to `ls' for verbose listing,")
2523 (defun list-directory (dirname &optional verbose)
2524 "Display a list of files in or matching DIRNAME, a la `ls'.
2525 DIRNAME is globbed by the shell if necessary.
2526 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2527 Actions controlled by variables `list-directory-brief-switches'
2528 and `list-directory-verbose-switches'."
2529 (interactive (let ((pfx current-prefix-arg))
2530 (list (read-file-name (if pfx "List directory (verbose): "
2531 "List directory (brief): ")
2532 nil default-directory nil)
2533 pfx)))
2534 (let ((switches (if verbose list-directory-verbose-switches
2535 list-directory-brief-switches)))
2536 (or dirname (setq dirname default-directory))
2537 (setq dirname (expand-file-name dirname))
2538 (with-output-to-temp-buffer "*Directory*"
2539 (buffer-disable-undo standard-output)
2540 (princ "Directory ")
2541 (princ dirname)
2542 (terpri)
2543 (save-excursion
2544 (set-buffer "*Directory*")
2545 (setq default-directory
2546 (if (file-directory-p dirname)
2547 (file-name-as-directory dirname)
2548 (file-name-directory dirname)))
2549 (let ((wildcard (not (file-directory-p dirname))))
2550 (insert-directory dirname switches wildcard (not wildcard)))))))
2552 (defvar insert-directory-program "ls"
2553 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2555 ;; insert-directory
2556 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2557 ;; FULL-DIRECTORY-P is nil.
2558 ;; The single line of output must display FILE's name as it was
2559 ;; given, namely, an absolute path name.
2560 ;; - must insert exactly one line for each file if WILDCARD or
2561 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
2562 ;; before the file lines, plus optional text after the file lines.
2563 ;; Lines are delimited by "\n", so filenames containing "\n" are not
2564 ;; allowed.
2565 ;; File lines should display the basename.
2566 ;; - must be consistent with
2567 ;; - functions dired-move-to-filename, (these two define what a file line is)
2568 ;; dired-move-to-end-of-filename,
2569 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2570 ;; dired-insert-headerline
2571 ;; dired-after-subdir-garbage (defines what a "total" line is)
2572 ;; - variable dired-subdir-regexp
2573 (defun insert-directory (file switches &optional wildcard full-directory-p)
2574 "Insert directory listing for FILE, formatted according to SWITCHES.
2575 Leaves point after the inserted text.
2576 SWITCHES may be a string of options, or a list of strings.
2577 Optional third arg WILDCARD means treat FILE as shell wildcard.
2578 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2579 switches do not contain `d', so that a full listing is expected.
2581 This works by running a directory listing program
2582 whose name is in the variable `insert-directory-program'.
2583 If WILDCARD, it also runs the shell specified by `shell-file-name'."
2584 ;; We need the directory in order to find the right handler.
2585 (let ((handler (find-file-name-handler (expand-file-name file)
2586 'insert-directory)))
2587 (if handler
2588 (funcall handler 'insert-directory file switches
2589 wildcard full-directory-p)
2590 (if (eq system-type 'vax-vms)
2591 (vms-read-directory file switches (current-buffer))
2592 (if wildcard
2593 ;; Run ls in the directory of the file pattern we asked for.
2594 (let ((default-directory
2595 (if (file-name-absolute-p file)
2596 (file-name-directory file)
2597 (file-name-directory (expand-file-name file))))
2598 (pattern (file-name-nondirectory file))
2599 (beg 0))
2600 ;; Quote some characters that have special meanings in shells;
2601 ;; but don't quote the wildcards--we want them to be special.
2602 ;; We also currently don't quote the quoting characters
2603 ;; in case people want to use them explicitly to quote
2604 ;; wildcard characters.
2605 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
2606 (setq pattern
2607 (concat (substring pattern 0 (match-beginning 0))
2608 "\\"
2609 (substring pattern (match-beginning 0)))
2610 beg (1+ (match-end 0))))
2611 (call-process shell-file-name nil t nil
2612 "-c" (concat "\\" ;; Disregard shell aliases!
2613 insert-directory-program
2614 " -d "
2615 (if (stringp switches)
2616 switches
2617 (mapconcat 'identity switches " "))
2619 pattern)))
2620 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2621 ;; directory if FILE is a symbolic link.
2622 (apply 'call-process
2623 insert-directory-program nil t nil
2624 (let (list)
2625 (if (listp switches)
2626 (setq list switches)
2627 (if (not (equal switches ""))
2628 (progn
2629 ;; Split the switches at any spaces
2630 ;; so we can pass separate options as separate args.
2631 (while (string-match " " switches)
2632 (setq list (cons (substring switches 0 (match-beginning 0))
2633 list)
2634 switches (substring switches (match-end 0))))
2635 (setq list (cons switches list)))))
2636 (append list
2637 (list
2638 (if full-directory-p
2639 (concat (file-name-as-directory file) ".")
2640 file))))))))))
2642 (defvar kill-emacs-query-functions nil
2643 "Functions to call with no arguments to query about killing Emacs.
2644 If any of these functions returns nil, killing Emacs is cancelled.
2645 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
2646 but `kill-emacs', the low level primitive, does not.
2647 See also `kill-emacs-hook'.")
2649 (defun save-buffers-kill-emacs (&optional arg)
2650 "Offer to save each buffer, then kill this Emacs process.
2651 With prefix arg, silently save all file-visiting buffers, then kill."
2652 (interactive "P")
2653 (save-some-buffers arg t)
2654 (and (or (not (memq t (mapcar (function
2655 (lambda (buf) (and (buffer-file-name buf)
2656 (buffer-modified-p buf))))
2657 (buffer-list))))
2658 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2659 (or (not (fboundp 'process-list))
2660 ;; process-list is not defined on VMS.
2661 (let ((processes (process-list))
2662 active)
2663 (while processes
2664 (and (memq (process-status (car processes)) '(run stop open))
2665 (let ((val (process-kill-without-query (car processes))))
2666 (process-kill-without-query (car processes) val)
2667 val)
2668 (setq active t))
2669 (setq processes (cdr processes)))
2670 (or (not active)
2671 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
2672 ;; Query the user for other things, perhaps.
2673 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
2674 (kill-emacs)))
2676 (define-key ctl-x-map "\C-f" 'find-file)
2677 (define-key ctl-x-map "\C-q" 'toggle-read-only)
2678 (define-key ctl-x-map "\C-r" 'find-file-read-only)
2679 (define-key ctl-x-map "\C-v" 'find-alternate-file)
2680 (define-key ctl-x-map "\C-s" 'save-buffer)
2681 (define-key ctl-x-map "s" 'save-some-buffers)
2682 (define-key ctl-x-map "\C-w" 'write-file)
2683 (define-key ctl-x-map "i" 'insert-file)
2684 (define-key esc-map "~" 'not-modified)
2685 (define-key ctl-x-map "\C-d" 'list-directory)
2686 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
2688 (define-key ctl-x-4-map "f" 'find-file-other-window)
2689 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
2690 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
2691 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
2692 (define-key ctl-x-4-map "\C-o" 'display-buffer)
2694 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
2695 (define-key ctl-x-5-map "f" 'find-file-other-frame)
2696 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
2697 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
2699 ;;; files.el ends here