(nntp-accept-response): Add a timeout parameter to `accept-process-output'.
[emacs.git] / lisp / files.el
blobdbd8209fbdc4eff52cd157f7d761309ddc134bea
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 buf)))
835 (defvar after-find-file-from-revert-buffer nil)
837 (defun after-find-file (&optional error warn noauto
838 after-find-file-from-revert-buffer
839 nomodes)
840 "Called after finding a file and by the default revert function.
841 Sets buffer mode, parses local variables.
842 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
843 error in reading the file. WARN non-nil means warn if there
844 exists an auto-save file more recent than the visited file.
845 NOAUTO means don't mess with auto-save mode.
846 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
847 means this call was from `revert-buffer'.
848 Fifth arg NOMODES non-nil means don't alter the file's modes.
849 Finishes by calling the functions in `find-file-hooks'
850 unless NOMODES is non-nil."
851 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
852 (if noninteractive
854 (let* (not-serious
855 (msg
856 (cond ((and error (file-attributes buffer-file-name))
857 (setq buffer-read-only t)
858 "File exists, but cannot be read.")
859 ((not buffer-read-only)
860 (if (and warn
861 (file-newer-than-file-p (make-auto-save-file-name)
862 buffer-file-name))
863 "Auto save file is newer; consider M-x recover-file"
864 (setq not-serious t)
865 (if error "(New file)" nil)))
866 ((not error)
867 (setq not-serious t)
868 "Note: file is write protected")
869 ((file-attributes (directory-file-name default-directory))
870 "File not found and directory write-protected")
871 ((file-exists-p (file-name-directory buffer-file-name))
872 (setq buffer-read-only nil))
874 (setq buffer-read-only nil)
875 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
876 "Use M-x make-dir RET RET to create the directory"
877 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
878 (if msg
879 (progn
880 (message msg)
881 (or not-serious (sit-for 1 nil t)))))
882 (if (and auto-save-default (not noauto))
883 (auto-save-mode t)))
884 (if nomodes
886 (normal-mode t)
887 (run-hooks 'find-file-hooks)))
889 (defun normal-mode (&optional find-file)
890 "Choose the major mode for this buffer automatically.
891 Also sets up any specified local variables of the file.
892 Uses the visited file name, the -*- line, and the local variables spec.
894 This function is called automatically from `find-file'. In that case,
895 we may set up specified local variables depending on the value of
896 `enable-local-variables': if it is t, we do; if it is nil, we don't;
897 otherwise, we query. `enable-local-variables' is ignored if you
898 run `normal-mode' explicitly."
899 (interactive)
900 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
901 (condition-case err
902 (set-auto-mode)
903 (error (message "File mode specification error: %s"
904 (prin1-to-string err))))
905 (condition-case err
906 (let ((enable-local-variables (or (not find-file)
907 enable-local-variables)))
908 (hack-local-variables))
909 (error (message "File local-variables error: %s"
910 (prin1-to-string err)))))
912 (defvar auto-mode-alist
913 '(("\\.te?xt\\'" . text-mode)
914 ("\\.c\\'" . c-mode)
915 ("\\.h\\'" . c-mode)
916 ("\\.tex\\'" . tex-mode)
917 ("\\.ltx\\'" . latex-mode)
918 ("\\.el\\'" . emacs-lisp-mode)
919 ("\\.mm\\'" . nroff-mode)
920 ("\\.me\\'" . nroff-mode)
921 ("\\.ms\\'" . nroff-mode)
922 ("\\.man\\'" . nroff-mode)
923 ("\\.scm\\'" . scheme-mode)
924 ("\\.l\\'" . lisp-mode)
925 ("\\.lisp\\'" . lisp-mode)
926 ("\\.f\\'" . fortran-mode)
927 ("\\.for\\'" . fortran-mode)
928 ("\\.p\\'" . pascal-mode)
929 ("\\.pas\\'" . pascal-mode)
930 ("\\.mss\\'" . scribe-mode)
931 ("\\.ad[abs]\\'" . ada-mode)
932 ("\\.icn\\'" . icon-mode)
933 ("\\.pl\\'" . perl-mode)
934 ("\\.cc\\'" . c++-mode)
935 ("\\.hh\\'" . c++-mode)
936 ("\\.C\\'" . c++-mode)
937 ("\\.H\\'" . c++-mode)
938 ("\\.cpp\\'" . c++-mode)
939 ("\\.cxx\\'" . c++-mode)
940 ("\\.hxx\\'" . c++-mode)
941 ("\\.c\\+\\+\\'" . c++-mode)
942 ("\\.h\\+\\+\\'" . c++-mode)
943 ("\\.mk\\'" . makefile-mode)
944 ("[Mm]akefile\\(.in\\)?\\'" . makefile-mode)
945 ;;; Less common extensions come here
946 ;;; so more common ones above are found faster.
947 ("\\.texinfo\\'" . texinfo-mode)
948 ("\\.te?xi\\'" . texinfo-mode)
949 ("\\.s\\'" . asm-mode)
950 ("\\.S\\'" . asm-mode)
951 ("\\.asm\\'" . asm-mode)
952 ("ChangeLog\\'" . change-log-mode)
953 ("change.log\\'" . change-log-mode)
954 ("changelo\\'" . change-log-mode)
955 ("ChangeLog.[0-9]+\\'" . change-log-mode)
956 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
957 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
958 ("\\.c?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
959 ("/\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
960 ("/\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
961 ("/\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
962 ;;; The following should come after the ChangeLog pattern
963 ;;; for the sake of ChangeLog.1, etc.
964 ;;; and after the .scm.[0-9] pattern too.
965 ("\\.[12345678]\\'" . nroff-mode)
966 ("\\.TeX\\'" . tex-mode)
967 ("\\.sty\\'" . latex-mode)
968 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
969 ("\\.bbl\\'" . latex-mode)
970 ("\\.bib\\'" . bibtex-mode)
971 ("\\.article\\'" . text-mode)
972 ("\\.letter\\'" . text-mode)
973 ("\\.tcl\\'" . tcl-mode)
974 ("\\.f90\\'" . f90-mode)
975 ("\\.lsp\\'" . lisp-mode)
976 ("\\.awk\\'" . awk-mode)
977 ("\\.prolog\\'" . prolog-mode)
978 ("\\.tar\\'" . tar-mode)
979 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\)\\'" . archive-mode)
980 ;; Mailer puts message to be edited in
981 ;; /tmp/Re.... or Message
982 ("^/tmp/Re" . text-mode)
983 ("/Message[0-9]*\\'" . text-mode)
984 ("/drafts/[0-9]+\\'" . mh-letter-mode)
985 ;; some news reader is reported to use this
986 ("^/tmp/fol/" . text-mode)
987 ("\\.y\\'" . c-mode)
988 ("\\.lex\\'" . c-mode)
989 ("\\.oak\\'" . scheme-mode)
990 ("\\.sgml?\\'" . sgml-mode)
991 ("\\.dtd\\'" . sgml-mode)
992 ("\\.s?html?\\'" . html-mode)
993 ;; .emacs following a directory delimiter
994 ;; in either Unix or VMS syntax.
995 ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
996 ;; _emacs following a directory delimiter
997 ;; in MsDos syntax
998 ("[:/]_emacs\\'" . emacs-lisp-mode)
999 ("\\.ml\\'" . lisp-mode))
1001 Alist of filename patterns vs corresponding major mode functions.
1002 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1003 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1004 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1005 mode function to use. FUNCTION will be called, unless it is nil.
1007 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1008 calling FUNCTION (if it's not nil), we delete the suffix that matched
1009 REGEXP and search the list again for another match.")
1011 (defconst interpreter-mode-alist
1012 '(("perl" . perl-mode)
1013 ("wish" . tcl-mode)
1014 ("wishx" . tcl-mode)
1015 ("tcl" . tcl-mode)
1016 ("tclsh" . tcl-mode)
1017 ("awk" . awk-mode)
1018 ("nawk" . awk-mode)
1019 ("gawk" . awk-mode)
1020 ("scm" . scheme-mode)
1021 ("ash" . sh-mode)
1022 ("bash" . sh-mode)
1023 ("csh" . sh-mode)
1024 ("dtksh" . sh-mode)
1025 ("es" . sh-mode)
1026 ("itcsh" . sh-mode)
1027 ("jsh" . sh-mode)
1028 ("ksh" . sh-mode)
1029 ("oash" . sh-mode)
1030 ("pdksh" . sh-mode)
1031 ("rc" . sh-mode)
1032 ("sh" . sh-mode)
1033 ("sh5" . sh-mode)
1034 ("tcsh" . sh-mode)
1035 ("wksh" . sh-mode)
1036 ("wsh" . sh-mode)
1037 ("zsh" . sh-mode)
1038 ("tail" . text-mode)
1039 ("more" . text-mode)
1040 ("less" . text-mode)
1041 ("pg" . text-mode))
1042 "Alist mapping interpreter names to major modes.
1043 This alist applies to files whose first line starts with `#!'.
1044 Each element looks like (INTERPRETER . MODE).
1045 The car of each element is compared with
1046 the name of the interpreter specified in the first line.
1047 If it matches, mode MODE is selected.")
1049 (defconst inhibit-first-line-modes-regexps '("\\.tar\\'")
1050 "List of regexps; if one matches a file name, don't look for `-*-'.")
1052 (defconst inhibit-first-line-modes-suffixes nil
1053 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1054 When checking `inhibit-first-line-modes-regexps', we first discard
1055 from the end of the file name anything that matches one of these regexps.")
1057 (defvar user-init-file
1058 "" ; set by command-line
1059 "File name including directory of user's initialization file.")
1061 (defun set-auto-mode ()
1062 "Select major mode appropriate for current buffer.
1063 This checks for a -*- mode tag in the buffer's text,
1064 compares the filename against the entries in `auto-mode-alist',
1065 or checks the interpreter that runs this file against
1066 `interpreter-mode-alist'.
1068 It does not check for the `mode:' local variable in the
1069 Local Variables section of the file; for that, use `hack-local-variables'.
1071 If `enable-local-variables' is nil, this function does not check for a
1072 -*- mode tag."
1073 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1074 (let (beg end done modes)
1075 (save-excursion
1076 (goto-char (point-min))
1077 (skip-chars-forward " \t\n")
1078 (and enable-local-variables
1079 ;; Don't look for -*- if this file name matches any
1080 ;; of the regexps in inhibit-first-line-modes-regexps.
1081 (let ((temp inhibit-first-line-modes-regexps)
1082 (name (if buffer-file-name
1083 (file-name-sans-versions buffer-file-name)
1084 (buffer-name))))
1085 (while (let ((sufs inhibit-first-line-modes-suffixes))
1086 (while (and sufs (not (string-match (car sufs) name)))
1087 (setq sufs (cdr sufs)))
1088 sufs)
1089 (setq name (substring name 0 (match-beginning 0))))
1090 (while (and temp
1091 (not (string-match (car temp) name)))
1092 (setq temp (cdr temp)))
1093 (not temp))
1094 (search-forward "-*-" (save-excursion
1095 ;; If the file begins with "#!"
1096 ;; (exec interpreter magic), look
1097 ;; for mode frobs in the first two
1098 ;; lines. You cannot necessarily
1099 ;; put them in the first line of
1100 ;; such a file without screwing up
1101 ;; the interpreter invocation.
1102 (end-of-line (and (looking-at "^#!") 2))
1103 (point)) t)
1104 (progn
1105 (skip-chars-forward " \t")
1106 (setq beg (point))
1107 (search-forward "-*-"
1108 (save-excursion (end-of-line) (point))
1110 (progn
1111 (forward-char -3)
1112 (skip-chars-backward " \t")
1113 (setq end (point))
1114 (goto-char beg)
1115 (if (save-excursion (search-forward ":" end t))
1116 ;; Find all specifications for the `mode:' variable
1117 ;; and execute them left to right.
1118 (while (let ((case-fold-search t))
1119 (or (and (looking-at "mode:")
1120 (goto-char (match-end 0)))
1121 (re-search-forward "[ \t;]mode:" end t)))
1122 (skip-chars-forward " \t")
1123 (setq beg (point))
1124 (if (search-forward ";" end t)
1125 (forward-char -1)
1126 (goto-char end))
1127 (skip-chars-backward " \t")
1128 (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1129 modes)))
1130 ;; Simple -*-MODE-*- case.
1131 (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
1132 "-mode"))
1133 modes))))))
1134 ;; If we found modes to use, invoke them now,
1135 ;; outside the save-excursion.
1136 (if modes
1137 (progn (mapcar 'funcall modes)
1138 (setq done t)))
1139 ;; If we didn't find a mode from a -*- line, try using the file name.
1140 (if (and (not done) buffer-file-name)
1141 (let ((name buffer-file-name)
1142 (keep-going t))
1143 ;; Remove backup-suffixes from file name.
1144 (setq name (file-name-sans-versions name))
1145 (while keep-going
1146 (setq keep-going nil)
1147 (let ((alist auto-mode-alist)
1148 (mode nil))
1149 ;; Find first matching alist entry.
1150 (let ((case-fold-search
1151 (memq system-type '(vax-vms windows-nt))))
1152 (while (and (not mode) alist)
1153 (if (string-match (car (car alist)) name)
1154 (if (and (consp (cdr (car alist)))
1155 (nth 2 (car alist)))
1156 (progn
1157 (setq mode (car (cdr (car alist)))
1158 name (substring name 0 (match-beginning 0))
1159 keep-going t))
1160 (setq mode (cdr (car alist))
1161 keep-going nil)))
1162 (setq alist (cdr alist))))
1163 (if mode
1164 (funcall mode)
1165 ;; If we can't deduce a mode from the file name,
1166 ;; look for an interpreter specified in the first line.
1167 ;; As a special case, allow for things like "#!/bin/env perl",
1168 ;; which finds the interpreter anywhere in $PATH.
1169 (let ((interpreter
1170 (save-excursion
1171 (goto-char (point-min))
1172 (if (looking-at "#! *\\([^ \t\n]*/bin/env +\\)?\\([^ \t\n]+\\)")
1173 (buffer-substring (match-beginning 2)
1174 (match-end 2))
1175 "")))
1176 elt)
1177 ;; Map interpreter name to a mode.
1178 (setq elt (assoc (file-name-nondirectory interpreter)
1179 interpreter-mode-alist))
1180 (if elt
1181 (funcall (cdr elt)))))))))))
1183 (defun hack-local-variables-prop-line ()
1184 ;; Set local variables specified in the -*- line.
1185 ;; Ignore any specification for `mode:';
1186 ;; set-auto-mode should already have handled that.
1187 (save-excursion
1188 (goto-char (point-min))
1189 (let ((result nil)
1190 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
1191 ;; Parse the -*- line into the `result' alist.
1192 (cond ((not (search-forward "-*-" end t))
1193 ;; doesn't have one.
1194 nil)
1195 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1196 ;; Simple form: "-*- MODENAME -*-". Already handled.
1197 nil)
1199 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1200 ;; (last ";" is optional).
1201 (save-excursion
1202 (if (search-forward "-*-" end t)
1203 (setq end (- (point) 3))
1204 (error "-*- not terminated before end of line")))
1205 (while (< (point) end)
1206 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1207 (error "malformed -*- line"))
1208 (goto-char (match-end 0))
1209 ;; There used to be a downcase here,
1210 ;; but the manual didn't say so,
1211 ;; and people want to set var names that aren't all lc.
1212 (let ((key (intern (buffer-substring
1213 (match-beginning 1)
1214 (match-end 1))))
1215 (val (save-restriction
1216 (narrow-to-region (point) end)
1217 (read (current-buffer)))))
1218 (or (eq key 'mode)
1219 (setq result (cons (cons key val) result)))
1220 (skip-chars-forward " \t;")))
1221 (setq result (nreverse result))))
1223 (if (and result
1224 (or (eq enable-local-variables t)
1225 (and enable-local-variables
1226 (save-window-excursion
1227 (condition-case nil
1228 (switch-to-buffer (current-buffer))
1229 (error
1230 ;; If we fail to switch in the selected window,
1231 ;; it is probably a minibuffer.
1232 ;; So try another window.
1233 (condition-case nil
1234 (switch-to-buffer-other-window (current-buffer))
1235 (error
1236 (switch-to-buffer-other-frame (current-buffer))))))
1237 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1238 (file-name-nondirectory buffer-file-name)))))))
1239 (while result
1240 (hack-one-local-variable (car (car result)) (cdr (car result)))
1241 (setq result (cdr result)))))))
1243 (defvar hack-local-variables-hook nil
1244 "Normal hook run after processing a file's local variables specs.
1245 Major modes can use this to examine user-specified local variables
1246 in order to initialize other data structure based on them.")
1248 (defun hack-local-variables ()
1249 "Parse and put into effect this buffer's local variables spec."
1250 (hack-local-variables-prop-line)
1251 ;; Look for "Local variables:" line in last page.
1252 (save-excursion
1253 (goto-char (point-max))
1254 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1255 (if (let ((case-fold-search t))
1256 (and (search-forward "Local Variables:" nil t)
1257 (or (eq enable-local-variables t)
1258 (and enable-local-variables
1259 (save-window-excursion
1260 (switch-to-buffer (current-buffer))
1261 (save-excursion
1262 (beginning-of-line)
1263 (set-window-start (selected-window) (point)))
1264 (y-or-n-p (format "Set local variables as specified at end of %s? "
1265 (if buffer-file-name
1266 (file-name-nondirectory
1267 buffer-file-name)
1268 (concat "buffer "
1269 (buffer-name))))))))))
1270 (let ((continue t)
1271 prefix prefixlen suffix beg
1272 (enable-local-eval enable-local-eval))
1273 ;; The prefix is what comes before "local variables:" in its line.
1274 ;; The suffix is what comes after "local variables:" in its line.
1275 (skip-chars-forward " \t")
1276 (or (eolp)
1277 (setq suffix (buffer-substring (point)
1278 (progn (end-of-line) (point)))))
1279 (goto-char (match-beginning 0))
1280 (or (bolp)
1281 (setq prefix
1282 (buffer-substring (point)
1283 (progn (beginning-of-line) (point)))))
1285 (if prefix (setq prefixlen (length prefix)
1286 prefix (regexp-quote prefix)))
1287 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1288 (while continue
1289 ;; Look at next local variable spec.
1290 (if selective-display (re-search-forward "[\n\C-m]")
1291 (forward-line 1))
1292 ;; Skip the prefix, if any.
1293 (if prefix
1294 (if (looking-at prefix)
1295 (forward-char prefixlen)
1296 (error "Local variables entry is missing the prefix")))
1297 ;; Find the variable name; strip whitespace.
1298 (skip-chars-forward " \t")
1299 (setq beg (point))
1300 (skip-chars-forward "^:\n")
1301 (if (eolp) (error "Missing colon in local variables entry"))
1302 (skip-chars-backward " \t")
1303 (let* ((str (buffer-substring beg (point)))
1304 (var (read str))
1305 val)
1306 ;; Setting variable named "end" means end of list.
1307 (if (string-equal (downcase str) "end")
1308 (setq continue nil)
1309 ;; Otherwise read the variable value.
1310 (skip-chars-forward "^:")
1311 (forward-char 1)
1312 (setq val (read (current-buffer)))
1313 (skip-chars-backward "\n")
1314 (skip-chars-forward " \t")
1315 (or (if suffix (looking-at suffix) (eolp))
1316 (error "Local variables entry is terminated incorrectly"))
1317 ;; Set the variable. "Variables" mode and eval are funny.
1318 (hack-one-local-variable var val)))))))
1319 (run-hooks 'hack-local-variables-hook))
1321 (defconst ignored-local-variables
1322 '(enable-local-eval)
1323 "Variables to be ignored in a file's local variable spec.")
1325 ;; Get confirmation before setting these variables as locals in a file.
1326 (put 'debugger 'risky-local-variable t)
1327 (put 'enable-local-eval 'risky-local-variable t)
1328 (put 'ignored-local-variables 'risky-local-variable t)
1329 (put 'eval 'risky-local-variable t)
1330 (put 'file-name-handler-alist 'risky-local-variable t)
1331 (put 'minor-mode-map-alist 'risky-local-variable t)
1332 (put 'after-load-alist 'risky-local-variable t)
1333 (put 'buffer-file-name 'risky-local-variable t)
1334 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1335 (put 'buffer-file-truename 'risky-local-variable t)
1336 (put 'exec-path 'risky-local-variable t)
1337 (put 'load-path 'risky-local-variable t)
1338 (put 'exec-directory 'risky-local-variable t)
1339 (put 'process-environment 'risky-local-variable t)
1340 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1341 (put 'outline-level 'risky-local-variable t)
1342 (put 'rmail-output-file-alist 'risky-local-variable t)
1344 ;; This one is safe because the user gets to check it before it is used.
1345 (put 'compile-command 'safe-local-variable t)
1347 (defun hack-one-local-variable-quotep (exp)
1348 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1350 ;; "Set" one variable in a local variables spec.
1351 ;; A few variable names are treated specially.
1352 (defun hack-one-local-variable (var val)
1353 (cond ((eq var 'mode)
1354 (funcall (intern (concat (downcase (symbol-name val))
1355 "-mode"))))
1356 ((memq var ignored-local-variables)
1357 nil)
1358 ;; "Setting" eval means either eval it or do nothing.
1359 ;; Likewise for setting hook variables.
1360 ((or (get var 'risky-local-variable)
1361 (and
1362 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
1363 (symbol-name var))
1364 (not (get var 'safe-local-variable))))
1365 ;; Permit evalling a put of a harmless property.
1366 ;; if the args do nothing tricky.
1367 (if (or (and (eq var 'eval)
1368 (consp val)
1369 (eq (car val) 'put)
1370 (hack-one-local-variable-quotep (nth 1 val))
1371 (hack-one-local-variable-quotep (nth 2 val))
1372 ;; Only allow safe values of lisp-indent-hook;
1373 ;; not functions.
1374 (or (numberp (nth 3 val))
1375 (equal (nth 3 val) ''defun))
1376 (memq (nth 1 (nth 2 val))
1377 '(lisp-indent-hook)))
1378 ;; Permit eval if not root and user says ok.
1379 (and (not (zerop (user-uid)))
1380 (or (eq enable-local-eval t)
1381 (and enable-local-eval
1382 (save-window-excursion
1383 (switch-to-buffer (current-buffer))
1384 (save-excursion
1385 (beginning-of-line)
1386 (set-window-start (selected-window) (point)))
1387 (setq enable-local-eval
1388 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1389 (file-name-nondirectory buffer-file-name)))))))))
1390 (if (eq var 'eval)
1391 (save-excursion (eval val))
1392 (make-local-variable var)
1393 (set var val))
1394 (message "Ignoring `eval:' in file's local variables")))
1395 ;; Ordinary variable, really set it.
1396 (t (make-local-variable var)
1397 (set var val))))
1400 (defun set-visited-file-name (filename)
1401 "Change name of file visited in current buffer to FILENAME.
1402 The next time the buffer is saved it will go in the newly specified file.
1403 nil or empty string as argument means make buffer not be visiting any file.
1404 Remember to delete the initial contents of the minibuffer
1405 if you wish to pass an empty string as the argument."
1406 (interactive "FSet visited file name: ")
1407 (if (buffer-base-buffer)
1408 (error "An indirect buffer cannot visit a file"))
1409 (let (truename)
1410 (if filename
1411 (setq filename
1412 (if (string-equal filename "")
1414 (expand-file-name filename))))
1415 (if filename
1416 (progn
1417 (setq truename (file-truename filename))
1418 (if find-file-visit-truename
1419 (setq filename truename))))
1420 (or (equal filename buffer-file-name)
1421 (progn
1422 (and filename (lock-buffer filename))
1423 (unlock-buffer)))
1424 (setq buffer-file-name filename)
1425 (if filename ; make buffer name reflect filename.
1426 (let ((new-name (file-name-nondirectory buffer-file-name)))
1427 (if (string= new-name "")
1428 (error "Empty file name"))
1429 (if (eq system-type 'vax-vms)
1430 (setq new-name (downcase new-name)))
1431 (setq default-directory (file-name-directory buffer-file-name))
1432 (or (string= new-name (buffer-name))
1433 (rename-buffer new-name t))))
1434 (setq buffer-backed-up nil)
1435 (clear-visited-file-modtime)
1436 ;; Abbreviate the file names of the buffer.
1437 (if truename
1438 (progn
1439 (setq buffer-file-truename (abbreviate-file-name truename))
1440 (if find-file-visit-truename
1441 (setq buffer-file-name buffer-file-truename))))
1442 (setq buffer-file-number
1443 (if filename
1444 (nthcdr 10 (file-attributes buffer-file-name))
1445 nil)))
1446 ;; write-file-hooks is normally used for things like ftp-find-file
1447 ;; that visit things that are not local files as if they were files.
1448 ;; Changing to visit an ordinary local file instead should flush the hook.
1449 (kill-local-variable 'write-file-hooks)
1450 (kill-local-variable 'local-write-file-hooks)
1451 (kill-local-variable 'revert-buffer-function)
1452 (kill-local-variable 'backup-inhibited)
1453 ;; If buffer was read-only because of version control,
1454 ;; that reason is gone now, so make it writable.
1455 (if vc-mode
1456 (setq buffer-read-only nil))
1457 (kill-local-variable 'vc-mode)
1458 ;; Turn off backup files for certain file names.
1459 ;; Since this is a permanent local, the major mode won't eliminate it.
1460 (and (not (funcall backup-enable-predicate buffer-file-name))
1461 (progn
1462 (make-local-variable 'backup-inhibited)
1463 (setq backup-inhibited t)))
1464 (let ((oauto buffer-auto-save-file-name))
1465 ;; If auto-save was not already on, turn it on if appropriate.
1466 (if (not buffer-auto-save-file-name)
1467 (and buffer-file-name auto-save-default
1468 (auto-save-mode t))
1469 ;; If auto save is on, start using a new name.
1470 ;; We deliberately don't rename or delete the old auto save
1471 ;; for the old visited file name. This is because perhaps
1472 ;; the user wants to save the new state and then compare with the
1473 ;; previous state from the auto save file.
1474 (setq buffer-auto-save-file-name
1475 (make-auto-save-file-name)))
1476 ;; Rename the old auto save file if any.
1477 (and oauto buffer-auto-save-file-name
1478 (file-exists-p oauto)
1479 (rename-file oauto buffer-auto-save-file-name t)))
1480 (if buffer-file-name
1481 (set-buffer-modified-p t)))
1483 (defun write-file (filename &optional confirm)
1484 "Write current buffer into file FILENAME.
1485 Makes buffer visit that file, and marks it not modified.
1486 If the buffer is already visiting a file, you can specify
1487 a directory name as FILENAME, to write a file of the same
1488 old name in that directory.
1489 If optional second arg CONFIRM is non-nil,
1490 ask for confirmation for overwriting an existing file."
1491 ;; (interactive "FWrite file: ")
1492 (interactive
1493 (list (if buffer-file-name
1494 (read-file-name "Write file: "
1495 nil nil nil nil)
1496 (read-file-name "Write file: "
1497 (cdr (assq 'default-directory
1498 (buffer-local-variables)))
1499 nil nil (buffer-name)))
1501 (or (null filename) (string-equal filename "")
1502 (progn
1503 ;; If arg is just a directory,
1504 ;; use same file name, but in that directory.
1505 (if (and (file-directory-p filename) buffer-file-name)
1506 (setq filename (concat (file-name-as-directory filename)
1507 (file-name-nondirectory buffer-file-name))))
1508 (and confirm
1509 (file-exists-p filename)
1510 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1511 (error "Canceled")))
1512 (set-visited-file-name filename)))
1513 (set-buffer-modified-p t)
1514 (save-buffer))
1516 (defun backup-buffer ()
1517 "Make a backup of the disk file visited by the current buffer, if appropriate.
1518 This is normally done before saving the buffer the first time.
1519 If the value is non-nil, it is the result of `file-modes' on the original
1520 file; this means that the caller, after saving the buffer, should change
1521 the modes of the new file to agree with the old modes."
1522 (if (and make-backup-files (not backup-inhibited)
1523 (not buffer-backed-up)
1524 (file-exists-p buffer-file-name)
1525 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1526 '(?- ?l)))
1527 (let ((real-file-name buffer-file-name)
1528 backup-info backupname targets setmodes)
1529 ;; If specified name is a symbolic link, chase it to the target.
1530 ;; Thus we make the backups in the directory where the real file is.
1531 (setq real-file-name (file-chase-links real-file-name))
1532 (setq backup-info (find-backup-file-name real-file-name)
1533 backupname (car backup-info)
1534 targets (cdr backup-info))
1535 ;;; (if (file-directory-p buffer-file-name)
1536 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1537 (if backup-info
1538 (condition-case ()
1539 (let ((delete-old-versions
1540 ;; If have old versions to maybe delete,
1541 ;; ask the user to confirm now, before doing anything.
1542 ;; But don't actually delete til later.
1543 (and targets
1544 (or (eq delete-old-versions t) (eq delete-old-versions nil))
1545 (or delete-old-versions
1546 (y-or-n-p (format "Delete excess backup versions of %s? "
1547 real-file-name))))))
1548 ;; Actually write the back up file.
1549 (condition-case ()
1550 (if (or file-precious-flag
1551 ; (file-symlink-p buffer-file-name)
1552 backup-by-copying
1553 (and backup-by-copying-when-linked
1554 (> (file-nlinks real-file-name) 1))
1555 (and backup-by-copying-when-mismatch
1556 (let ((attr (file-attributes real-file-name)))
1557 (or (nth 9 attr)
1558 (not (file-ownership-preserved-p real-file-name))))))
1559 (condition-case ()
1560 (copy-file real-file-name backupname t t)
1561 (file-error
1562 ;; If copying fails because file BACKUPNAME
1563 ;; is not writable, delete that file and try again.
1564 (if (and (file-exists-p backupname)
1565 (not (file-writable-p backupname)))
1566 (delete-file backupname))
1567 (copy-file real-file-name backupname t t)))
1568 ;; rename-file should delete old backup.
1569 (rename-file real-file-name backupname t)
1570 (setq setmodes (file-modes backupname)))
1571 (file-error
1572 ;; If trouble writing the backup, write it in ~.
1573 (setq backupname (expand-file-name
1574 (convert-standard-filename
1575 "~/%backup%~")))
1576 (message "Cannot write backup file; backing up in %s"
1577 (file-name-nondirectory backupname))
1578 (sleep-for 1)
1579 (condition-case ()
1580 (copy-file real-file-name backupname t t)
1581 (file-error
1582 ;; If copying fails because file BACKUPNAME
1583 ;; is not writable, delete that file and try again.
1584 (if (and (file-exists-p backupname)
1585 (not (file-writable-p backupname)))
1586 (delete-file backupname))
1587 (copy-file real-file-name backupname t t)))))
1588 (setq buffer-backed-up t)
1589 ;; Now delete the old versions, if desired.
1590 (if delete-old-versions
1591 (while targets
1592 (condition-case ()
1593 (delete-file (car targets))
1594 (file-error nil))
1595 (setq targets (cdr targets))))
1596 setmodes)
1597 (file-error nil))))))
1599 (defun file-name-sans-versions (name &optional keep-backup-version)
1600 "Return FILENAME sans backup versions or strings.
1601 This is a separate procedure so your site-init or startup file can
1602 redefine it.
1603 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1604 we do not remove backup version numbers, only true file version numbers."
1605 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1606 (if handler
1607 (funcall handler 'file-name-sans-versions name keep-backup-version)
1608 (substring name 0
1609 (if (eq system-type 'vax-vms)
1610 ;; VMS version number is (a) semicolon, optional
1611 ;; sign, zero or more digits or (b) period, option
1612 ;; sign, zero or more digits, provided this is the
1613 ;; second period encountered outside of the
1614 ;; device/directory part of the file name.
1615 (or (string-match ";[-+]?[0-9]*\\'" name)
1616 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1617 name)
1618 (match-beginning 1))
1619 (length name))
1620 (if keep-backup-version
1621 (length name)
1622 (or (string-match "\\.~[0-9.]+~\\'" name)
1623 (string-match "~\\'" name)
1624 (length name))))))))
1626 (defun file-ownership-preserved-p (file)
1627 "Returns t if deleting FILE and rewriting it would preserve the owner."
1628 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1629 (if handler
1630 (funcall handler 'file-ownership-preserved-p file)
1631 (let ((attributes (file-attributes file)))
1632 ;; Return t if the file doesn't exist, since it's true that no
1633 ;; information would be lost by an (attempted) delete and create.
1634 (or (null attributes)
1635 (= (nth 2 attributes) (user-uid)))))))
1637 (defun file-name-sans-extension (filename)
1638 "Return FILENAME sans final \"extension\".
1639 The extension, in a file name, is the part that follows the last `.'."
1640 (save-match-data
1641 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1642 directory)
1643 (if (string-match "\\.[^.]*\\'" file)
1644 (if (setq directory (file-name-directory filename))
1645 (expand-file-name (substring file 0 (match-beginning 0))
1646 directory)
1647 (substring file 0 (match-beginning 0)))
1648 filename))))
1650 (defun make-backup-file-name (file)
1651 "Create the non-numeric backup file name for FILE.
1652 This is a separate function so you can redefine it for customization."
1653 (if (eq system-type 'ms-dos)
1654 (let ((fn (file-name-nondirectory file)))
1655 (concat (file-name-directory file)
1657 (and (string-match "\\`[^.]+\\'" fn)
1658 (concat (match-string 0 fn) ".~"))
1659 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
1660 (concat (match-string 0 fn) "~")))))
1661 (concat file "~")))
1663 (defun backup-file-name-p (file)
1664 "Return non-nil if FILE is a backup file name (numeric or not).
1665 This is a separate function so you can redefine it for customization.
1666 You may need to redefine `file-name-sans-versions' as well."
1667 (string-match "~\\'" file))
1669 ;; This is used in various files.
1670 ;; The usage of bv-length is not very clean,
1671 ;; but I can't see a good alternative,
1672 ;; so as of now I am leaving it alone.
1673 (defun backup-extract-version (fn)
1674 "Given the name of a numeric backup file, return the backup number.
1675 Uses the free variable `bv-length', whose value should be
1676 the index in the name where the version number begins."
1677 (if (and (string-match "[0-9]+~$" fn bv-length)
1678 (= (match-beginning 0) bv-length))
1679 (string-to-int (substring fn bv-length -1))
1682 ;; I believe there is no need to alter this behavior for VMS;
1683 ;; since backup files are not made on VMS, it should not get called.
1684 (defun find-backup-file-name (fn)
1685 "Find a file name for a backup file, and suggestions for deletions.
1686 Value is a list whose car is the name for the backup file
1687 and whose cdr is a list of old versions to consider deleting now.
1688 If the value is nil, don't make a backup."
1689 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
1690 ;; Run a handler for this function so that ange-ftp can refuse to do it.
1691 (if handler
1692 (funcall handler 'find-backup-file-name fn)
1693 (if (eq version-control 'never)
1694 (list (make-backup-file-name fn))
1695 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
1696 (bv-length (length base-versions))
1697 possibilities
1698 (versions nil)
1699 (high-water-mark 0)
1700 (deserve-versions-p nil)
1701 (number-to-delete 0))
1702 (condition-case ()
1703 (setq possibilities (file-name-all-completions
1704 base-versions
1705 (file-name-directory fn))
1706 versions (sort (mapcar
1707 (function backup-extract-version)
1708 possibilities)
1710 high-water-mark (apply 'max 0 versions)
1711 deserve-versions-p (or version-control
1712 (> high-water-mark 0))
1713 number-to-delete (- (length versions)
1714 kept-old-versions kept-new-versions -1))
1715 (file-error
1716 (setq possibilities nil)))
1717 (if (not deserve-versions-p)
1718 (list (make-backup-file-name fn))
1719 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
1720 (if (and (> number-to-delete 0)
1721 ;; Delete nothing if there is overflow
1722 ;; in the number of versions to keep.
1723 (>= (+ kept-new-versions kept-old-versions -1) 0))
1724 (mapcar (function (lambda (n)
1725 (concat fn ".~" (int-to-string n) "~")))
1726 (let ((v (nthcdr kept-old-versions versions)))
1727 (rplacd (nthcdr (1- number-to-delete) v) ())
1728 v))))))))))
1730 (defun file-nlinks (filename)
1731 "Return number of names file FILENAME has."
1732 (car (cdr (file-attributes filename))))
1734 (defun file-relative-name (filename &optional directory)
1735 "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
1736 (setq filename (expand-file-name filename)
1737 directory (file-name-as-directory (expand-file-name
1738 (or directory default-directory))))
1739 (let ((ancestor ""))
1740 (while (not (string-match (concat "^" (regexp-quote directory)) filename))
1741 (setq directory (file-name-directory (substring directory 0 -1))
1742 ancestor (concat "../" ancestor)))
1743 (concat ancestor (substring filename (match-end 0)))))
1745 (defun save-buffer (&optional args)
1746 "Save current buffer in visited file if modified. Versions described below.
1747 By default, makes the previous version into a backup file
1748 if previously requested or if this is the first save.
1749 With 1 \\[universal-argument], marks this version
1750 to become a backup when the next save is done.
1751 With 2 \\[universal-argument]'s,
1752 unconditionally makes the previous version into a backup file.
1753 With 3 \\[universal-argument]'s, marks this version
1754 to become a backup when the next save is done,
1755 and unconditionally makes the previous version into a backup file.
1757 With argument of 0, never makes the previous version into a backup file.
1759 If a file's name is FOO, the names of its numbered backup versions are
1760 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
1761 Numeric backups (rather than FOO~) will be made if value of
1762 `version-control' is not the atom `never' and either there are already
1763 numeric versions of the file being backed up, or `version-control' is
1764 non-nil.
1765 We don't want excessive versions piling up, so there are variables
1766 `kept-old-versions', which tells Emacs how many oldest versions to keep,
1767 and `kept-new-versions', which tells how many newest versions to keep.
1768 Defaults are 2 old versions and 2 new.
1769 `dired-kept-versions' controls dired's clean-directory (.) command.
1770 If `delete-old-versions' is nil, system will query user
1771 before trimming versions. Otherwise it does it silently."
1772 (interactive "p")
1773 (let ((modp (buffer-modified-p))
1774 (large (> (buffer-size) 50000))
1775 (make-backup-files (or (and make-backup-files (not (eq args 0)))
1776 (memq args '(16 64)))))
1777 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
1778 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
1779 (basic-save-buffer)
1780 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
1782 (defun delete-auto-save-file-if-necessary (&optional force)
1783 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
1784 Normally delete only if the file was written by this Emacs since
1785 the last real save, but optional arg FORCE non-nil means delete anyway."
1786 (and buffer-auto-save-file-name delete-auto-save-files
1787 (not (string= buffer-file-name buffer-auto-save-file-name))
1788 (or force (recent-auto-save-p))
1789 (progn
1790 (condition-case ()
1791 (delete-file buffer-auto-save-file-name)
1792 (file-error nil))
1793 (set-buffer-auto-saved))))
1795 (defvar after-save-hook nil
1796 "Normal hook that is run after a buffer is saved to its file.")
1798 (defun basic-save-buffer ()
1799 "Save the current buffer in its visited file, if it has been modified.
1800 After saving the buffer, run `after-save-hook'."
1801 (interactive)
1802 (save-excursion
1803 ;; In an indirect buffer, save its base buffer instead.
1804 (if (buffer-base-buffer)
1805 (set-buffer (buffer-base-buffer)))
1806 (if (buffer-modified-p)
1807 (let ((recent-save (recent-auto-save-p))
1808 setmodes tempsetmodes)
1809 ;; On VMS, rename file and buffer to get rid of version number.
1810 (if (and (eq system-type 'vax-vms)
1811 (not (string= buffer-file-name
1812 (file-name-sans-versions buffer-file-name))))
1813 (let (buffer-new-name)
1814 ;; Strip VMS version number before save.
1815 (setq buffer-file-name
1816 (file-name-sans-versions buffer-file-name))
1817 ;; Construct a (unique) buffer name to correspond.
1818 (let ((buf (create-file-buffer (downcase buffer-file-name))))
1819 (setq buffer-new-name (buffer-name buf))
1820 (kill-buffer buf))
1821 (rename-buffer buffer-new-name)))
1822 ;; If buffer has no file name, ask user for one.
1823 (or buffer-file-name
1824 (let ((filename
1825 (expand-file-name
1826 (read-file-name "File to save in: ") nil)))
1827 (and (file-exists-p filename)
1828 (or (y-or-n-p (format "File `%s' exists; overwrite? "
1829 filename))
1830 (error "Canceled")))
1831 (set-visited-file-name filename)))
1832 (or (verify-visited-file-modtime (current-buffer))
1833 (not (file-exists-p buffer-file-name))
1834 (yes-or-no-p
1835 (format "%s has changed since visited or saved. Save anyway? "
1836 (file-name-nondirectory buffer-file-name)))
1837 (error "Save not confirmed"))
1838 (save-restriction
1839 (widen)
1840 (and (> (point-max) 1)
1841 (/= (char-after (1- (point-max))) ?\n)
1842 (not (and (eq selective-display t)
1843 (= (char-after (1- (point-max))) ?\r)))
1844 (or (eq require-final-newline t)
1845 (and require-final-newline
1846 (y-or-n-p
1847 (format "Buffer %s does not end in newline. Add one? "
1848 (buffer-name)))))
1849 (save-excursion
1850 (goto-char (point-max))
1851 (insert ?\n)))
1852 (or (run-hook-with-args-until-success 'write-contents-hooks)
1853 (run-hook-with-args-until-success 'local-write-file-hooks)
1854 (run-hook-with-args-until-success 'write-file-hooks)
1855 ;; If a hook returned t, file is already "written".
1856 ;; Otherwise, write it the usual way now.
1857 (setq setmodes (basic-save-buffer-1)))
1858 (setq buffer-file-number
1859 (nthcdr 10 (file-attributes buffer-file-name)))
1860 (if setmodes
1861 (condition-case ()
1862 (set-file-modes buffer-file-name setmodes)
1863 (error nil))))
1864 ;; If the auto-save file was recent before this command,
1865 ;; delete it now.
1866 (delete-auto-save-file-if-necessary recent-save)
1867 ;; Support VC `implicit' locking.
1868 (vc-after-save)
1869 (run-hooks 'after-save-hook))
1870 (message "(No changes need to be saved)"))))
1872 ;; This does the "real job" of writing a buffer into its visited file
1873 ;; and making a backup file. This is what is normally done
1874 ;; but inhibited if one of write-file-hooks returns non-nil.
1875 ;; It returns a value to store in setmodes.
1876 (defun basic-save-buffer-1 ()
1877 (let (tempsetmodes setmodes)
1878 (if (not (file-writable-p buffer-file-name))
1879 (let ((dir (file-name-directory buffer-file-name)))
1880 (if (not (file-directory-p dir))
1881 (error "%s is not a directory" dir)
1882 (if (not (file-exists-p buffer-file-name))
1883 (error "Directory %s write-protected" dir)
1884 (if (yes-or-no-p
1885 (format "File %s is write-protected; try to save anyway? "
1886 (file-name-nondirectory
1887 buffer-file-name)))
1888 (setq tempsetmodes t)
1889 (error "Attempt to save to a file which you aren't allowed to write"))))))
1890 (or buffer-backed-up
1891 (setq setmodes (backup-buffer)))
1892 (let ((dir (file-name-directory buffer-file-name)))
1893 (if (and file-precious-flag
1894 (file-writable-p dir))
1895 ;; If file is precious, write temp name, then rename it.
1896 ;; This requires write access to the containing dir,
1897 ;; which is why we don't try it if we don't have that access.
1898 (let ((realname buffer-file-name)
1899 tempname temp nogood i succeed
1900 (old-modtime (visited-file-modtime)))
1901 (setq i 0)
1902 (setq nogood t)
1903 ;; Find the temporary name to write under.
1904 (while nogood
1905 (setq tempname (format
1906 (if (eq system-type 'ms-dos)
1907 "%s#%d.tm#" ; MSDOS limits files to 8+3
1908 "%s#tmp#%d")
1909 dir i))
1910 (setq nogood (file-exists-p tempname))
1911 (setq i (1+ i)))
1912 (unwind-protect
1913 (progn (clear-visited-file-modtime)
1914 (write-region (point-min) (point-max)
1915 tempname nil realname
1916 buffer-file-truename)
1917 (setq succeed t))
1918 ;; If writing the temp file fails,
1919 ;; delete the temp file.
1920 (or succeed
1921 (progn
1922 (delete-file tempname)
1923 (set-visited-file-modtime old-modtime))))
1924 ;; Since we have created an entirely new file
1925 ;; and renamed it, make sure it gets the
1926 ;; right permission bits set.
1927 (setq setmodes (file-modes buffer-file-name))
1928 ;; We succeeded in writing the temp file,
1929 ;; so rename it.
1930 (rename-file tempname buffer-file-name t))
1931 ;; If file not writable, see if we can make it writable
1932 ;; temporarily while we write it.
1933 ;; But no need to do so if we have just backed it up
1934 ;; (setmodes is set) because that says we're superseding.
1935 (cond ((and tempsetmodes (not setmodes))
1936 ;; Change the mode back, after writing.
1937 (setq setmodes (file-modes buffer-file-name))
1938 (set-file-modes buffer-file-name 511)))
1939 (write-region (point-min) (point-max)
1940 buffer-file-name nil t buffer-file-truename)))
1941 setmodes))
1943 (defun save-some-buffers (&optional arg exiting)
1944 "Save some modified file-visiting buffers. Asks user about each one.
1945 Optional argument (the prefix) non-nil means save all with no questions.
1946 Optional second argument EXITING means ask about certain non-file buffers
1947 as well as about file buffers."
1948 (interactive "P")
1949 (save-window-excursion
1950 (let* ((queried nil)
1951 (files-done
1952 (map-y-or-n-p
1953 (function
1954 (lambda (buffer)
1955 (and (buffer-modified-p buffer)
1956 (not (buffer-base-buffer buffer))
1958 (buffer-file-name buffer)
1959 (and exiting
1960 (progn
1961 (set-buffer buffer)
1962 (and buffer-offer-save (> (buffer-size) 0)))))
1963 (if arg
1965 (setq queried t)
1966 (if (buffer-file-name buffer)
1967 (format "Save file %s? "
1968 (buffer-file-name buffer))
1969 (format "Save buffer %s? "
1970 (buffer-name buffer)))))))
1971 (function
1972 (lambda (buffer)
1973 (set-buffer buffer)
1974 (save-buffer)))
1975 (buffer-list)
1976 '("buffer" "buffers" "save")
1977 (list (list ?\C-r (lambda (buf)
1978 (view-buffer buf)
1979 (setq view-exit-action
1980 '(lambda (ignore)
1981 (exit-recursive-edit)))
1982 (recursive-edit)
1983 ;; Return nil to ask about BUF again.
1984 nil)
1985 "display the current buffer"))))
1986 (abbrevs-done
1987 (and save-abbrevs abbrevs-changed
1988 (progn
1989 (if (or arg
1990 (y-or-n-p (format "Save abbrevs in %s? "
1991 abbrev-file-name)))
1992 (write-abbrev-file nil))
1993 ;; Don't keep bothering user if he says no.
1994 (setq abbrevs-changed nil)
1995 t))))
1996 (or queried (> files-done 0) abbrevs-done
1997 (message "(No files need saving)")))))
1999 (defun not-modified (&optional arg)
2000 "Mark current buffer as unmodified, not needing to be saved.
2001 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2003 It is not a good idea to use this function in Lisp programs, because it
2004 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2005 (interactive "P")
2006 (message (if arg "Modification-flag set"
2007 "Modification-flag cleared"))
2008 (set-buffer-modified-p arg))
2010 (defun toggle-read-only (&optional arg)
2011 "Change whether this buffer is visiting its file read-only.
2012 With arg, set read-only iff arg is positive."
2013 (interactive "P")
2014 (setq buffer-read-only
2015 (if (null arg)
2016 (not buffer-read-only)
2017 (> (prefix-numeric-value arg) 0)))
2018 (force-mode-line-update))
2020 (defun insert-file (filename)
2021 "Insert contents of file FILENAME into buffer after point.
2022 Set mark after the inserted text.
2024 This function is meant for the user to run interactively.
2025 Don't call it from programs! Use `insert-file-contents' instead.
2026 \(Its calling sequence is different; see its documentation)."
2027 (interactive "*fInsert file: ")
2028 (if (file-directory-p filename)
2029 (signal 'file-error (list "Opening input file" "file is a directory"
2030 filename)))
2031 (let ((tem (insert-file-contents filename)))
2032 (push-mark (+ (point) (car (cdr tem))))))
2034 (defun append-to-file (start end filename)
2035 "Append the contents of the region to the end of file FILENAME.
2036 When called from a function, expects three arguments,
2037 START, END and FILENAME. START and END are buffer positions
2038 saying what text to write."
2039 (interactive "r\nFAppend to file: ")
2040 (write-region start end filename t))
2042 (defun file-newest-backup (filename)
2043 "Return most recent backup file for FILENAME or nil if no backups exist."
2044 (let* ((filename (expand-file-name filename))
2045 (file (file-name-nondirectory filename))
2046 (dir (file-name-directory filename))
2047 (comp (file-name-all-completions file dir))
2048 newest)
2049 (while comp
2050 (setq file (concat dir (car comp))
2051 comp (cdr comp))
2052 (if (and (backup-file-name-p file)
2053 (or (null newest) (file-newer-than-file-p file newest)))
2054 (setq newest file)))
2055 newest))
2057 (defun rename-uniquely ()
2058 "Rename current buffer to a similar name not already taken.
2059 This function is useful for creating multiple shell process buffers
2060 or multiple mail buffers, etc."
2061 (interactive)
2062 (save-match-data
2063 (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
2064 (not (and buffer-file-name
2065 (string= (buffer-name)
2066 (file-name-nondirectory
2067 buffer-file-name)))))
2068 ;; If the existing buffer name has a <NNN>,
2069 ;; which isn't part of the file name (if any),
2070 ;; then get rid of that.
2071 (substring (buffer-name) 0 (match-beginning 0))
2072 (buffer-name)))
2073 (new-buf (generate-new-buffer base-name))
2074 (name (buffer-name new-buf)))
2075 (kill-buffer new-buf)
2076 (rename-buffer name)
2077 (force-mode-line-update))))
2079 (defun make-directory (dir &optional parents)
2080 "Create the directory DIR and any nonexistent parent dirs.
2081 Interactively, the default choice of directory to create
2082 is the current default directory for file names.
2083 That is useful when you have visited a file in a nonexistent directory.
2085 Noninteractively, the second (optional) argument PARENTS says whether
2086 to create parent directories if they don't exist."
2087 (interactive
2088 (list (read-file-name "Make directory: " default-directory default-directory
2089 nil nil)
2091 (let ((handler (find-file-name-handler dir 'make-directory)))
2092 (if handler
2093 (funcall handler 'make-directory dir parents)
2094 (if (not parents)
2095 (make-directory-internal dir)
2096 (let ((dir (directory-file-name (expand-file-name dir)))
2097 create-list)
2098 (while (not (file-exists-p dir))
2099 (setq create-list (cons dir create-list)
2100 dir (directory-file-name (file-name-directory dir))))
2101 (while create-list
2102 (make-directory-internal (car create-list))
2103 (setq create-list (cdr create-list))))))))
2105 (put 'revert-buffer-function 'permanent-local t)
2106 (defvar revert-buffer-function nil
2107 "Function to use to revert this buffer, or nil to do the default.
2108 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2109 which are the arguments that `revert-buffer' received.")
2111 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2112 (defvar revert-buffer-insert-file-contents-function nil
2113 "Function to use to insert contents when reverting this buffer.
2114 Gets two args, first the nominal file name to use,
2115 and second, t if reading the auto-save file.")
2117 (defvar before-revert-hook nil
2118 "Normal hook for `revert-buffer' to run before reverting.
2119 If `revert-buffer-function' is used to override the normal revert
2120 mechanism, this hook is not used.")
2122 (defvar after-revert-hook nil
2123 "Normal hook for `revert-buffer' to run after reverting.
2124 Note that the hook value that it runs is the value that was in effect
2125 before reverting; that makes a difference if you have buffer-local
2126 hook functions.
2128 If `revert-buffer-function' is used to override the normal revert
2129 mechanism, this hook is not used.")
2131 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2132 "Replace the buffer text with the text of the visited file on disk.
2133 This undoes all changes since the file was visited or saved.
2134 With a prefix argument, offer to revert from latest auto-save file, if
2135 that is more recent than the visited file.
2137 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2138 to revert from the auto-save file when this is nil. Note that the
2139 sense of this argument is the reverse of the prefix argument, for the
2140 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2141 to nil.
2143 Optional second argument NOCONFIRM means don't ask for confirmation at
2144 all.
2146 If the value of `revert-buffer-function' is non-nil, it is called to
2147 do the work.
2149 The default revert function runs the hook `before-revert-hook' at the
2150 beginning and `after-revert-hook' at the end."
2151 ;; I admit it's odd to reverse the sense of the prefix argument, but
2152 ;; there is a lot of code out there which assumes that the first
2153 ;; argument should be t to avoid consulting the auto-save file, and
2154 ;; there's no straightforward way to encourage authors to notice a
2155 ;; reversal of the argument sense. So I'm just changing the user
2156 ;; interface, but leaving the programmatic interface the same.
2157 (interactive (list (not current-prefix-arg)))
2158 (if revert-buffer-function
2159 (funcall revert-buffer-function ignore-auto noconfirm)
2160 (let* ((opoint (point))
2161 (auto-save-p (and (not ignore-auto)
2162 (recent-auto-save-p)
2163 buffer-auto-save-file-name
2164 (file-readable-p buffer-auto-save-file-name)
2165 (y-or-n-p
2166 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2167 (file-name (if auto-save-p
2168 buffer-auto-save-file-name
2169 buffer-file-name)))
2170 (cond ((null file-name)
2171 (error "Buffer does not seem to be associated with any file"))
2172 ((or noconfirm
2173 (yes-or-no-p (format "Revert buffer from file %s? "
2174 file-name)))
2175 (run-hooks 'before-revert-hook)
2176 ;; If file was backed up but has changed since,
2177 ;; we shd make another backup.
2178 (and (not auto-save-p)
2179 (not (verify-visited-file-modtime (current-buffer)))
2180 (setq buffer-backed-up nil))
2181 ;; Get rid of all undo records for this buffer.
2182 (or (eq buffer-undo-list t)
2183 (setq buffer-undo-list nil))
2184 ;; Effectively copy the after-revert-hook status,
2185 ;; since after-find-file will clobber it.
2186 (let ((global-hook (default-value 'after-revert-hook))
2187 (local-hook-p (local-variable-p 'after-revert-hook))
2188 (local-hook (and (local-variable-p 'after-revert-hook)
2189 after-revert-hook)))
2190 (let (buffer-read-only
2191 ;; Don't make undo records for the reversion.
2192 (buffer-undo-list t))
2193 (if revert-buffer-insert-file-contents-function
2194 (funcall revert-buffer-insert-file-contents-function
2195 file-name auto-save-p)
2196 (if (not (file-exists-p file-name))
2197 (error "File %s no longer exists!" file-name))
2198 ;; Bind buffer-file-name to nil
2199 ;; so that we don't try to lock the file.
2200 (let ((buffer-file-name nil))
2201 (or auto-save-p
2202 (unlock-buffer)))
2203 (widen)
2204 (insert-file-contents file-name (not auto-save-p)
2205 nil nil t)))
2206 (goto-char (min opoint (point-max)))
2207 ;; Recompute the truename in case changes in symlinks
2208 ;; have changed the truename.
2209 (setq buffer-file-truename
2210 (abbreviate-file-name (file-truename buffer-file-name)))
2211 (after-find-file nil nil t t preserve-modes)
2212 ;; Run after-revert-hook as it was before we reverted.
2213 (setq-default revert-buffer-internal-hook global-hook)
2214 (if local-hook-p
2215 (progn
2216 (make-local-variable 'revert-buffer-internal-hook)
2217 (setq revert-buffer-internal-hook local-hook))
2218 (kill-local-variable 'revert-buffer-internal-hook))
2219 (run-hooks 'revert-buffer-internal-hook))
2220 t)))))
2222 (defun recover-file (file)
2223 "Visit file FILE, but get contents from its last auto-save file."
2224 ;; Actually putting the file name in the minibuffer should be used
2225 ;; only rarely.
2226 ;; Not just because users often use the default.
2227 (interactive "FRecover file: ")
2228 (setq file (expand-file-name file))
2229 (if (auto-save-file-name-p (file-name-nondirectory file))
2230 (error "%s is an auto-save file" file))
2231 (let ((file-name (let ((buffer-file-name file))
2232 (make-auto-save-file-name))))
2233 (cond ((if (file-exists-p file)
2234 (not (file-newer-than-file-p file-name file))
2235 (not (file-exists-p file-name)))
2236 (error "Auto-save file %s not current" file-name))
2237 ((save-window-excursion
2238 (if (not (eq system-type 'vax-vms))
2239 (with-output-to-temp-buffer "*Directory*"
2240 (buffer-disable-undo standard-output)
2241 (call-process "ls" nil standard-output nil
2242 (if (file-symlink-p file) "-lL" "-l")
2243 file file-name)))
2244 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2245 (switch-to-buffer (find-file-noselect file t))
2246 (let ((buffer-read-only nil))
2247 (erase-buffer)
2248 (insert-file-contents file-name nil))
2249 (after-find-file nil nil t))
2250 (t (error "Recover-file cancelled.")))))
2252 (defun recover-session ()
2253 "Recover auto save files from a previous Emacs session.
2254 This command first displays a Dired buffer showing you the
2255 previous sessions that you could recover from.
2256 To choose one, move point to the proper line and then type C-c C-c.
2257 Then you'll be asked about a number of files to recover."
2258 (interactive)
2259 (let ((ls-lisp-support-shell-wildcards t))
2260 (dired (concat auto-save-list-file-prefix "*")))
2261 (goto-char (point-min))
2262 (or (looking-at "Move to the session you want to recover,")
2263 (let ((inhibit-read-only t))
2264 (insert "Move to the session you want to recover,\n"
2265 "then type C-c C-c to select it.\n\n"
2266 "You can also delete some of these files;\n"
2267 "type d on a line to mark that file for deletion.\n\n")))
2268 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2269 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
2271 (defun recover-session-finish ()
2272 "Choose one saved session to recover auto-save files from.
2273 This command is used in the special Dired buffer created by
2274 \\[recover-session]."
2275 (interactive)
2276 ;; Get the name of the session file to recover from.
2277 (let ((file (dired-get-filename))
2278 files
2279 (buffer (get-buffer-create " *recover*")))
2280 (dired-do-flagged-delete t)
2281 (unwind-protect
2282 (save-excursion
2283 ;; Read in the auto-save-list file.
2284 (set-buffer buffer)
2285 (erase-buffer)
2286 (insert-file-contents file)
2287 ;; Loop thru the text of that file
2288 ;; and get out the names of the files to recover.
2289 (while (not (eobp))
2290 (let (thisfile autofile)
2291 (if (eolp)
2292 ;; This is a pair of lines for a non-file-visiting buffer.
2293 ;; Get the auto-save file name and manufacture
2294 ;; a "visited file name" from that.
2295 (progn
2296 (forward-line 1)
2297 (setq autofile
2298 (buffer-substring-no-properties
2299 (point)
2300 (save-excursion
2301 (end-of-line)
2302 (point))))
2303 (setq thisfile
2304 (expand-file-name
2305 (substring
2306 (file-name-nondirectory autofile)
2307 1 -1)
2308 (file-name-directory autofile)))
2309 (forward-line 1))
2310 ;; This pair of lines is a file-visiting
2311 ;; buffer. Use the visited file name.
2312 (progn
2313 (setq thisfile
2314 (buffer-substring-no-properties
2315 (point) (progn (end-of-line) (point))))
2316 (forward-line 1)
2317 (setq autofile
2318 (buffer-substring-no-properties
2319 (point) (progn (end-of-line) (point))))
2320 (forward-line 1)))
2321 ;; Ignore a file if its auto-save file does not exist now.
2322 (if (file-exists-p autofile)
2323 (setq files (cons thisfile files)))))
2324 (setq files (nreverse files))
2325 ;; The file contains a pair of line for each auto-saved buffer.
2326 ;; The first line of the pair contains the visited file name
2327 ;; or is empty if the buffer was not visiting a file.
2328 ;; The second line is the auto-save file name.
2329 (if files
2330 (map-y-or-n-p "Recover %s? "
2331 (lambda (file)
2332 (condition-case nil
2333 (save-excursion (recover-file file))
2334 (error
2335 "Failed to recover `%s'" file)))
2336 files
2337 '("file" "files" "recover"))
2338 (message "No files can be recovered from this session now")))
2339 (kill-buffer buffer))))
2341 (defun kill-some-buffers ()
2342 "For each buffer, ask whether to kill it."
2343 (interactive)
2344 (let ((list (buffer-list)))
2345 (while list
2346 (let* ((buffer (car list))
2347 (name (buffer-name buffer)))
2348 (and (not (string-equal name ""))
2349 (/= (aref name 0) ? )
2350 (yes-or-no-p
2351 (format "Buffer %s %s. Kill? "
2352 name
2353 (if (buffer-modified-p buffer)
2354 "HAS BEEN EDITED" "is unmodified")))
2355 (kill-buffer buffer)))
2356 (setq list (cdr list)))))
2358 (defun auto-save-mode (arg)
2359 "Toggle auto-saving of contents of current buffer.
2360 With prefix argument ARG, turn auto-saving on if positive, else off."
2361 (interactive "P")
2362 (setq buffer-auto-save-file-name
2363 (and (if (null arg)
2364 (or (not buffer-auto-save-file-name)
2365 ;; If autosave is off because buffer has shrunk,
2366 ;; then toggling should turn it on.
2367 (< buffer-saved-size 0))
2368 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2369 (if (and buffer-file-name auto-save-visited-file-name
2370 (not buffer-read-only))
2371 buffer-file-name
2372 (make-auto-save-file-name))))
2373 ;; If -1 was stored here, to temporarily turn off saving,
2374 ;; turn it back on.
2375 (and (< buffer-saved-size 0)
2376 (setq buffer-saved-size 0))
2377 (if (interactive-p)
2378 (message "Auto-save %s (in this buffer)"
2379 (if buffer-auto-save-file-name "on" "off")))
2380 buffer-auto-save-file-name)
2382 (defun rename-auto-save-file ()
2383 "Adjust current buffer's auto save file name for current conditions.
2384 Also rename any existing auto save file, if it was made in this session."
2385 (let ((osave buffer-auto-save-file-name))
2386 (setq buffer-auto-save-file-name
2387 (make-auto-save-file-name))
2388 (if (and osave buffer-auto-save-file-name
2389 (not (string= buffer-auto-save-file-name buffer-file-name))
2390 (not (string= buffer-auto-save-file-name osave))
2391 (file-exists-p osave)
2392 (recent-auto-save-p))
2393 (rename-file osave buffer-auto-save-file-name t))))
2395 (defun make-auto-save-file-name ()
2396 "Return file name to use for auto-saves of current buffer.
2397 Does not consider `auto-save-visited-file-name' as that variable is checked
2398 before calling this function. You can redefine this for customization.
2399 See also `auto-save-file-name-p'."
2400 (if buffer-file-name
2401 (if (eq system-type 'ms-dos)
2402 (let ((fn (file-name-nondirectory buffer-file-name)))
2403 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
2404 (concat (file-name-directory buffer-file-name)
2405 "#" (match-string 1 fn)
2406 "." (match-string 3 fn) "#"))
2407 (concat (file-name-directory buffer-file-name)
2409 (file-name-nondirectory buffer-file-name)
2410 "#"))
2412 ;; Deal with buffers that don't have any associated files. (Mail
2413 ;; mode tends to create a good number of these.)
2415 (let ((buffer-name (buffer-name))
2416 (limit 0))
2417 ;; Use technique from Sebastian Kremer's auto-save
2418 ;; package to turn slashes into \\!. This ensures that
2419 ;; the auto-save buffer name is unique.
2421 (while (string-match "[/\\]" buffer-name limit)
2422 (setq buffer-name (concat (substring buffer-name 0 (match-beginning 0))
2423 (if (string= (substring buffer-name
2424 (match-beginning 0)
2425 (match-end 0))
2426 "/")
2427 "\\!"
2428 "\\\\")
2429 (substring buffer-name (match-end 0))))
2430 (setq limit (1+ (match-end 0))))
2432 (expand-file-name (format "#%s#%s#" buffer-name (make-temp-name ""))))))
2434 (defun auto-save-file-name-p (filename)
2435 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2436 FILENAME should lack slashes. You can redefine this for customization."
2437 (string-match "^#.*#$" filename))
2439 (defun wildcard-to-regexp (wildcard)
2440 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2441 The generated regexp will match a filename iff the filename
2442 matches that wildcard according to shell rules. Only wildcards known
2443 by `sh' are supported."
2444 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
2445 ;; Copy the initial run of non-special characters.
2446 (result (substring wildcard 0 i))
2447 (len (length wildcard)))
2448 ;; If no special characters, we're almost done.
2449 (if i
2450 (while (< i len)
2451 (let ((ch (aref wildcard i))
2453 (setq
2454 result
2455 (concat result
2456 (cond
2457 ((eq ch ?\[) ; [...] maps to regexp char class
2458 (progn
2459 (setq i (1+ i))
2460 (concat
2461 (cond
2462 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
2463 (progn
2464 (setq i (1+ i))
2465 (if (eq (aref wildcard i) ?\])
2466 (progn
2467 (setq i (1+ i))
2468 "[^]")
2469 "[^")))
2470 ((eq (aref wildcard i) ?^)
2471 ;; Found "[^". Insert a `\0' character
2472 ;; (which cannot happen in a filename)
2473 ;; into the character class, so that `^'
2474 ;; is not the first character after `[',
2475 ;; and thus non-special in a regexp.
2476 (progn
2477 (setq i (1+ i))
2478 "[\000^"))
2479 ((eq (aref wildcard i) ?\])
2480 ;; I don't think `]' can appear in a
2481 ;; character class in a wildcard, but
2482 ;; let's be general here.
2483 (progn
2484 (setq i (1+ i))
2485 "[]"))
2486 (t "["))
2487 (prog1 ; copy everything upto next `]'.
2488 (substring wildcard
2490 (setq j (string-match
2491 "]" wildcard i)))
2492 (setq i (if j (1- j) (1- len)))))))
2493 ((eq ch ?.) "\\.")
2494 ((eq ch ?*) "[^\000]*")
2495 ((eq ch ?+) "\\+")
2496 ((eq ch ?^) "\\^")
2497 ((eq ch ?$) "\\$")
2498 ((eq ch ?\\) "\\\\") ; probably cannot happen...
2499 ((eq ch ??) "[^\000]")
2500 (t (char-to-string ch)))))
2501 (setq i (1+ i)))))
2502 ;; Shell wildcards should match the entire filename,
2503 ;; not its part. Make the regexp say so.
2504 (concat "\\`" result "\\'")))
2506 (defconst list-directory-brief-switches
2507 (if (eq system-type 'vax-vms) "" "-CF")
2508 "*Switches for list-directory to pass to `ls' for brief listing,")
2510 (defconst list-directory-verbose-switches
2511 (if (eq system-type 'vax-vms)
2512 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2513 "-l")
2514 "*Switches for list-directory to pass to `ls' for verbose listing,")
2516 (defun list-directory (dirname &optional verbose)
2517 "Display a list of files in or matching DIRNAME, a la `ls'.
2518 DIRNAME is globbed by the shell if necessary.
2519 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2520 Actions controlled by variables `list-directory-brief-switches'
2521 and `list-directory-verbose-switches'."
2522 (interactive (let ((pfx current-prefix-arg))
2523 (list (read-file-name (if pfx "List directory (verbose): "
2524 "List directory (brief): ")
2525 nil default-directory nil)
2526 pfx)))
2527 (let ((switches (if verbose list-directory-verbose-switches
2528 list-directory-brief-switches)))
2529 (or dirname (setq dirname default-directory))
2530 (setq dirname (expand-file-name dirname))
2531 (with-output-to-temp-buffer "*Directory*"
2532 (buffer-disable-undo standard-output)
2533 (princ "Directory ")
2534 (princ dirname)
2535 (terpri)
2536 (save-excursion
2537 (set-buffer "*Directory*")
2538 (setq default-directory (file-name-directory dirname))
2539 (let ((wildcard (not (file-directory-p dirname))))
2540 (insert-directory dirname switches wildcard (not wildcard)))))))
2542 (defvar insert-directory-program "ls"
2543 "Absolute or relative name of the `ls' program used by `insert-directory'.")
2545 ;; insert-directory
2546 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
2547 ;; FULL-DIRECTORY-P is nil.
2548 ;; The single line of output must display FILE's name as it was
2549 ;; given, namely, an absolute path name.
2550 ;; - must insert exactly one line for each file if WILDCARD or
2551 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
2552 ;; before the file lines, plus optional text after the file lines.
2553 ;; Lines are delimited by "\n", so filenames containing "\n" are not
2554 ;; allowed.
2555 ;; File lines should display the basename.
2556 ;; - must be consistent with
2557 ;; - functions dired-move-to-filename, (these two define what a file line is)
2558 ;; dired-move-to-end-of-filename,
2559 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
2560 ;; dired-insert-headerline
2561 ;; dired-after-subdir-garbage (defines what a "total" line is)
2562 ;; - variable dired-subdir-regexp
2563 (defun insert-directory (file switches &optional wildcard full-directory-p)
2564 "Insert directory listing for FILE, formatted according to SWITCHES.
2565 Leaves point after the inserted text.
2566 SWITCHES may be a string of options, or a list of strings.
2567 Optional third arg WILDCARD means treat FILE as shell wildcard.
2568 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
2569 switches do not contain `d', so that a full listing is expected.
2571 This works by running a directory listing program
2572 whose name is in the variable `insert-directory-program'.
2573 If WILDCARD, it also runs the shell specified by `shell-file-name'."
2574 ;; We need the directory in order to find the right handler.
2575 (let ((handler (find-file-name-handler (expand-file-name file)
2576 'insert-directory)))
2577 (if handler
2578 (funcall handler 'insert-directory file switches
2579 wildcard full-directory-p)
2580 (if (eq system-type 'vax-vms)
2581 (vms-read-directory file switches (current-buffer))
2582 (if wildcard
2583 ;; Run ls in the directory of the file pattern we asked for.
2584 (let ((default-directory
2585 (if (file-name-absolute-p file)
2586 (file-name-directory file)
2587 (file-name-directory (expand-file-name file))))
2588 (pattern (file-name-nondirectory file))
2589 (beg 0))
2590 ;; Quote some characters that have special meanings in shells;
2591 ;; but don't quote the wildcards--we want them to be special.
2592 ;; We also currently don't quote the quoting characters
2593 ;; in case people want to use them explicitly to quote
2594 ;; wildcard characters.
2595 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
2596 (setq pattern
2597 (concat (substring pattern 0 (match-beginning 0))
2598 "\\"
2599 (substring pattern (match-beginning 0)))
2600 beg (1+ (match-end 0))))
2601 (call-process shell-file-name nil t nil
2602 "-c" (concat "\\" ;; Disregard shell aliases!
2603 insert-directory-program
2604 " -d "
2605 (if (stringp switches)
2606 switches
2607 (mapconcat 'identity switches " "))
2609 pattern)))
2610 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
2611 ;; directory if FILE is a symbolic link.
2612 (apply 'call-process
2613 insert-directory-program nil t nil
2614 (let (list)
2615 (if (listp switches)
2616 (setq list switches)
2617 (if (not (equal switches ""))
2618 (progn
2619 ;; Split the switches at any spaces
2620 ;; so we can pass separate options as separate args.
2621 (while (string-match " " switches)
2622 (setq list (cons (substring switches 0 (match-beginning 0))
2623 list)
2624 switches (substring switches (match-end 0))))
2625 (setq list (cons switches list)))))
2626 (append list
2627 (list
2628 (if full-directory-p
2629 (concat (file-name-as-directory file) ".")
2630 file))))))))))
2632 (defvar kill-emacs-query-functions nil
2633 "Functions to call with no arguments to query about killing Emacs.
2634 If any of these functions returns nil, killing Emacs is cancelled.
2635 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
2636 but `kill-emacs', the low level primitive, does not.
2637 See also `kill-emacs-hook'.")
2639 (defun save-buffers-kill-emacs (&optional arg)
2640 "Offer to save each buffer, then kill this Emacs process.
2641 With prefix arg, silently save all file-visiting buffers, then kill."
2642 (interactive "P")
2643 (save-some-buffers arg t)
2644 (and (or (not (memq t (mapcar (function
2645 (lambda (buf) (and (buffer-file-name buf)
2646 (buffer-modified-p buf))))
2647 (buffer-list))))
2648 (yes-or-no-p "Modified buffers exist; exit anyway? "))
2649 (or (not (fboundp 'process-list))
2650 ;; process-list is not defined on VMS.
2651 (let ((processes (process-list))
2652 active)
2653 (while processes
2654 (and (memq (process-status (car processes)) '(run stop open))
2655 (let ((val (process-kill-without-query (car processes))))
2656 (process-kill-without-query (car processes) val)
2657 val)
2658 (setq active t))
2659 (setq processes (cdr processes)))
2660 (or (not active)
2661 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
2662 ;; Query the user for other things, perhaps.
2663 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
2664 (kill-emacs)))
2666 (define-key ctl-x-map "\C-f" 'find-file)
2667 (define-key ctl-x-map "\C-q" 'toggle-read-only)
2668 (define-key ctl-x-map "\C-r" 'find-file-read-only)
2669 (define-key ctl-x-map "\C-v" 'find-alternate-file)
2670 (define-key ctl-x-map "\C-s" 'save-buffer)
2671 (define-key ctl-x-map "s" 'save-some-buffers)
2672 (define-key ctl-x-map "\C-w" 'write-file)
2673 (define-key ctl-x-map "i" 'insert-file)
2674 (define-key esc-map "~" 'not-modified)
2675 (define-key ctl-x-map "\C-d" 'list-directory)
2676 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
2678 (define-key ctl-x-4-map "f" 'find-file-other-window)
2679 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
2680 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
2681 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
2682 (define-key ctl-x-4-map "\C-o" 'display-buffer)
2684 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
2685 (define-key ctl-x-5-map "f" 'find-file-other-frame)
2686 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
2687 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
2689 ;;; files.el ends here