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