home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.006 / xemacs-1 / lib / xemacs-19.13 / lisp / prim / files.el < prev    next >
Encoding:
Text File  |  1995-08-31  |  98.5 KB  |  2,511 lines

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