home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / lucid / lemacs-19.6 / lisp / prim / files.el < prev    next >
Encoding:
Text File  |  1993-02-15  |  54.2 KB  |  1,430 lines

  1. ;; File input and output commands for Emacs
  2. ;; Copyright (C) 1985-1993 Free Software Foundation, Inc.
  3.  
  4. ;; This file is part of GNU Emacs.
  5.  
  6. ;; GNU Emacs is free software; you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation; either version 2, or (at your option)
  9. ;; any later version.
  10.  
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. ;; GNU General Public License for more details.
  15.  
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  18. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  
  20. (defconst delete-auto-save-files t
  21.   "*Non-nil means delete a buffer's auto-save file
  22. when the buffer is saved for real.")
  23.  
  24. ;;; Turn off backup files on VMS since it has version numbers.
  25. (defconst make-backup-files (not (eq system-type 'vax-vms))
  26.   "*Create a backup of each file when it is saved for the first time.
  27. This can be done by renaming the file or by copying.
  28.  
  29. Renaming means that Emacs renames the existing file so that it is a
  30. backup file, then writes the buffer into a new file.  Any other names
  31. that the old file had will now refer to the backup file.
  32. The new file is owned by you and its group is defaulted.
  33.  
  34. Copying means that Emacs copies the existing file into the backup file,
  35. then writes the buffer on top of the existing file.  Any other names
  36. that the old file had will now refer to the new (edited) file.
  37. The file's owner and group are unchanged.
  38.  
  39. The choice of renaming or copying is controlled by the variables
  40. backup-by-copying, backup-by-copying-when-linked and
  41. backup-by-copying-when-mismatch.")
  42.  
  43. (defconst backup-by-copying nil
  44.  "*Non-nil means always use copying to create backup files.
  45. See documentation of variable  make-backup-files.")
  46.  
  47. (defconst backup-by-copying-when-linked nil
  48.  "*Non-nil means use copying to create backups for files with multiple names.
  49. This causes the alternate names to refer to the latest version as edited.
  50. This variable is relevant only if  backup-by-copying  is nil.")
  51.  
  52. (defconst backup-by-copying-when-mismatch nil
  53.   "*Non-nil means create backups by copying if this preserves owner or group.
  54. Renaming may still be used (subject to control of other variables)
  55. when it would not result in changing the owner or group of the file;
  56. that is, for files which are owned by you and whose group matches
  57. the default for a new file created there by you.
  58. This variable is relevant only if  backup-by-copying  is nil.")
  59.  
  60. (defconst buffer-offer-save nil
  61.   "*Non-nil in a buffer means offer to save the buffer on exit
  62. even if the buffer is not visiting a file.  Automatically local in
  63. all buffers.")
  64. (make-variable-buffer-local 'buffer-offer-save)
  65.  
  66. (defconst file-precious-flag nil
  67.   "*Non-nil means protect against I/O errors while saving files.
  68. Some modes set this non-nil in particular buffers.")
  69.  
  70. (defvar version-control nil
  71.   "*Control use of version numbers for backup files.
  72. t means make numeric backup versions unconditionally.
  73. nil means make them for files that have some already.
  74. never means do not make them.")
  75.  
  76. (defvar dired-kept-versions 2
  77.   "*When cleaning directory, number of versions to keep.")
  78.  
  79. (defvar trim-versions-without-asking nil
  80.   "*If true, deletes excess backup versions silently.
  81. Otherwise asks confirmation.")
  82.  
  83. (defvar kept-old-versions 2
  84.   "*Number of oldest versions to keep when a new numbered backup is made.")
  85.  
  86. (defvar kept-new-versions 2
  87.   "*Number of newest versions to keep when a new numbered backup is made.
  88. Includes the new backup.  Must be > 0")
  89.  
  90. (defconst require-final-newline nil
  91.   "*Value of t says silently ensure a file ends in a newline when it is saved.
  92. Non-nil but not t says ask user whether to add a newline when there isn't one.
  93. nil means don't add newlines.")
  94.  
  95. (defconst auto-save-default t
  96.   "*Non-nil says by default do auto-saving of every file-visiting buffer.")
  97.  
  98. (defconst auto-save-visited-file-name nil
  99.   "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
  100. Normally auto-save files are written under other names.")
  101.  
  102. (defconst save-abbrevs nil
  103.   "*Non-nil means save word abbrevs too when files are saved.
  104. Loading an abbrev file sets this to t.")
  105.  
  106. (defconst find-file-run-dired t
  107.   "*Non-nil says run dired if find-file is given the name of a directory.")
  108.  
  109. (put 'find-file-not-found-hooks 'permanent-local t)
  110. (defvar find-file-not-found-hooks nil
  111.   "List of functions to be called for find-file on nonexistent file.
  112. These functions are called as soon as the error is detected.
  113. buffer-file-name is already set up.
  114. The functions are called in the order given,
  115. until one of them returns non-nil.")
  116.  
  117. (put 'find-file-hooks 'permanent-local t)
  118. (defvar find-file-hooks nil
  119.   "List of functions to be called after a buffer is loaded from a file.
  120. The buffer's local variables (if any) will have been processed before the
  121. functions are called.")
  122.  
  123. (put 'write-file-hooks 'permanent-local t)
  124. (defvar write-file-hooks nil
  125.   "List of functions to be called before writing out a buffer to a file.
  126. If one of them returns non-nil, the file is considered already written
  127. and the rest are not called.
  128. These hooks are considered to pertain to the visited file.
  129. So this list is cleared if you change the visited file name.
  130. See also `write-contents-hooks'.")
  131.  
  132. (defvar write-contents-hooks nil
  133.   "List of functions to be called before writing out a buffer to a file.
  134. If one of them returns non-nil, the file is considered already written
  135. and the rest are not called.
  136. These hooks are considered to pertain to the buffer's contents,
  137. not to the particular visited file; thus, `set-visited-file-name' does
  138. not clear this variable, but changing the major mode does clear it.
  139. See also `write-file-hooks'.")
  140.  
  141. (put 'write-file-data-hooks 'permanent-local t)
  142. (defvar write-file-data-hooks nil
  143.   "List of functions to be called to put the bytes on disk.  
  144. These functions receive the name of the file to write to as argument.
  145. The default behavior is to call 
  146.   (write-region (point-min) (point-max) filename nil t)
  147. If one of them returns non-nil, the file is considered already written
  148. and the rest are not called.
  149. These hooks are considered to pertain to the visited file.
  150. So this list is cleared if you change the visited file name.
  151. See also `write-file-hooks'.")
  152.  
  153. (put 'after-write-file-hooks 'permanent-local t)
  154. (defvar after-write-file-hooks nil
  155.   "List of functions to be called after writing out a buffer to a file.
  156. These hooks are considered to pertain to the visited file.
  157. So this list is cleared if you change the visited file name.")
  158.  
  159. (defconst enable-local-variables t
  160.   "*Control use of local-variables lists in files you visit.
  161. The value can be t, nil or something else.
  162. A value of t means local-variables lists are obeyed;
  163. nil means they are ignored; anything else means query.
  164.  
  165. The command \\[normal-mode] always obeys local-variables lists
  166. and ignores this variable.")
  167.  
  168. ;; Avoid losing in versions where CLASH_DETECTION is disabled.
  169. (or (fboundp 'lock-buffer)
  170.     (fset 'lock-buffer 'ignore))
  171. (or (fboundp 'unlock-buffer)
  172.     (fset 'unlock-buffer 'ignore))
  173.  
  174. (defun frob-cdlist (dir)
  175.   (let ((l cdlist)
  176.     cdpathed-dir)
  177.     (while (and l (not (file-directory-p
  178.             (setq cdpathed-dir (concat (car l) "/" dir)))))
  179.       (setq l (cdr l)))
  180.     (and l cdpathed-dir)))
  181.  
  182. (defun pwd ()
  183.   "Show the current default directory."
  184.   (interactive nil)
  185.   (message "%s" default-directory))
  186.  
  187. (defun cd (dir)
  188.   "Make DIR become the current buffer's default directory."
  189.   (interactive "DChange default directory: ")
  190.   (setq dir (expand-file-name dir))
  191.   (if (not (eq system-type 'vax-vms))
  192.       (setq dir (file-name-as-directory dir)))
  193.   (if (not (file-directory-p dir))
  194.       (error "%s is not a directory" dir)
  195.     (if (file-executable-p dir)
  196.     (setq default-directory dir)
  197.       (error "Cannot cd to %s:  Permission denied" dir)))
  198.   (pwd))
  199.  
  200. (defun load-file (file)
  201.   "Load the file FILE of Lisp code."
  202.   (interactive "fLoad file: ")
  203.   (load (expand-file-name file) nil nil t))
  204.  
  205. (defun load-library (library)
  206.   "Load the library named LIBRARY.
  207. This is an interface to the function `load'."
  208.   (interactive "sLoad library: ")
  209.   (load library))
  210.  
  211. (defun switch-to-other-buffer (arg)
  212.   "Switch to the previous buffer.  With a numeric arg, n, switch to the nth
  213. most recent buffer.  With an arg of 0, buries the current buffer at the
  214. bottom of the buffer stack."
  215.   (interactive "p")
  216.   (if (eq arg 0)
  217.       (bury-buffer (current-buffer)))
  218.   (switch-to-buffer
  219.    (if (<= arg 1) (other-buffer (current-buffer))
  220.      (nth (1+ arg) (buffer-list)))))
  221.  
  222. (defun switch-to-buffer-other-window (buffer)
  223.   "Select buffer BUFFER in another window."
  224.   (interactive "BSwitch to buffer in other window: ")
  225.   (let ((pop-up-windows t))
  226.     (pop-to-buffer buffer t)))
  227.  
  228. (defun find-file (filename)
  229.   "Edit file FILENAME.
  230. Switch to a buffer visiting file FILENAME,
  231. creating one if none already exists."
  232.   (interactive "FFind file: ")
  233.   (switch-to-buffer (find-file-noselect filename)))
  234.  
  235. (defun find-file-other-window (filename)
  236.   "Edit file FILENAME, in another window.
  237. May create a new window, or reuse an existing one;
  238. see the function display-buffer."
  239.   (interactive "FFind file in other window: ")
  240.   (switch-to-buffer-other-window (find-file-noselect filename)))
  241.  
  242. (defun find-file-read-only (filename)
  243.   "Edit file FILENAME but don't allow changes.
  244. Like \\[find-file] but marks buffer as read-only.
  245. Use \\[toggle-read-only] to permit editing."
  246.   (interactive "fFind file read-only: ")
  247.   (find-file filename)
  248.   (setq buffer-read-only t))
  249.  
  250. (defun find-file-read-only-other-window (filename)
  251.   "Edit file FILENAME in another window but don't allow changes.
  252. Like \\[find-file-other-window] but marks buffer as read-only.
  253. Use \\[toggle-read-only] to permit editing."
  254.   (interactive "fFind file read-only other window: ")
  255.   (find-file filename)
  256.   (setq buffer-read-only t))
  257.  
  258. (defun find-alternate-file (filename)
  259.   "Find file FILENAME, select its buffer, kill previous buffer.
  260. If the current buffer now contains an empty file that you just visited
  261. \(presumably by mistake), use this command to visit the file you really want."
  262.   (interactive
  263.    (let ((file buffer-file-name)
  264.      (file-name nil)
  265.      (file-dir nil))
  266.      (and file
  267.       (setq file-name (file-name-nondirectory file)
  268.         file-dir (file-name-directory file)))
  269.      (list (read-file-name
  270.         "Find alternate file: " file-dir nil nil file-name))))
  271.   (and (buffer-modified-p)
  272.        ;; (not buffer-read-only)
  273.        (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
  274.                  (buffer-name))))
  275.        (error "Aborted"))
  276.   (let ((obuf (current-buffer))
  277.     (ofile buffer-file-name)
  278.     (oname (buffer-name)))
  279.     (rename-buffer " **lose**")
  280.     (setq buffer-file-name nil)
  281.     (unwind-protect
  282.     (progn
  283.       (unlock-buffer)
  284.       (find-file filename))
  285.       (cond ((eq obuf (current-buffer))
  286.          (setq buffer-file-name ofile)
  287.          (lock-buffer)
  288.          (rename-buffer oname))))
  289.     (or (eq (current-buffer) obuf)
  290.     (kill-buffer obuf))))
  291.  
  292. (defun create-file-buffer (filename)
  293.   "Create a suitably named buffer for visiting FILENAME, and return it.
  294. FILENAME (sans directory) is used unchanged if that name is free;
  295. otherwise a string <2> or <3> or ... is appended to get an unused name."
  296.   (let ((lastname (file-name-nondirectory filename)))
  297.     (if (string= lastname "")
  298.     (setq lastname filename))
  299.     (generate-new-buffer lastname)))
  300.  
  301.  
  302. (defun compute-buffer-file-truename ()
  303.   "Recomputes this buffer's value of `buffer-file-truename'
  304. based on the current value of `buffer-file-name'."
  305.   (cond ((null buffer-file-name)
  306.      (setq buffer-file-truename nil))
  307.     ((setq buffer-file-truename (truename buffer-file-name))
  308.      ;; it exists, we're done.
  309.      nil)
  310.     (t
  311.      ;; the file doesn't exist, but maybe the directory does.
  312.      (let* ((dir (file-name-directory buffer-file-name))
  313.         (truedir (truename dir)))
  314.        (if truedir (setq dir truedir))
  315.        (setq buffer-file-truename
  316.          (expand-file-name (file-name-nondirectory buffer-file-name)
  317.                    dir)))))
  318.   (if (and find-file-use-truenames buffer-file-truename)
  319.       (setq buffer-file-name (abbreviate-file-name buffer-file-truename)
  320.         default-directory (file-name-directory buffer-file-name)))
  321.   buffer-file-truename)
  322.  
  323.  
  324. (defun find-file-noselect (filename &optional nowarn)
  325.   "Read file FILENAME into a buffer and return the buffer.
  326. If a buffer exists visiting FILENAME, return that one, but
  327. verify that the file has not changed since visited or saved.
  328. The buffer is not selected, just returned to the caller."
  329.   (setq filename (abbreviate-file-name (expand-file-name filename)))
  330.   (if (file-directory-p filename)
  331.       (if find-file-run-dired
  332.       (dired-noselect filename)
  333.     (error "%s is a directory." filename))
  334.     (let ((buf (get-file-buffer filename))
  335.       error)
  336.       (if (and buf (not nowarn)
  337.            (or find-file-compare-truenames find-file-use-truenames))
  338.       (save-excursion
  339.         (set-buffer buf)
  340.         (if (not (equal buffer-file-name filename))
  341.         (message "%s and %s are the same file (%s)"
  342.              filename buffer-file-name
  343.              buffer-file-truename))))
  344.       (if buf
  345.       (or nowarn
  346.           (verify-visited-file-modtime buf)
  347.           (cond ((not (file-exists-p filename))
  348.              (error "File %s no longer exists!" filename))
  349.             ((yes-or-no-p
  350.               (format
  351.                (if (buffer-modified-p buf)
  352.     "File %s changed on disk.  Discard your edits? "
  353.     "File %s changed on disk.  Read the new version? ")
  354.                (file-name-nondirectory filename)))
  355.              (save-excursion
  356.                (set-buffer buf)
  357.                (revert-buffer t t)))))
  358.     (save-excursion
  359.       (setq buf (create-file-buffer filename))
  360.       (set-buffer buf)
  361.       (erase-buffer)
  362.       (condition-case ()
  363.           (insert-file-contents filename t)
  364.         (file-error
  365.          (setq error t)
  366.          ;; Run find-file-not-found-hooks until one returns non-nil.
  367.          (let ((hooks find-file-not-found-hooks))
  368.            (while (and hooks
  369.                (not (funcall (car hooks))))
  370.          (setq hooks (cdr hooks))))))
  371.       ;; Set buffer's default directory to that of the file.
  372.       (setq default-directory (file-name-directory buffer-file-name))
  373.       (after-find-file error (not nowarn))))
  374.       buf)))
  375.  
  376. (defun after-find-file (&optional error warn)
  377.   "Called after finding a file and by the default revert function.
  378. Sets buffer mode, parses local variables.
  379. Optional args ERROR and WARN: ERROR non-nil means there was an
  380. error in reading the file.  WARN non-nil means warn if there
  381. exists an auto-save file more recent than the visited file.
  382. Finishes by calling the functions in find-file-hooks."
  383.   (setq buffer-read-only (not (file-writable-p buffer-file-name)))
  384.   (if noninteractive
  385.       nil
  386.     (let* (not-serious
  387.        (msg
  388.         (cond ((and error (file-attributes buffer-file-name))
  389.            (setq buffer-read-only t)
  390.            "File exists, but is read-protected.")
  391.           ((not buffer-read-only)
  392.            (if (and warn
  393.                 (file-newer-than-file-p (make-auto-save-file-name)
  394.                             buffer-file-name))
  395.                "Auto save file is newer; consider M-x recover-file"
  396.              (setq not-serious t)
  397.              (if error "(New file)" nil)))
  398.           ((not error)
  399.            (setq not-serious t)
  400.            "File is write protected")
  401.           ((file-attributes (directory-file-name default-directory))
  402.            "File not found and directory write-protected")
  403.           (t
  404.            ;; If the directory the buffer is in doesn't exist,
  405.            ;; offer to create it.  It's better to do this now
  406.            ;; than when we save the buffer, because we want
  407.            ;; autosaving to work.
  408.            (setq buffer-read-only nil)
  409.            (or (file-exists-p (file-name-directory buffer-file-name))
  410.                (if (yes-or-no-p
  411.                 (format
  412.                "The directory containing %s does not exist.  Create? "
  413.                  (abbreviate-file-name buffer-file-name)))
  414.                (make-directory-path
  415.                 (file-name-directory buffer-file-name))))
  416.            nil))))
  417.       (if msg
  418.       (progn
  419.         (message msg)
  420.         (or not-serious (sit-for 1 t)))))
  421.     (if auto-save-default
  422.     (auto-save-mode t)))
  423.   (normal-mode t)
  424.   (mapcar 'funcall find-file-hooks))
  425.  
  426. (defun normal-mode (&optional find-file)
  427.   "Choose the major mode for this buffer automatically.
  428. Also sets up any specified local variables of the file.
  429. Uses the visited file name, the -*- line, and the local variables spec.
  430.  
  431. This function is called automatically from `find-file'.  In that case,
  432. we may set up specified local variables depending on the value of
  433. `enable-local-variables': if it is t, we do; if it is nil, we don't;
  434. otherwise, we query.  `enable-local-variables' is ignored if you
  435. run `normal-mode' explicitly."
  436.   (interactive)
  437.   (or find-file (funcall (or default-major-mode 'fundamental-mode)))
  438.   (let (err)
  439.     (condition-case err
  440.     (set-auto-mode)
  441.       (error (message "File mode specification error: %s"
  442.               (prin1-to-string err))
  443.          (setq err t)))
  444.     (or err
  445.     (condition-case err
  446.         (hack-local-variables (not find-file))
  447.       (error (message "File local-variables error: %s"
  448.               (prin1-to-string err)))))))
  449.  
  450. ;(defvar auto-mode-alist ...) now in loaddefs.el
  451. (defun set-auto-mode ()
  452.   "Select major mode appropriate for current buffer.
  453. May base decision on visited file name (see variable `auto-mode-alist') or on
  454. buffer contents (the -*- line), but does not look for the \"mode:\" local
  455. variable spec in the last page.  For that, use `hack-local-variables'."
  456.  
  457.   (save-excursion
  458.   ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
  459.   ;; Do this by calling the hack-local-variables helper to avoid redundancy.
  460.   (or (let ((enable-local-variables nil))
  461.     (hack-local-variables-prop-line nil))
  462.       ;; It's not in the -*- line, so check the auto-mode-alist, unless
  463.       ;; this buffer isn't associated with a file.
  464.       (null buffer-file-name)
  465.       (let (mode
  466.         (alist auto-mode-alist)
  467.         (name (file-name-sans-versions buffer-file-name))
  468.         (case-fold-search (eq system-type 'vax-vms)))
  469.     ;; Find first matching alist entry.
  470.     (while (and (not mode) alist)
  471.       (if (string-match (car (car alist)) name)
  472.           (setq mode (cdr (car alist))))
  473.       (setq alist (cdr alist)))
  474.     (if mode (funcall mode))))))
  475.  
  476.  
  477. (defun hack-local-variables (&optional force)
  478.   "Parse, and bind or evaluate as appropriate, any local variables
  479. for current buffer."
  480.   (hack-local-variables-prop-line force)  ;; Look for variables in the -*- line.
  481.   (hack-local-variables-last-page force)  ;; Look for "Local variables:" block in last page.
  482.   )
  483.  
  484. ;;; Local variables may be specified in the last page of the file (within 3k
  485. ;;; from the end of the file and after the last ^L) in the form
  486. ;;;
  487. ;;;   Local variables:
  488. ;;;   variable-name: variable-value
  489. ;;;   end:
  490. ;;;
  491. ;;; The lines may begin with a common prefix, like ";;;   " in the above
  492. ;;; example.  They may also have a common suffix (" */" for example).  In 
  493. ;;; this form, the local variable "mode" can be used to change the major 
  494. ;;; mode, and the local variable "eval" can be used to evaluate an arbitrary
  495. ;;; form.
  496. ;;;
  497. ;;; Local variables may also be specified in the first line of the file.
  498. ;;; Embedded in this line are a pair of "-*-" sequences.  What lies between
  499. ;;; them are variable-name/variable-value pairs, like:
  500. ;;;
  501. ;;;     -*- mode: emacs-lisp -*-
  502. ;;; or     -*- mode: postscript; version-control: never -*-
  503. ;;; or     -*- tags-file-name: "/foo/bar/TAGS" -*-
  504. ;;;
  505. ;;; The local variable "eval" is not used with this form. For hysterical
  506. ;;; reasons, the syntax "-*- modename -*-" is allowed as well.
  507. ;;;
  508.  
  509. (defun hack-local-variables-last-page (&optional force)
  510.   ;; Set local variables set in the "Local Variables:" block of the last page.
  511.   (save-excursion
  512.     (goto-char (point-max))
  513.     (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
  514.     (if (let ((case-fold-search t))
  515.       (and (search-forward "Local Variables:" nil t)
  516.            (or force (eq enable-local-variables t)
  517.            (and enable-local-variables
  518.             (save-window-excursion
  519.               (switch-to-buffer (current-buffer))
  520.               (y-or-n-p (format "Set local variables as specified at end of %s? "
  521.                         (file-name-nondirectory buffer-file-name))))))))
  522.     (let ((continue t)
  523.           prefix prefixlen suffix beg)
  524.       ;; The prefix is what comes before "local variables:" in its line.
  525.       ;; The suffix is what comes after "local variables:" in its line.
  526.       (skip-chars-forward " \t")
  527.       (or (eolp)
  528.           (setq suffix (buffer-substring (point)
  529.                          (progn (end-of-line) (point)))))
  530.       (goto-char (match-beginning 0))
  531.       (or (bolp)
  532.           (setq prefix
  533.             (buffer-substring (point)
  534.                       (progn (beginning-of-line) (point)))))
  535.       (if prefix (setq prefixlen (length prefix)
  536.                prefix (regexp-quote prefix)))
  537.       (if suffix (setq suffix (regexp-quote suffix)))
  538.       (while continue
  539.         ;; Look at next local variable spec.
  540.         (if selective-display (re-search-forward "[\n\C-m]")
  541.           (forward-line 1))
  542.         ;; Skip the prefix, if any.
  543.         (if prefix
  544.         (if (looking-at prefix)
  545.             (forward-char prefixlen)
  546.           (error "Local variables entry is missing the prefix")))
  547.         ;; Find the variable name; strip whitespace.
  548.         (skip-chars-forward " \t")
  549.         (setq beg (point))
  550.         (skip-chars-forward "^:\n")
  551.         (if (eolp) (error "Missing colon in local variables entry"))
  552.         (skip-chars-backward " \t")
  553.         (let* ((str (buffer-substring beg (point)))
  554.            (var (read str))
  555.           val)
  556.           ;; Setting variable named "end" means end of list.
  557.           (if (string-equal (downcase str) "end")
  558.           (setq continue nil)
  559.         ;; Otherwise read the variable value.
  560.         (skip-chars-forward "^:")
  561.         (forward-char 1)
  562.         (setq val (read (current-buffer)))
  563.         (skip-chars-backward "\n")
  564.         (skip-chars-forward " \t")
  565.         (or (if suffix (looking-at suffix) (eolp))
  566.             (error "Local variables entry is terminated incorrectly"))
  567.         ;; Set the variable.  "Variables" mode and eval are funny.
  568.         (cond ((eq var 'mode)
  569.                (funcall (intern (concat (downcase (symbol-name val))
  570.                         "-mode"))))
  571.               ((eq var 'eval)
  572.                (if (string= (user-login-name) "root")
  573.                (message "Ignoring `eval:' in file's local variables")
  574.              (save-excursion (eval val))))
  575.               (t (make-local-variable var)
  576.              (set var val))))))))))
  577.  
  578.  
  579. (defun hack-local-variables-prop-line (&optional force)
  580.   ;; Set local variables specified in the -*- line.
  581.   ;; Returns t if mode was set.
  582.   (save-excursion
  583.     (goto-char (point-min))
  584.     (skip-chars-forward " \t\n\r")
  585.     (let ((result '())
  586.       (end (save-excursion (end-of-line) (point)))
  587.       mode-p)
  588.       ;; Parse the -*- line into the `result' alist.
  589.       (cond ((not (search-forward "-*-" end t))
  590.          ;; doesn't have one.
  591.          nil)
  592.         ((looking-at "[ \t]*\\([^ \t\n\r:;]\\)+\\([ \t]*-\\*-\\)")
  593.          ;; Antiquated form: "-*- ModeName -*-".
  594.          (setq result
  595.            (list (cons 'mode
  596.                (intern (buffer-substring
  597.                     (match-beginning 1)
  598.                     ;; (match-end 1) doesn't do what I expect
  599.                     (match-beginning 2)))))))
  600.         (t
  601.          ;; Usual form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
  602.          ;; (last ";" is optional).
  603.          (save-excursion
  604.            (if (search-forward "-*-" end t)
  605.            (setq end (- (point) 3))
  606.          (error "-*- not terminated before end-of-line")))
  607.          (while (< (point) end)
  608.            (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
  609.            (error "malformed -*- line"))
  610.            (goto-char (match-end 0))
  611.            (let ((key (intern (downcase (buffer-substring
  612.                          (match-beginning 1)
  613.                          (match-end 1)))))
  614.              (val (save-restriction
  615.                 (narrow-to-region (point) end)
  616.                 (read (current-buffer)))))
  617.          (setq result (cons (cons key val) result))
  618.          (skip-chars-forward " \t;")))
  619.          (setq result (nreverse result))))
  620.  
  621.       ;; Mode is magic.
  622.       (let (mode)
  623.     (while (setq mode (assq 'mode result))
  624.       (setq mode-p t result (delq mode result))
  625.       (funcall (intern (concat (downcase (symbol-name (cdr mode)))
  626.                    "-mode")))))
  627.       
  628.       (if (and result
  629.            (or force (eq enable-local-variables t)
  630.            (and enable-local-variables
  631.             (save-window-excursion
  632.               (switch-to-buffer (current-buffer))
  633.               (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
  634.                         (file-name-nondirectory buffer-file-name)))))))
  635.       (while result
  636.         (let ((key (car (car result)))
  637.           (val (cdr (car result))))
  638.           ;; 'mode has already been removed from this list.
  639.           (make-local-variable key)
  640.           (set key val))
  641.         (setq result (cdr result))))
  642.       mode-p)))
  643.  
  644.  
  645. (defun set-visited-file-name (filename)
  646.   "Change name of file visited in current buffer to FILENAME.
  647. The next time the buffer is saved it will go in the newly specified file.
  648. nil or empty string as argument means make buffer not be visiting any file.
  649. Remember to delete the initial contents of the minibuffer
  650. if you wish to pass an empty string as the argument."
  651.   (interactive "FSet visited file name: ")
  652.   (if filename
  653.       (setq filename
  654.         (if (string-equal filename "")
  655.         nil
  656.           (expand-file-name filename))))
  657.   (or (equal filename buffer-file-name)
  658.       (null filename)
  659.       (progn
  660.     (lock-buffer filename)
  661.     (unlock-buffer)))
  662.   (setq buffer-file-name filename)
  663.   (if filename                ; make buffer name reflect filename.
  664.       (let ((new-name (file-name-nondirectory buffer-file-name)))
  665.     (if (string= new-name "")
  666.         (error "Empty file name"))
  667.     (if (eq system-type 'vax-vms)
  668.         (setq new-name (downcase new-name)))
  669.     (setq default-directory (file-name-directory buffer-file-name))
  670.     (let ((new-buffer (get-buffer new-name))
  671.           (current-buffer (current-buffer)))
  672.       (cond ((eq new-buffer current-buffer)
  673.                  ;; continue using current buffer name
  674.                 )
  675.         ((not (null new-buffer))
  676.                  ;; the buffer name that we want to use is taken
  677.          (let* ((buf (create-file-buffer buffer-file-name)))
  678.            (setq new-name (buffer-name buf))
  679.            (kill-buffer buf))
  680.          (rename-buffer new-name))
  681.         (t
  682.                  ;; Just rename the buffer to the new name
  683.          (rename-buffer new-name))))))
  684.   (compute-buffer-file-truename) ; insert-file-contents does this too.
  685.   (setq buffer-backed-up nil)
  686.   (clear-visited-file-modtime)
  687.   ;; write-file-hooks is normally used for things like ftp-find-file
  688.   ;; that visit things that are not local files as if they were files.
  689.   ;; Changing to visit an ordinary local file instead should flush the hook.
  690.   (kill-local-variable 'write-file-hooks)
  691.   (kill-local-variable 'write-file-data-hooks)
  692.   (kill-local-variable 'after-write-file-hooks)
  693.   (kill-local-variable 'revert-buffer-function)
  694.   ;; If auto-save was not already on, turn it on if appropriate.
  695.   (if (not buffer-auto-save-file-name)
  696.       (auto-save-mode (and buffer-file-name auto-save-default)))
  697.   (if buffer-file-name
  698.       (set-buffer-modified-p t)))
  699.  
  700. (defun write-file (filename)
  701.   "Write current buffer into file FILENAME.
  702. Makes buffer visit that file, and marks it not modified."
  703. ;;  (interactive "FWrite file: ")
  704.   (interactive
  705.    (list (if buffer-file-name
  706.          (read-file-name "Write file: "
  707.                  nil nil nil nil)
  708.        (read-file-name "Write file: "
  709.                    (cdr (assq 'default-directory
  710.                       (buffer-local-variables)))
  711.                    nil nil (buffer-name)))))
  712.   (or (null filename) (string-equal filename "")
  713.       (set-visited-file-name filename))
  714.   (set-buffer-modified-p t)
  715.   (save-buffer))
  716.  
  717. (defun backup-buffer ()
  718.   "Make a backup of the disk file visited by the current buffer, if appropriate.
  719. This is normally done before saving the buffer the first time.
  720. If the value is non-nil, it is the result of `file-modes' on the original file;
  721. this means that the caller, after saving the buffer, should change the modes
  722. of the new file to agree with the old modes."
  723.   (if (and make-backup-files
  724.        (not buffer-backed-up)
  725.        (file-exists-p buffer-file-name)
  726.        (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
  727.          '(?- ?l))
  728. ;; user should do this with after-find-file-hooks if desired
  729. ;;       (or (< (length buffer-file-name) 5)
  730. ;;           (not (string-equal "/tmp/" (substring buffer-file-name 0 5))))
  731.        )
  732.       (let ((real-file-name buffer-file-name)
  733.         backup-info backupname targets setmodes last)
  734.     ;; If specified name is a symbolic link, chase it to the target.
  735.     ;; Thus we make the backups in the directory where the real file is.
  736.     (while (let ((tem (file-symlink-p real-file-name)))
  737.          (if (equal real-file-name last)
  738.              ;; this is to prevent us from looping on pathnames
  739.              ;; like "dir1/dir2/../foo", where that is not the
  740.              ;; same as "dir1/foo" because dir2 is a link.
  741.              nil
  742.            (if tem
  743.                (setq last real-file-name
  744.                  real-file-name
  745.                  (expand-file-name tem
  746.                            (file-name-directory
  747.                         real-file-name)))
  748.              tem))))
  749.     (setq backup-info (find-backup-file-name real-file-name)
  750.           backupname (car backup-info)
  751.           targets (cdr backup-info))
  752. ;;;     (if (file-directory-p buffer-file-name)
  753. ;;;         (error "Cannot save buffer in directory %s" buffer-file-name))
  754.         (condition-case ()
  755.         (let ((delete-old-versions
  756.            ;; If have old versions to maybe delete,
  757.            ;; ask the user to confirm now, before doing anything.
  758.            ;; But don't actually delete til later.
  759.            (and targets
  760.             (or trim-versions-without-asking
  761.                 (y-or-n-p (format "Delete excess backup versions of %s? "
  762.                           real-file-name))))))
  763.           ;; Actually write the back up file.
  764.           (condition-case ()
  765.           (if (or file-precious-flag
  766. ;              (file-symlink-p buffer-file-name)
  767.               backup-by-copying
  768.               (and backup-by-copying-when-linked
  769.                    (> (file-nlinks real-file-name) 1))
  770.               (and backup-by-copying-when-mismatch
  771.                    (let ((attr (file-attributes real-file-name)))
  772.                  (or (nth 9 attr)
  773.                      (/= (nth 2 attr) (user-uid))))))
  774.               (copy-file real-file-name backupname t t)
  775. ; rename-file should delete old backup.
  776. ;            (condition-case ()
  777. ;            (delete-file backupname)
  778. ;              (file-error nil))
  779.             (rename-file real-file-name backupname t)
  780.             (setq setmodes (file-modes backupname)))
  781.         (file-error
  782.          ;; If trouble writing the backup, write it in ~.
  783.          (setq backupname (expand-file-name "~/%backup%~"))
  784.          (message "Cannot write backup file; backing up in ~/%%backup%%~")
  785.          (sleep-for 1)
  786.          (copy-file real-file-name backupname t t)))
  787.           (setq buffer-backed-up t)
  788.           ;; Now delete the old versions, if desired.
  789.           (if delete-old-versions
  790.           (while targets
  791.             (condition-case ()
  792.             (delete-file (car targets))
  793.               (file-error nil))
  794.             (setq targets (cdr targets))))
  795.           setmodes)
  796.     (file-error nil)))))
  797.  
  798. (defun file-name-sans-versions (name)
  799.   "Return FILENAME sans backup versions or strings.
  800. This is a separate procedure so your site-init or startup file can
  801. redefine it."
  802.   (substring name 0
  803.              (if (eq system-type 'vax-vms)
  804.          ;; VMS version number is (a) semicolon, optional
  805.          ;; sign, zero or more digits or (b) period, option
  806.          ;; sign, zero or more digits, provided this is the
  807.          ;; second period encountered outside of the
  808.          ;; device/directory part of the file name.
  809.                  (or (string-match ";[---+]?[0-9]*\\'" name)
  810.                      (if (string-match "\\.[^]>:]*\\(\\.[---+]?[0-9]*\\)\\'"
  811.                                        name)
  812.                          (match-beginning 1))
  813.                      (length name))
  814.                (or (string-match "\\.~[0-9]+~\\'" name)
  815.                    (string-match "~\\'" name)
  816.                    (length name)))))
  817.  
  818. (defun make-backup-file-name (file)
  819.   "Create the non-numeric backup file name for FILE.
  820. This is a separate function so you can redefine it for customization."
  821.   (concat file "~"))
  822.  
  823. (defun backup-file-name-p (file)
  824.   "Return non-nil if FILE is a backup file name (numeric or not).
  825. This is a separate function so you can redefine it for customization.
  826. You may need to redefine file-name-sans-versions as well."
  827.   (string-match "~$" file))
  828.  
  829. ;; I believe there is no need to alter this behavior for VMS;
  830. ;; since backup files are not made on VMS, it should not get called.
  831. (defun find-backup-file-name (fn)
  832.   "Find a file name for a backup file, and suggestions for deletions.
  833. Value is a list whose car is the name for the backup file
  834.  and whose cdr is a list of old versions to consider deleting now."
  835.   (if (eq version-control 'never)
  836.       (list (make-backup-file-name fn))
  837.     (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
  838.        (bv-length (length base-versions)) ; used by backup-extract-version
  839.        (possibilities (file-name-all-completions
  840.                base-versions
  841.                (file-name-directory fn)))
  842.        (versions (sort (mapcar 'backup-extract-version possibilities)
  843.                '<))
  844.        (high-water-mark (apply 'max (cons 0 versions)))
  845.        (deserve-versions-p
  846.         (or version-control
  847.         (> high-water-mark 0)))
  848.        (number-to-delete (- (length versions)
  849.                 kept-old-versions kept-new-versions -1)))
  850.       (if (not deserve-versions-p)
  851.       (list (make-backup-file-name fn))
  852.     (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
  853.           (if (> number-to-delete 0)
  854.           (mapcar (function (lambda (n)
  855.                       (concat fn ".~" (int-to-string n) "~")))
  856.               (let ((v (nthcdr kept-old-versions versions)))
  857.                 (rplacd (nthcdr (1- number-to-delete) v) ())
  858.                 v))))))))
  859.  
  860. (defun backup-extract-version (fn)
  861.   ;; bv-length is bound in find-backup-file-name
  862.   (if (and (string-match "[0-9]+~$" fn bv-length)
  863.        (= (match-beginning 0) bv-length))
  864.       (string-to-int (substring fn bv-length -1))
  865.       0))
  866.  
  867. (defun file-nlinks (filename)
  868.   "Return number of names file FILENAME has."
  869.   (car (cdr (file-attributes filename))))
  870.  
  871. (defun file-relative-name-1 (directory)
  872.   (cond ((string= directory "/")
  873.      filename)
  874.     ((string-match (concat "^" (regexp-quote directory))
  875.                filename)
  876.      (substring filename (match-end 0)))
  877.     (t
  878.      (file-relative-name-1
  879.       (file-name-directory (substring directory 0 -1))))))
  880.  
  881. (defun file-relative-name (filename &optional directory)
  882.   "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
  883.   (setq filename (expand-file-name filename)
  884.     directory (file-name-as-directory (if directory
  885.                           (expand-file-name directory)
  886.                           default-directory)))
  887.   (file-relative-name-1 directory))
  888.  
  889. (defun save-buffer (&optional args)
  890.   "Save current buffer in visited file if modified.  Versions described below.
  891.  
  892. By default, makes the previous version into a backup file
  893.  if previously requested or if this is the first save.
  894. With 1 or 3 \\[universal-argument]'s, marks this version
  895.  to become a backup when the next save is done.
  896. With 2 or 3 \\[universal-argument]'s,
  897.  unconditionally makes the previous version into a backup file.
  898. With argument of 0, never makes the previous version into a backup file.
  899.  
  900. If a file's name is FOO, the names of its numbered backup versions are
  901.  FOO.~i~ for various integers i.  A non-numbered backup file is called FOO~.
  902. Numeric backups (rather than FOO~) will be made if value of
  903.  `version-control' is not the atom `never' and either there are already
  904.  numeric versions of the file being backed up, or `version-control' is
  905.  non-nil.
  906. We don't want excessive versions piling up, so there are variables
  907.  `kept-old-versions', which tells Emacs how many oldest versions to keep,
  908.  and `kept-new-versions', which tells how many newest versions to keep.
  909.  Defaults are 2 old versions and 2 new.
  910. `dired-kept-versions' controls dired's clean-directory (.) command.
  911. If `trim-versions-without-asking' is nil, system will query user
  912.  before trimming versions.  Otherwise it does it silently."
  913.   (interactive "p")
  914.   (let ((modp (buffer-modified-p))
  915.     (large (> (buffer-size) 50000))
  916.     (make-backup-files (and make-backup-files (not (eq args 0)))))
  917.     (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
  918.     (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
  919.     (basic-save-buffer)
  920.     (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
  921.  
  922. (defun delete-auto-save-file-if-necessary (&optional force)
  923.   "Delete the auto-save filename for the current buffer (if it has one)
  924. if variable `delete-auto-save-files' is non-nil.
  925. Normally delete only if the file was written by this Emacs
  926. since the last real save, but optional arg FORCE non-nil means delete anyway."
  927.   (and buffer-auto-save-file-name delete-auto-save-files
  928.        (not (string= buffer-file-name buffer-auto-save-file-name))
  929.        (or force (recent-auto-save-p))
  930.        (progn
  931.      (condition-case ()
  932.          (delete-file buffer-auto-save-file-name)
  933.        (file-error nil))
  934.      (set-buffer-auto-saved))))
  935.  
  936. (defun basic-write-file-data (realname)
  937.   ;; call the hooks until the bytes are put
  938.   ;; call write-region as a last resort
  939.   (let ((region-written nil)
  940.     (hooks write-file-data-hooks))
  941.     (while (and hooks (not region-written))
  942.       (setq region-written (funcall (car hooks) realname)
  943.         hooks (cdr hooks)))
  944.     (if (not region-written)
  945.     (write-region (point-min) (point-max) realname nil t))))
  946.  
  947. (defun basic-save-buffer ()
  948.   "Save the current buffer in its visited file, if it has been modified."
  949.   (interactive)
  950.   (if (buffer-modified-p)
  951.       (let ((recent-save (recent-auto-save-p))
  952.         setmodes tempsetmodes)
  953.     ;; On VMS, rename file and buffer to get rid of version number.
  954.     (if (and (eq system-type 'vax-vms)
  955.          (not (string= buffer-file-name
  956.                    (file-name-sans-versions buffer-file-name))))
  957.         (let (buffer-new-name)
  958.           ;; Strip VMS version number before save.
  959.           (setq buffer-file-name
  960.             (file-name-sans-versions buffer-file-name))
  961.           ;; Construct a (unique) buffer name to correspond.
  962.           (let ((buf (create-file-buffer (downcase buffer-file-name))))
  963.         (setq buffer-new-name (buffer-name buf))
  964.         (kill-buffer buf))
  965.           (rename-buffer buffer-new-name)))
  966.     ;; If buffer has no file name, ask user for one.
  967.     (or buffer-file-name
  968.         (progn
  969.           (setq buffer-file-name
  970.             (expand-file-name (read-file-name "File to save in: ") nil)
  971.             default-directory (file-name-directory buffer-file-name))
  972.           (auto-save-mode auto-save-default)))
  973.     (or (verify-visited-file-modtime (current-buffer))
  974.         (not (file-exists-p buffer-file-name))
  975.         (yes-or-no-p
  976.          (format "%s has changed since visited or saved.  Save anyway? "
  977.              (file-name-nondirectory buffer-file-name)))
  978.         (error "Save not confirmed"))
  979.     (save-restriction
  980.       (widen)
  981.       (and (> (point-max) 1)
  982.            (/= (char-after (1- (point-max))) ?\n)
  983.            (or (eq require-final-newline t)
  984.            (and require-final-newline
  985.             (y-or-n-p
  986.              (format "Buffer %s does not end in newline.  Add one? "
  987.                  (buffer-name)))))
  988.            (save-excursion
  989.          (goto-char (point-max))
  990.          (insert ?\n)))
  991.       (let ((done nil))
  992.         ;;
  993.         ;; Run the write-file-hooks until one returns non-null.
  994.         ;; Bind after-write-file-hooks to nil while running the
  995.         ;; write-file-hooks so that if this function is called
  996.         ;; recursively (from inside a write-file-hook) the after-
  997.         ;; hooks will only get run once (from the outermost call.)
  998.         ;;
  999.         (let ((hooks (append write-contents-hooks write-file-hooks))
  1000.           (after-write-file-hooks nil)
  1001.           (write-contents-hooks nil)
  1002.           (write-file-hooks nil))
  1003.           (while (and hooks
  1004.               (not (setq done (funcall (car hooks)))))
  1005.         (setq hooks (cdr hooks))))
  1006.         ;;
  1007.         ;; If a hook returned t, file is already "written".
  1008.         (cond ((not done)
  1009.            (if (not (file-writable-p buffer-file-name))
  1010.                (let ((dir (file-name-directory buffer-file-name)))
  1011.              (if (not (file-directory-p dir))
  1012.                  (error "%s is not a directory" dir)
  1013.                (if (not (file-exists-p buffer-file-name))
  1014.                    (error "Directory %s write-protected" dir)
  1015.                  (if (yes-or-no-p
  1016.                   (format "File %s is write-protected; try to save anyway? "
  1017.                       (file-name-nondirectory
  1018.                        buffer-file-name)))
  1019.                  (setq tempsetmodes t)
  1020.                    (error
  1021.        "Attempt to save to a file which you aren't allowed to write"))))))
  1022.            (or buffer-backed-up
  1023.                (setq setmodes (backup-buffer)))
  1024.            (if file-precious-flag
  1025.                ;; If file is precious, rename it away before
  1026.                ;; overwriting it.
  1027.                (let ((rename t)
  1028.                  realname tempname temp)
  1029.              ;; Chase symlinks; rename the ultimate actual file.
  1030.              (setq realname buffer-file-name)
  1031.              (while (setq temp (file-symlink-p realname))
  1032.                (setq realname temp))
  1033.              (setq tempname (concat realname "#"))
  1034.              (condition-case ()
  1035.                  (progn (rename-file realname tempname t)
  1036.                     (setq setmodes (file-modes tempname)))
  1037.                (file-error (setq rename nil tempname nil)))
  1038.              (if (file-directory-p realname)
  1039.                  (error "%s is a directory" realname))
  1040.              (unwind-protect
  1041.                  (progn (clear-visited-file-modtime)
  1042.                     (basic-write-file-data realname)
  1043.                     (setq rename nil))
  1044.                ;; If rename is still t, writing failed.
  1045.                ;; So rename the old file back to original name,
  1046.                (if rename
  1047.                    (progn
  1048.                  (rename-file tempname realname t)
  1049.                  (clear-visited-file-modtime))
  1050.                  ;; Otherwise we don't need the original file,
  1051.                  ;; so flush it, if we still have it.
  1052.                  ;; If rename failed due to name length restriction
  1053.                  ;; then TEMPNAME is now nil.
  1054.                  (if tempname
  1055.                  (condition-case ()
  1056.                      (delete-file tempname)
  1057.                    (error nil))))))
  1058.              ;; If file not writable, see if we can make it writable
  1059.              ;; temporarily while we write it.
  1060.              ;; But no need to do so if we have just backed it up
  1061.              ;; (setmodes is set) because that says we're superseding.
  1062.              (cond ((and tempsetmodes (not setmodes))
  1063.                 ;; Change the mode back, after writing.
  1064.                 (setq setmodes (file-modes buffer-file-name))
  1065.                 (set-file-modes buffer-file-name 511)))
  1066.              (basic-write-file-data buffer-file-name)))))
  1067.       (if setmodes
  1068.           (condition-case ()
  1069.            (set-file-modes buffer-file-name setmodes)
  1070.         (error nil))))
  1071.     ;; If the auto-save file was recent before this command,
  1072.     ;; delete it now.
  1073.     (delete-auto-save-file-if-necessary recent-save)
  1074.     ;; Now we're done with everything; run the after-write-file-hooks.
  1075.     ;; ## warning: FSF calls this variable `after-save-hooks'.
  1076.     (run-hooks 'after-write-file-hooks))
  1077.     (message "(No changes need to be saved)")))
  1078.  
  1079. (defun save-some-buffers (&optional arg exiting)
  1080.   "Save some modified file-visiting buffers.  Asks user about each one.
  1081. Optional argument (the prefix) non-nil means save all with no questions.
  1082. Optional second argument EXITING means ask about certain non-file buffers
  1083.  as well as about file buffers."
  1084.   (interactive "P")
  1085.   (let (considered (list (buffer-list)))
  1086.     (while list
  1087.       (let ((buffer (car list)))
  1088.     (and (buffer-modified-p buffer)
  1089.          (not (cdr (assoc 'save-buffers-skip
  1090.                   (buffer-local-variables buffer))))
  1091.          (save-excursion
  1092.            (set-buffer buffer)
  1093.            (and
  1094.         (or buffer-file-name
  1095.             (and exiting buffer-offer-save (> (buffer-size) 0)))
  1096.         (setq considered t)
  1097.         (or arg
  1098.             (y-or-n-p (if buffer-file-name
  1099.                   (format "Save file %s? "
  1100.                       buffer-file-name)
  1101.                 (format "Save buffer %s? " (buffer-name)))))
  1102.         (condition-case ()
  1103.             (save-buffer)
  1104.           (error nil))))))
  1105.       (setq list (cdr list)))
  1106.     (and save-abbrevs abbrevs-changed
  1107.      (progn
  1108.        (setq considered t)
  1109.        (if (or arg
  1110.            (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
  1111.            (write-abbrev-file nil))
  1112.        ;; Don't keep bothering user if he says no.
  1113.        (setq abbrevs-changed nil)))
  1114.     (if considered
  1115.     (message "")
  1116.     (message "(No files need saving)"))))
  1117.  
  1118. (defun not-modified (&optional arg)
  1119.   "Mark current buffer as unmodified, not needing to be saved.
  1120. With prefix arg, mark buffer as modified, so \\[save-buffer] will save."
  1121.   (interactive "P")
  1122.   (message (if arg "Modification-flag set"
  1123.            "Modification-flag cleared"))
  1124.   (set-buffer-modified-p arg))
  1125.  
  1126. (defun toggle-read-only (&optional arg)
  1127.   "Change whether this buffer is visiting its file read-only.
  1128. With arg, set read-only iff arg is positive."
  1129.   (interactive "P")
  1130.   (setq buffer-read-only
  1131.     (if (null arg)
  1132.             (not buffer-read-only)
  1133.             (> (prefix-numeric-value arg) 0)))
  1134.   ;; Force mode-line redisplay
  1135.   (set-buffer-modified-p (buffer-modified-p)))
  1136.  
  1137. (defun insert-file (filename)
  1138.   "Insert contents of file FILENAME into buffer after point.
  1139. Set mark after the inserted text.
  1140.  
  1141. This function is meant for the user to run interactively.
  1142. Don't call it from programs!  Use `insert-file-contents' instead.
  1143. \(Its calling sequence is different; see its documentation)."
  1144.   (interactive "fInsert file: ")
  1145.   (let ((tem (insert-file-contents filename)))
  1146.     (push-mark (+ (point) (car (cdr tem))))))
  1147.  
  1148. (defun append-to-file (start end filename)
  1149.   "Append the contents of the region to the end of file FILENAME.
  1150. When called from a function, expects three arguments,
  1151. START, END and FILENAME.  START and END are buffer positions
  1152. saying what text to write."
  1153.   (interactive "r\nFAppend to file: ")
  1154.   (write-region start end filename t))
  1155.  
  1156. (defun file-newest-backup (filename)
  1157.   "Return most recent backup file for FILENAME or nil if no backups exist."
  1158.   (let* ((filename (expand-file-name filename))
  1159.      (file (file-name-nondirectory filename))
  1160.      (dir  (file-name-directory    filename))
  1161.      (comp (file-name-all-completions file dir))
  1162.      newest)
  1163.     (while comp
  1164.       (setq file (concat dir (car comp))
  1165.         comp (cdr comp))
  1166.       (if (and (backup-file-name-p file)
  1167.            (or (null newest) (file-newer-than-file-p file newest)))
  1168.       (setq newest file)))
  1169.     newest))
  1170.  
  1171. (defun rename-uniquely ()
  1172.   "Rename current buffer to a similar name not already taken.
  1173. This function is useful for creating multiple shell process buffers
  1174. or multiple mail buffers, etc."
  1175.   (interactive)
  1176.   (let* ((new-buf (generate-new-buffer (buffer-name)))
  1177.      (name (buffer-name new-buf)))
  1178.     (kill-buffer new-buf)
  1179.     (rename-buffer name)
  1180.     (set-buffer-modified-p (buffer-modified-p)))) ; force mode line update
  1181.  
  1182. (defun make-directory-path (path)
  1183.   "Create all the directories along path that don't exist yet."
  1184.   (interactive "Fdirectory path to create: ")
  1185.   (let ((path (directory-file-name (expand-file-name path)))
  1186.     create-list)
  1187.     (while (not (file-exists-p path))
  1188.       (setq create-list (cons path create-list)        
  1189.         path (directory-file-name (file-name-directory path))))
  1190.     (while create-list
  1191.       (make-directory (car create-list))
  1192.       (setq create-list (cdr create-list)))))
  1193.  
  1194.  
  1195. (put 'revert-buffer-function 'permanent-local t)
  1196. (defvar revert-buffer-function nil
  1197.   "Function to use to revert this buffer, or nil to do the default.")
  1198.  
  1199. (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
  1200. (defvar revert-buffer-insert-file-contents-function nil
  1201.   "Function to use to insert contents when reverting this buffer.
  1202. Gets two args, first the nominal file name to use,
  1203. and second, t if reading the auto-save file.")
  1204.  
  1205. (defun revert-buffer (&optional check-auto noconfirm)
  1206.   "Replace the buffer text with the text of the visited file on disk.
  1207. This undoes all changes since the file was visited or saved.
  1208. With a prefix argument, offer to revert from latest auto-save file, if
  1209. that is more recent than the visited file.
  1210. When called from lisp, this is the first argument, CHECK-AUTO; it is optional.
  1211. Optional second argument NOCONFIRM means don't ask for confirmation at all.
  1212.  
  1213. If the value of `revert-buffer-function' is non-nil, it is called to
  1214. do the work."
  1215.   (interactive "P")
  1216.   (if revert-buffer-function
  1217.       (funcall revert-buffer-function (not check-auto) noconfirm)
  1218.     (let* ((opoint (point))
  1219.        (auto-save-p (and check-auto (recent-auto-save-p)
  1220.                  buffer-auto-save-file-name
  1221.                  (file-readable-p buffer-auto-save-file-name)
  1222.                  (y-or-n-p
  1223.    "Buffer has been auto-saved recently.  Revert from auto-save file? ")))
  1224.        (file-name (if auto-save-p
  1225.               buffer-auto-save-file-name
  1226.             buffer-file-name)))
  1227.       (cond ((null file-name)
  1228.          (error "Buffer does not seem to be associated with any file"))
  1229.         ((or noconfirm
  1230.          (yes-or-no-p (format "Revert buffer from file %s? "
  1231.                       file-name)))
  1232.          ;; If file was backed up but has changed since,
  1233.          ;; we shd make another backup.
  1234.          (and (not auto-save-p)
  1235.           (not (verify-visited-file-modtime (current-buffer)))
  1236.           (setq buffer-backed-up nil))
  1237.          ;; Get rid of all undo records for this buffer.
  1238.          (or (eq buffer-undo-list t)
  1239.          (setq buffer-undo-list nil))
  1240.          (let ((buffer-read-only nil)
  1241.            ;; Don't make undo records for the reversion.
  1242.            (buffer-undo-list t))
  1243.            (if revert-buffer-insert-file-contents-function
  1244.            (funcall revert-buffer-insert-file-contents-function
  1245.                 file-name auto-save-p)
  1246.          (if (not (file-exists-p file-name))
  1247.              (error "File %s no longer exists!" file-name))
  1248.          ;; Bind buffer-file-name to nil
  1249.          ;; so that we don't try to lock the file.
  1250.          (let ((buffer-file-name nil))
  1251.            (or auto-save-p
  1252.                (unlock-buffer))
  1253.            (erase-buffer))
  1254.          (insert-file-contents file-name (not auto-save-p))))
  1255.          (goto-char (min opoint (point-max)))
  1256.          (after-find-file nil)
  1257.          t)))))
  1258.  
  1259. (defun recover-file (file)
  1260.   "Visit file FILE, but get contents from its last auto-save file."
  1261.   (interactive
  1262.    (let ((prompt-file buffer-file-name)
  1263.      (file-name nil)
  1264.      (file-dir nil))
  1265.      (and prompt-file
  1266.       (setq file-name (file-name-nondirectory prompt-file)
  1267.         file-dir (file-name-directory prompt-file)))
  1268.      (list (read-file-name "Recover file: "
  1269.                    file-dir nil nil file-name))))
  1270.   (setq file (expand-file-name file))
  1271.   (if (auto-save-file-name-p file) (error "%s is an auto-save file" file))
  1272.   (let ((file-name (let ((buffer-file-name file))
  1273.              (make-auto-save-file-name))))
  1274.     (cond ((not (file-newer-than-file-p file-name file))
  1275.        (error "Auto-save file %s not current" file-name))
  1276.       ((save-window-excursion
  1277.          (if (not (eq system-type 'vax-vms))
  1278.          (with-output-to-temp-buffer "*Directory*"
  1279.            (buffer-disable-undo standard-output)
  1280.            (call-process "ls" nil standard-output nil
  1281.                  (if (file-symlink-p file) "-lL" "-l")
  1282.                  file file-name)))
  1283.          (yes-or-no-p (format "Recover auto save file %s? " file-name)))
  1284.        (switch-to-buffer (find-file-noselect file t))
  1285.        (let ((buffer-read-only nil))
  1286.          (erase-buffer)
  1287.          (insert-file-contents file-name nil))
  1288.        (after-find-file nil))
  1289.       (t (error "Recover-file cancelled.")))))
  1290.  
  1291. (defun kill-some-buffers ()
  1292.   "For each buffer, ask whether to kill it."
  1293.   (interactive)
  1294.   (let ((list (buffer-list)))
  1295.     (while list
  1296.       (let* ((buffer (car list))
  1297.          (name (buffer-name buffer)))
  1298.     (and (not (string-equal name ""))
  1299.          (/= (aref name 0) ? )
  1300.          (yes-or-no-p
  1301.           (format "Buffer %s %s.  Kill? "
  1302.               name
  1303.               (if (buffer-modified-p buffer)
  1304.               "HAS BEEN EDITED" "is unmodified")))
  1305.          (kill-buffer buffer)))
  1306.       (setq list (cdr list)))))
  1307.  
  1308. (defun auto-save-mode (arg)
  1309.   "Toggle auto-saving of contents of current buffer.
  1310. With arg, turn auto-saving on if arg is positive, else off."
  1311.   (interactive "P")
  1312.   (setq buffer-auto-save-file-name
  1313.         (and (if (null arg)
  1314.          (not buffer-auto-save-file-name)
  1315.            (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
  1316.          (if (and buffer-file-name auto-save-visited-file-name
  1317.               (not buffer-read-only))
  1318.          buffer-file-name
  1319.            (make-auto-save-file-name))))
  1320.   (if (interactive-p)
  1321.       (message "Auto-save %s (in this buffer)"
  1322.            (if buffer-auto-save-file-name "on" "off")))
  1323.   buffer-auto-save-file-name)
  1324.  
  1325. (defun rename-auto-save-file ()
  1326.   "Adjust current buffer's auto save file name for current conditions.
  1327. Also rename any existing auto save file, if it was made in this session."
  1328.   (let ((osave buffer-auto-save-file-name))
  1329.     (setq buffer-auto-save-file-name
  1330.       (make-auto-save-file-name))
  1331.     (if (and osave buffer-auto-save-file-name
  1332.          (not (string= buffer-auto-save-file-name buffer-file-name))
  1333.          (not (string= buffer-auto-save-file-name osave))
  1334.          (file-exists-p osave)
  1335.          (recent-auto-save-p))
  1336.     (rename-file osave buffer-auto-save-file-name t))))
  1337.  
  1338. (defun make-auto-save-file-name ()
  1339.   "Return file name to use for auto-saves of current buffer.
  1340. Does not consider auto-save-visited-file-name; that is checked
  1341. before calling this function.
  1342. You can redefine this for customization.
  1343. See also auto-save-file-name-p."
  1344.   (if buffer-file-name
  1345.       (concat (file-name-directory buffer-file-name)
  1346.           "#"
  1347.           (file-name-nondirectory buffer-file-name)
  1348.           "#")
  1349.     ;; For non-file bfr, use bfr name and Emacs pid.
  1350.     (expand-file-name (format "#%s#%s#" (buffer-name) (make-temp-name "")))))
  1351.  
  1352. (defun auto-save-file-name-p (filename)
  1353.   "Return non-nil if FILENAME can be yielded by make-auto-save-file-name.
  1354. FILENAME should lack slashes.
  1355. You can redefine this for customization."
  1356.   (string-match "^#.*#$" filename))
  1357.  
  1358. (defconst list-directory-brief-switches
  1359.   (if (eq system-type 'vax-vms) "" "-CF")
  1360.   "*Switches for list-directory to pass to `ls' for brief listing,")
  1361.  
  1362. (defconst list-directory-verbose-switches
  1363.   (if (eq system-type 'vax-vms)
  1364.       "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
  1365.     "-l")
  1366.   "*Switches for list-directory to pass to `ls' for verbose listing,")
  1367.  
  1368. (defun list-directory (dirname &optional verbose)
  1369.   "Display a list of files in or matching DIRNAME, a la `ls'.
  1370. DIRNAME is globbed by the shell if necessary.
  1371. Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
  1372. Actions controlled by variables list-directory-brief-switches
  1373.  and list-directory-verbose-switches."
  1374.   (interactive (let ((pfx current-prefix-arg))
  1375.          (list (read-file-name (if pfx "List directory (verbose): "
  1376.                      "List directory (brief): ")
  1377.                        nil default-directory nil)
  1378.                pfx)))
  1379.   (let ((switches (if verbose list-directory-verbose-switches
  1380.             list-directory-brief-switches)))
  1381.     (or dirname (setq dirname default-directory))
  1382.     (setq dirname (expand-file-name dirname))
  1383.     (with-output-to-temp-buffer "*Directory*"
  1384.       (buffer-disable-undo standard-output)
  1385.       (princ "Directory ")
  1386.       (princ dirname)
  1387.       (terpri)
  1388.       (if (eq system-type 'vax-vms)
  1389.       (vms-read-directory dirname switches standard-output)
  1390.     (if (file-directory-p dirname)
  1391.         (save-excursion
  1392.           (set-buffer "*Directory*")
  1393.           (call-process "ls" nil standard-output nil switches
  1394.                 (setq default-directory
  1395.                   (file-name-as-directory dirname))))
  1396.       (let ((default-directory (file-name-directory dirname)))
  1397.         (if (file-exists-p default-directory)
  1398.         (call-process shell-file-name nil standard-output nil
  1399.                   "-c" (concat "exec ls "
  1400.                        switches " "
  1401.                        (file-name-nondirectory dirname)))
  1402.           (princ "No such directory: ")
  1403.           (princ dirname)
  1404.           (terpri))))))))
  1405.  
  1406. (defun save-buffers-kill-emacs (&optional arg)
  1407.   "Offer to save each buffer, then kill this Emacs process.
  1408. With prefix arg, silently save all file-visiting buffers, then kill."
  1409.   (interactive "P")
  1410.   (save-some-buffers arg t)
  1411.   (and (or (not (memq t (mapcar (function
  1412.                   (lambda (buf) (and (buffer-file-name buf)
  1413.                              (buffer-modified-p buf))))
  1414.                 (buffer-list))))
  1415.        (yes-or-no-p "Modified buffers exist; exit anyway? "))
  1416.        (or (not (fboundp 'process-list))
  1417.        ;; process-list is not defined on VMS.
  1418.        (let ((processes (process-list))
  1419.          active)
  1420.          (while processes
  1421.            (and (memq (process-status (car processes)) '(run stop open))
  1422.             (let ((val (process-kill-without-query (car processes))))
  1423.               (process-kill-without-query (car processes) val)
  1424.               val)
  1425.             (setq active t))
  1426.            (setq processes (cdr processes)))
  1427.          (or (not active)
  1428.          (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
  1429.        (kill-emacs)))
  1430.