Merged from emacs@sv.gnu.org
[bpt/emacs.git] / lisp / subr.el
index 01288b4..ad3e732 100644 (file)
@@ -1,7 +1,7 @@
 ;;; subr.el --- basic lisp subroutines for Emacs
 
 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
-;;   2004, 2005 Free Software Foundation, Inc.
+;;   2004, 2005, 2006 Free Software Foundation, Inc.
 
 ;; Maintainer: FSF
 ;; Keywords: internal
@@ -37,24 +37,28 @@ Each element of this list holds the arguments to one call to `defcustom'.")
        (cons arguments custom-declare-variable-list)))
 
 \f
-;;;; Lisp language features.
+;;;; Basic Lisp macros.
 
 (defalias 'not 'null)
 
 (defmacro noreturn (form)
-  "Evaluates FORM, with the expectation that the evaluation will signal an error
-instead of returning to its caller.  If FORM does return, an error is
-signaled."
+  "Evaluate FORM, expecting it not to return.
+If FORM does return, signal an error."
   `(prog1 ,form
      (error "Form marked with `noreturn' did return")))
 
 (defmacro 1value (form)
-  "Evaluates FORM, with the expectation that the same value will be returned
-from all evaluations of FORM.  This is the global do-nothing
-version of `1value'.  There is also `testcover-1value' that
-complains if FORM ever does return differing values."
+  "Evaluate FORM, expecting a constant return value.
+This is the global do-nothing version.  There is also `testcover-1value'
+that complains if FORM ever does return differing values."
   form)
 
+(defmacro def-edebug-spec (symbol spec)
+  "Set the `edebug-form-spec' property of SYMBOL according to SPEC.
+Both SYMBOL and SPEC are unevaluated. The SPEC can be 0, t, a symbol
+\(naming a function), or a list."
+  `(put (quote ,symbol) 'edebug-form-spec (quote ,spec)))
+
 (defmacro lambda (&rest cdr)
   "Return a lambda expression.
 A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
@@ -104,6 +108,9 @@ change the list."
   (declare (indent 1) (debug t))
   (cons 'if (cons cond (cons nil body))))
 
+(defvar --dolist-tail-- nil
+  "Temporary variable used in `dolist' expansion.")
+
 (defmacro dolist (spec &rest body)
   "Loop over a list.
 Evaluate BODY with VAR bound to each car from LIST, in turn.
@@ -111,16 +118,22 @@ Then evaluate RESULT to get return value, default nil.
 
 \(fn (VAR LIST [RESULT]) BODY...)"
   (declare (indent 1) (debug ((symbolp form &optional form) body)))
-  (let ((temp (make-symbol "--dolist-temp--")))
+  ;; It would be cleaner to create an uninterned symbol,
+  ;; but that uses a lot more space when many functions in many files
+  ;; use dolist.
+  (let ((temp '--dolist-tail--))
     `(let ((,temp ,(nth 1 spec))
           ,(car spec))
        (while ,temp
         (setq ,(car spec) (car ,temp))
-        (setq ,temp (cdr ,temp))
-        ,@body)
+        ,@body
+        (setq ,temp (cdr ,temp)))
        ,@(if (cdr (cdr spec))
             `((setq ,(car spec) nil) ,@(cdr (cdr spec)))))))
 
+(defvar --dotimes-limit-- nil
+  "Temporary variable used in `dotimes' expansion.")
+
 (defmacro dotimes (spec &rest body)
   "Loop a certain number of times.
 Evaluate BODY with VAR bound to successive integers running from 0,
@@ -129,7 +142,10 @@ the return value (nil if RESULT is omitted).
 
 \(fn (VAR COUNT [RESULT]) BODY...)"
   (declare (indent 1) (debug dolist))
-  (let ((temp (make-symbol "--dotimes-temp--"))
+  ;; It would be cleaner to create an uninterned symbol,
+  ;; but that uses a lot more space when many functions in many files
+  ;; use dotimes.
+  (let ((temp '--dotimes-limit--)
        (start 0)
        (end (nth 1 spec)))
     `(let ((,temp ,end)
@@ -144,6 +160,47 @@ the return value (nil if RESULT is omitted).
 Treated as a declaration when used at the right place in a
 `defmacro' form.  \(See Info anchor `(elisp)Definition of declare'.)"
   nil)
+\f
+;;;; Basic Lisp functions.
+
+(defun ignore (&rest ignore)
+  "Do nothing and return nil.
+This function accepts any number of arguments, but ignores them."
+  (interactive)
+  nil)
+
+(defun error (&rest args)
+  "Signal an error, making error message by passing all args to `format'.
+In Emacs, the convention is that error messages start with a capital
+letter but *do not* end with a period.  Please follow this convention
+for the sake of consistency."
+  (while t
+    (signal 'error (list (apply 'format args)))))
+
+;; We put this here instead of in frame.el so that it's defined even on
+;; systems where frame.el isn't loaded.
+(defun frame-configuration-p (object)
+  "Return non-nil if OBJECT seems to be a frame configuration.
+Any list whose car is `frame-configuration' is assumed to be a frame
+configuration."
+  (and (consp object)
+       (eq (car object) 'frame-configuration)))
+
+(defun functionp (object)
+  "Non-nil if OBJECT is any kind of function or a special form.
+Also non-nil if OBJECT is a symbol and its function definition is
+\(recursively) a function or special form.  This does not include
+macros."
+  (or (and (symbolp object) (fboundp object)
+          (condition-case nil
+              (setq object (indirect-function object))
+            (error nil))
+          (eq (car-safe object) 'autoload)
+          (not (car-safe (cdr-safe (cdr-safe (cdr-safe (cdr-safe object)))))))
+      (subrp object) (byte-code-function-p object)
+      (eq (car-safe object) 'lambda)))
+\f
+;;;; List functions.
 
 (defsubst caar (x)
   "Return the car of the car of X."
@@ -240,23 +297,6 @@ of course, also replace TO with a slightly larger value
                 next (+ from (* n inc)))))
       (nreverse seq))))
 
-(defun remove (elt seq)
-  "Return a copy of SEQ with all occurrences of ELT removed.
-SEQ must be a list, vector, or string.  The comparison is done with `equal'."
-  (if (nlistp seq)
-      ;; If SEQ isn't a list, there's no need to copy SEQ because
-      ;; `delete' will return a new object.
-      (delete elt seq)
-    (delete elt (copy-sequence seq))))
-
-(defun remq (elt list)
-  "Return LIST with all occurrences of ELT removed.
-The comparison is done with `eq'.  Contrary to `delq', this does not use
-side-effects, and the argument LIST is not modified."
-  (if (memq elt list)
-      (delq elt (copy-sequence list))
-    list))
-
 (defun copy-tree (tree &optional vecp)
   "Make a copy of TREE.
 If TREE is a cons cell, this recursively copies both its car and its cdr.
@@ -277,6 +317,8 @@ argument VECP, this copies vectors as well as conses."
            (aset tree i (copy-tree (aref tree i) vecp)))
          tree)
       tree)))
+\f
+;;;; Various list-search functions.
 
 (defun assoc-default (key alist &optional test default)
   "Find object KEY in a pseudo-alist ALIST.
@@ -321,15 +363,67 @@ Non-strings in LIST are ignored."
     (setq list (cdr list)))
   list)
 
+(defun assq-delete-all (key alist)
+  "Delete from ALIST all elements whose car is `eq' to KEY.
+Return the modified alist.
+Elements of ALIST that are not conses are ignored."
+  (while (and (consp (car alist))
+             (eq (car (car alist)) key))
+    (setq alist (cdr alist)))
+  (let ((tail alist) tail-cdr)
+    (while (setq tail-cdr (cdr tail))
+      (if (and (consp (car tail-cdr))
+              (eq (car (car tail-cdr)) key))
+         (setcdr tail (cdr tail-cdr))
+       (setq tail tail-cdr))))
+  alist)
+
+(defun rassq-delete-all (value alist)
+  "Delete from ALIST all elements whose cdr is `eq' to VALUE.
+Return the modified alist.
+Elements of ALIST that are not conses are ignored."
+  (while (and (consp (car alist))
+             (eq (cdr (car alist)) value))
+    (setq alist (cdr alist)))
+  (let ((tail alist) tail-cdr)
+    (while (setq tail-cdr (cdr tail))
+      (if (and (consp (car tail-cdr))
+              (eq (cdr (car tail-cdr)) value))
+         (setcdr tail (cdr tail-cdr))
+       (setq tail tail-cdr))))
+  alist)
+
+(defun remove (elt seq)
+  "Return a copy of SEQ with all occurrences of ELT removed.
+SEQ must be a list, vector, or string.  The comparison is done with `equal'."
+  (if (nlistp seq)
+      ;; If SEQ isn't a list, there's no need to copy SEQ because
+      ;; `delete' will return a new object.
+      (delete elt seq)
+    (delete elt (copy-sequence seq))))
+
+(defun remq (elt list)
+  "Return LIST with all occurrences of ELT removed.
+The comparison is done with `eq'.  Contrary to `delq', this does not use
+side-effects, and the argument LIST is not modified."
+  (if (memq elt list)
+      (delq elt (copy-sequence list))
+    list))
 \f
 ;;;; Keymap support.
 
+(defmacro kbd (keys)
+  "Convert KEYS to the internal Emacs key representation.
+KEYS should be a string constant in the format used for
+saving keyboard macros (see `edmacro-mode')."
+  (read-kbd-macro keys))
+
 (defun undefined ()
   (interactive)
   (ding))
 
-;Prevent the \{...} documentation construct
-;from mentioning keys that run this command.
+;Prevent the \{...} documentation construct
+;from mentioning keys that run this command.
 (put 'undefined 'suppress-keymap t)
 
 (defun suppress-keymap (map &optional nodigits)
@@ -346,76 +440,6 @@ but optional second arg NODIGITS non-nil treats them like other chars."
          (define-key map (char-to-string loop) 'digit-argument)
          (setq loop (1+ loop))))))
 
-(defvar key-substitution-in-progress nil
- "Used internally by `substitute-key-definition'.")
-
-(defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
-  "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
-In other words, OLDDEF is replaced with NEWDEF where ever it appears.
-Alternatively, if optional fourth argument OLDMAP is specified, we redefine
-in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
-
-For most uses, it is simpler and safer to use command remappping like this:
-  \(define-key KEYMAP [remap OLDDEF] NEWDEF)"
-  ;; Don't document PREFIX in the doc string because we don't want to
-  ;; advertise it.  It's meant for recursive calls only.  Here's its
-  ;; meaning
-
-  ;; If optional argument PREFIX is specified, it should be a key
-  ;; prefix, a string.  Redefined bindings will then be bound to the
-  ;; original key, with PREFIX added at the front.
-  (or prefix (setq prefix ""))
-  (let* ((scan (or oldmap keymap))
-        (prefix1 (vconcat prefix [nil]))
-        (key-substitution-in-progress
-         (cons scan key-substitution-in-progress)))
-    ;; Scan OLDMAP, finding each char or event-symbol that
-    ;; has any definition, and act on it with hack-key.
-    (map-keymap
-     (lambda (char defn)
-       (aset prefix1 (length prefix) char)
-       (substitute-key-definition-key defn olddef newdef prefix1 keymap))
-     scan)))
-
-(defun substitute-key-definition-key (defn olddef newdef prefix keymap)
-  (let (inner-def skipped menu-item)
-    ;; Find the actual command name within the binding.
-    (if (eq (car-safe defn) 'menu-item)
-       (setq menu-item defn defn (nth 2 defn))
-      ;; Skip past menu-prompt.
-      (while (stringp (car-safe defn))
-       (push (pop defn) skipped))
-      ;; Skip past cached key-equivalence data for menu items.
-      (if (consp (car-safe defn))
-         (setq defn (cdr defn))))
-    (if (or (eq defn olddef)
-           ;; Compare with equal if definition is a key sequence.
-           ;; That is useful for operating on function-key-map.
-           (and (or (stringp defn) (vectorp defn))
-                (equal defn olddef)))
-       (define-key keymap prefix
-         (if menu-item
-             (let ((copy (copy-sequence menu-item)))
-               (setcar (nthcdr 2 copy) newdef)
-               copy)
-           (nconc (nreverse skipped) newdef)))
-      ;; Look past a symbol that names a keymap.
-      (setq inner-def
-           (and defn
-                (condition-case nil (indirect-function defn) (error defn))))
-      ;; For nested keymaps, we use `inner-def' rather than `defn' so as to
-      ;; avoid autoloading a keymap.  This is mostly done to preserve the
-      ;; original non-autoloading behavior of pre-map-keymap times.
-      (if (and (keymapp inner-def)
-              ;; Avoid recursively scanning
-              ;; where KEYMAP does not have a submap.
-              (let ((elt (lookup-key keymap prefix)))
-                (or (null elt) (natnump elt) (keymapp elt)))
-              ;; Avoid recursively rescanning keymap being scanned.
-              (not (memq inner-def key-substitution-in-progress)))
-         ;; If this one isn't being scanned already, scan it now.
-         (substitute-key-definition olddef newdef keymap inner-def prefix)))))
-
 (defun define-key-after (keymap key definition &optional after)
   "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
 This is like `define-key' except that the binding for KEY is placed
@@ -483,58 +507,175 @@ Don't call this function; it is for internal use only."
          (funcall function (car p) (cdr p))))
     (map-keymap function keymap)))
 
-(defmacro kbd (keys)
-  "Convert KEYS to the internal Emacs key representation.
-KEYS should be a string constant in the format used for
-saving keyboard macros (see `edmacro-mode')."
-  (read-kbd-macro keys))
-
 (put 'keyboard-translate-table 'char-table-extra-slots 0)
 
 (defun keyboard-translate (from to)
   "Translate character FROM to TO at a low level.
 This function creates a `keyboard-translate-table' if necessary
 and then modifies one entry in it."
-  (let (t (terminal-local-value 'keyboard-translate-table))
-    (or (char-table-p t)
-       (setq t (make-char-table 'keyboard-translate-table nil)))
-    (aset t from to)))
-
+  (or (char-table-p keyboard-translate-table)
+      (setq keyboard-translate-table
+           (make-char-table 'keyboard-translate-table nil)))
+  (aset keyboard-translate-table from to))
 \f
-;;;; The global keymap tree.
-
-;;; global-map, esc-map, and ctl-x-map have their values set up in
-;;; keymap.c; we just give them docstrings here.
+;;;; Key binding commands.
 
-(defvar global-map nil
-  "Default global keymap mapping Emacs keyboard input into commands.
-The value is a keymap which is usually (but not necessarily) Emacs's
-global map.")
+(defun global-set-key (key command)
+  "Give KEY a global binding as COMMAND.
+COMMAND is the command definition to use; usually it is
+a symbol naming an interactively-callable function.
+KEY is a key sequence; noninteractively, it is a string or vector
+of characters or event types, and non-ASCII characters with codes
+above 127 (such as ISO Latin-1) can be included if you use a vector.
 
-(defvar esc-map nil
-  "Default keymap for ESC (meta) commands.
-The normal global definition of the character ESC indirects to this keymap.")
+Note that if KEY has a local binding in the current buffer,
+that local binding will continue to shadow any global binding
+that you make with this function."
+  (interactive "KSet key globally: \nCSet key %s to command: ")
+  (or (vectorp key) (stringp key)
+      (signal 'wrong-type-argument (list 'arrayp key)))
+  (define-key (current-global-map) key command))
 
-(defvar ctl-x-map nil
-  "Default keymap for C-x commands.
-The normal global definition of the character C-x indirects to this keymap.")
+(defun local-set-key (key command)
+  "Give KEY a local binding as COMMAND.
+COMMAND is the command definition to use; usually it is
+a symbol naming an interactively-callable function.
+KEY is a key sequence; noninteractively, it is a string or vector
+of characters or event types, and non-ASCII characters with codes
+above 127 (such as ISO Latin-1) can be included if you use a vector.
 
-(defvar ctl-x-4-map (make-sparse-keymap)
-  "Keymap for subcommands of C-x 4.")
-(defalias 'ctl-x-4-prefix ctl-x-4-map)
-(define-key ctl-x-map "4" 'ctl-x-4-prefix)
+The binding goes in the current buffer's local map,
+which in most cases is shared with all other buffers in the same major mode."
+  (interactive "KSet key locally: \nCSet key %s locally to command: ")
+  (let ((map (current-local-map)))
+    (or map
+       (use-local-map (setq map (make-sparse-keymap))))
+    (or (vectorp key) (stringp key)
+       (signal 'wrong-type-argument (list 'arrayp key)))
+    (define-key map key command)))
 
-(defvar ctl-x-5-map (make-sparse-keymap)
-  "Keymap for frame commands.")
-(defalias 'ctl-x-5-prefix ctl-x-5-map)
-(define-key ctl-x-map "5" 'ctl-x-5-prefix)
+(defun global-unset-key (key)
+  "Remove global binding of KEY.
+KEY is a string or vector representing a sequence of keystrokes."
+  (interactive "kUnset key globally: ")
+  (global-set-key key nil))
 
+(defun local-unset-key (key)
+  "Remove local binding of KEY.
+KEY is a string or vector representing a sequence of keystrokes."
+  (interactive "kUnset key locally: ")
+  (if (current-local-map)
+      (local-set-key key nil))
+  nil)
 \f
-;;;; Event manipulation functions.
+;;;; substitute-key-definition and its subroutines.
 
-;; The call to `read' is to ensure that the value is computed at load time
-;; and not compiled into the .elc file.  The value is negative on most
-;; machines, but not on all!
+(defvar key-substitution-in-progress nil
+ "Used internally by `substitute-key-definition'.")
+
+(defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
+  "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
+In other words, OLDDEF is replaced with NEWDEF where ever it appears.
+Alternatively, if optional fourth argument OLDMAP is specified, we redefine
+in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
+
+If you don't specify OLDMAP, you can usually get the same results
+in a cleaner way with command remapping, like this:
+  \(define-key KEYMAP [remap OLDDEF] NEWDEF)
+\n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)"
+  ;; Don't document PREFIX in the doc string because we don't want to
+  ;; advertise it.  It's meant for recursive calls only.  Here's its
+  ;; meaning
+
+  ;; If optional argument PREFIX is specified, it should be a key
+  ;; prefix, a string.  Redefined bindings will then be bound to the
+  ;; original key, with PREFIX added at the front.
+  (or prefix (setq prefix ""))
+  (let* ((scan (or oldmap keymap))
+        (prefix1 (vconcat prefix [nil]))
+        (key-substitution-in-progress
+         (cons scan key-substitution-in-progress)))
+    ;; Scan OLDMAP, finding each char or event-symbol that
+    ;; has any definition, and act on it with hack-key.
+    (map-keymap
+     (lambda (char defn)
+       (aset prefix1 (length prefix) char)
+       (substitute-key-definition-key defn olddef newdef prefix1 keymap))
+     scan)))
+
+(defun substitute-key-definition-key (defn olddef newdef prefix keymap)
+  (let (inner-def skipped menu-item)
+    ;; Find the actual command name within the binding.
+    (if (eq (car-safe defn) 'menu-item)
+       (setq menu-item defn defn (nth 2 defn))
+      ;; Skip past menu-prompt.
+      (while (stringp (car-safe defn))
+       (push (pop defn) skipped))
+      ;; Skip past cached key-equivalence data for menu items.
+      (if (consp (car-safe defn))
+         (setq defn (cdr defn))))
+    (if (or (eq defn olddef)
+           ;; Compare with equal if definition is a key sequence.
+           ;; That is useful for operating on function-key-map.
+           (and (or (stringp defn) (vectorp defn))
+                (equal defn olddef)))
+       (define-key keymap prefix
+         (if menu-item
+             (let ((copy (copy-sequence menu-item)))
+               (setcar (nthcdr 2 copy) newdef)
+               copy)
+           (nconc (nreverse skipped) newdef)))
+      ;; Look past a symbol that names a keymap.
+      (setq inner-def
+           (or (indirect-function defn t) defn))
+      ;; For nested keymaps, we use `inner-def' rather than `defn' so as to
+      ;; avoid autoloading a keymap.  This is mostly done to preserve the
+      ;; original non-autoloading behavior of pre-map-keymap times.
+      (if (and (keymapp inner-def)
+              ;; Avoid recursively scanning
+              ;; where KEYMAP does not have a submap.
+              (let ((elt (lookup-key keymap prefix)))
+                (or (null elt) (natnump elt) (keymapp elt)))
+              ;; Avoid recursively rescanning keymap being scanned.
+              (not (memq inner-def key-substitution-in-progress)))
+         ;; If this one isn't being scanned already, scan it now.
+         (substitute-key-definition olddef newdef keymap inner-def prefix)))))
+
+\f
+;;;; The global keymap tree.
+
+;;; global-map, esc-map, and ctl-x-map have their values set up in
+;;; keymap.c; we just give them docstrings here.
+
+(defvar global-map nil
+  "Default global keymap mapping Emacs keyboard input into commands.
+The value is a keymap which is usually (but not necessarily) Emacs's
+global map.")
+
+(defvar esc-map nil
+  "Default keymap for ESC (meta) commands.
+The normal global definition of the character ESC indirects to this keymap.")
+
+(defvar ctl-x-map nil
+  "Default keymap for C-x commands.
+The normal global definition of the character C-x indirects to this keymap.")
+
+(defvar ctl-x-4-map (make-sparse-keymap)
+  "Keymap for subcommands of C-x 4.")
+(defalias 'ctl-x-4-prefix ctl-x-4-map)
+(define-key ctl-x-map "4" 'ctl-x-4-prefix)
+
+(defvar ctl-x-5-map (make-sparse-keymap)
+  "Keymap for frame commands.")
+(defalias 'ctl-x-5-prefix ctl-x-5-map)
+(define-key ctl-x-map "5" 'ctl-x-5-prefix)
+
+\f
+;;;; Event manipulation functions.
+
+;; The call to `read' is to ensure that the value is computed at load time
+;; and not compiled into the .elc file.  The value is negative on most
+;; machines, but not on all!
 (defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
 
 (defun listify-key-sequence (key)
@@ -642,6 +783,8 @@ The `posn-' functions access elements of such lists."
   "Return the multi-click count of EVENT, a click or drag event.
 The return value is a positive integer."
   (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
+\f
+;;;; Extracting fields of the positions in an event.
 
 (defsubst posn-window (position)
   "Return the window in POSITION.
@@ -726,19 +869,23 @@ and `event-end' functions."
   (nth 3 position))
 
 (defsubst posn-string (position)
-  "Return the string object of POSITION, or nil if a buffer position.
+  "Return the string object of POSITION.
+Value is a cons (STRING . STRING-POS), or nil if not a string.
 POSITION should be a list of the form returned by the `event-start'
 and `event-end' functions."
   (nth 4 position))
 
 (defsubst posn-image (position)
-  "Return the image object of POSITION, or nil if a not an image.
+  "Return the image object of POSITION.
+Value is an list (image ...), or nil if not an image.
 POSITION should be a list of the form returned by the `event-start'
 and `event-end' functions."
   (nth 7 position))
 
 (defsubst posn-object (position)
   "Return the object (image or string) of POSITION.
+Value is a list (image ...) for an image object, a cons cell
+\(STRING . STRING-POS) for a string object, and nil for a buffer position.
 POSITION should be a list of the form returned by the `event-start'
 and `event-end' functions."
   (or (posn-image position) (posn-string position)))
@@ -831,6 +978,8 @@ is converted into a string by expressing it in decimal."
 (defalias 'point-at-eol 'line-end-position)
 (defalias 'point-at-bol 'line-beginning-position)
 
+(defalias 'user-original-login-name 'user-login-name)
+
 \f
 ;;;; Hook manipulation functions.
 
@@ -936,9 +1085,10 @@ the hook's buffer-local value rather than its default value."
            (kill-local-variable hook)
          (set hook hook-value))))))
 
-(defun add-to-list (list-var element &optional append)
+(defun add-to-list (list-var element &optional append compare-fn)
   "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
-The test for presence of ELEMENT is done with `equal'.
+The test for presence of ELEMENT is done with `equal',
+or with COMPARE-FN if that's non-nil.
 If ELEMENT is added, it is added at the beginning of the list,
 unless the optional argument APPEND is non-nil, in which case
 ELEMENT is added at the end.
@@ -950,7 +1100,13 @@ until a certain package is loaded, you should put the call to `add-to-list'
 into a hook function that will be run only after loading the package.
 `eval-after-load' provides one way to do this.  In some cases
 other hooks, such as major mode hooks, can do the job."
-  (if (member element (symbol-value list-var))
+  (if (if compare-fn
+         (let (present)
+           (dolist (elt (symbol-value list-var))
+             (if (funcall compare-fn element elt)
+                 (setq present t)))
+           present)
+       (member element (symbol-value list-var)))
       (symbol-value list-var)
     (set list-var
         (if append
@@ -992,28 +1148,197 @@ The return value is the new value of LIST-VAR."
                                (< oa ob)
                              oa)))))))
 
+(defun add-to-history (history-var newelt &optional maxelt keep-all)
+  "Add NEWELT to the history list stored in the variable HISTORY-VAR.
+Return the new history list.
+If MAXELT is non-nil, it specifies the maximum length of the history.
+Otherwise, the maximum history length is the value of the `history-length'
+property on symbol HISTORY-VAR, if set, or the value of the `history-length'
+variable.
+Remove duplicates of NEWELT if `history-delete-duplicates' is non-nil.
+If optional fourth arg KEEP-ALL is non-nil, add NEWELT to history even
+if it is empty or a duplicate."
+  (unless maxelt
+    (setq maxelt (or (get history-var 'history-length)
+                    history-length)))
+  (let ((history (symbol-value history-var))
+       tail)
+    (when (and (listp history)
+              (or keep-all
+                  (not (stringp newelt))
+                  (> (length newelt) 0))
+              (or keep-all
+                  (not (equal (car history) newelt))))
+      (if history-delete-duplicates
+         (delete newelt history))
+      (setq history (cons newelt history))
+      (when (integerp maxelt)
+       (if (= 0 maxelt)
+           (setq history nil)
+         (setq tail (nthcdr (1- maxelt) history))
+         (when (consp tail)
+           (setcdr tail nil)))))
+    (set history-var history)))
+
+\f
+;;;; Mode hooks.
+
+(defvar delay-mode-hooks nil
+  "If non-nil, `run-mode-hooks' should delay running the hooks.")
+(defvar delayed-mode-hooks nil
+  "List of delayed mode hooks waiting to be run.")
+(make-variable-buffer-local 'delayed-mode-hooks)
+(put 'delay-mode-hooks 'permanent-local t)
+
+(defvar after-change-major-mode-hook nil
+  "Normal hook run at the very end of major mode functions.")
+
+(defun run-mode-hooks (&rest hooks)
+  "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
+Execution is delayed if `delay-mode-hooks' is non-nil.
+If `delay-mode-hooks' is nil, run `after-change-major-mode-hook'
+after running the mode hooks.
+Major mode functions should use this."
+  (if delay-mode-hooks
+      ;; Delaying case.
+      (dolist (hook hooks)
+       (push hook delayed-mode-hooks))
+    ;; Normal case, just run the hook as before plus any delayed hooks.
+    (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
+    (setq delayed-mode-hooks nil)
+    (apply 'run-hooks hooks)
+    (run-hooks 'after-change-major-mode-hook)))
+
+(defmacro delay-mode-hooks (&rest body)
+  "Execute BODY, but delay any `run-mode-hooks'.
+These hooks will be executed by the first following call to
+`run-mode-hooks' that occurs outside any `delayed-mode-hooks' form.
+Only affects hooks run in the current buffer."
+  (declare (debug t) (indent 0))
+  `(progn
+     (make-local-variable 'delay-mode-hooks)
+     (let ((delay-mode-hooks t))
+       ,@body)))
+
+;; PUBLIC: find if the current mode derives from another.
+
+(defun derived-mode-p (&rest modes)
+  "Non-nil if the current major mode is derived from one of MODES.
+Uses the `derived-mode-parent' property of the symbol to trace backwards."
+  (let ((parent major-mode))
+    (while (and (not (memq parent modes))
+               (setq parent (get parent 'derived-mode-parent))))
+    parent))
+\f
+;;;; Minor modes.
+
+;; If a minor mode is not defined with define-minor-mode,
+;; add it here explicitly.
+;; isearch-mode is deliberately excluded, since you should
+;; not call it yourself.
+(defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
+                                        overwrite-mode view-mode
+                                         hs-minor-mode)
+  "List of all minor mode functions.")
+
+(defun add-minor-mode (toggle name &optional keymap after toggle-fun)
+  "Register a new minor mode.
+
+This is an XEmacs-compatibility function.  Use `define-minor-mode' instead.
+
+TOGGLE is a symbol which is the name of a buffer-local variable that
+is toggled on or off to say whether the minor mode is active or not.
+
+NAME specifies what will appear in the mode line when the minor mode
+is active.  NAME should be either a string starting with a space, or a
+symbol whose value is such a string.
+
+Optional KEYMAP is the keymap for the minor mode that will be added
+to `minor-mode-map-alist'.
+
+Optional AFTER specifies that TOGGLE should be added after AFTER
+in `minor-mode-alist'.
+
+Optional TOGGLE-FUN is an interactive function to toggle the mode.
+It defaults to (and should by convention be) TOGGLE.
+
+If TOGGLE has a non-nil `:included' property, an entry for the mode is
+included in the mode-line minor mode menu.
+If TOGGLE has a `:menu-tag', that is used for the menu item's label."
+  (unless (memq toggle minor-mode-list)
+    (push toggle minor-mode-list))
+
+  (unless toggle-fun (setq toggle-fun toggle))
+  (unless (eq toggle-fun toggle)
+    (put toggle :minor-mode-function toggle-fun))
+  ;; Add the name to the minor-mode-alist.
+  (when name
+    (let ((existing (assq toggle minor-mode-alist)))
+      (if existing
+         (setcdr existing (list name))
+       (let ((tail minor-mode-alist) found)
+         (while (and tail (not found))
+           (if (eq after (caar tail))
+               (setq found tail)
+             (setq tail (cdr tail))))
+         (if found
+             (let ((rest (cdr found)))
+               (setcdr found nil)
+               (nconc found (list (list toggle name)) rest))
+           (setq minor-mode-alist (cons (list toggle name)
+                                        minor-mode-alist)))))))
+  ;; Add the toggle to the minor-modes menu if requested.
+  (when (get toggle :included)
+    (define-key mode-line-mode-menu
+      (vector toggle)
+      (list 'menu-item
+           (concat
+            (or (get toggle :menu-tag)
+                (if (stringp name) name (symbol-name toggle)))
+            (let ((mode-name (if (symbolp name) (symbol-value name))))
+              (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
+                  (concat " (" (match-string 0 mode-name) ")"))))
+           toggle-fun
+           :button (cons :toggle toggle))))
+
+  ;; Add the map to the minor-mode-map-alist.
+  (when keymap
+    (let ((existing (assq toggle minor-mode-map-alist)))
+      (if existing
+         (setcdr existing keymap)
+       (let ((tail minor-mode-map-alist) found)
+         (while (and tail (not found))
+           (if (eq after (caar tail))
+               (setq found tail)
+             (setq tail (cdr tail))))
+         (if found
+             (let ((rest (cdr found)))
+               (setcdr found nil)
+               (nconc found (list (cons toggle keymap)) rest))
+           (setq minor-mode-map-alist (cons (cons toggle keymap)
+                                            minor-mode-map-alist))))))))
 \f
 ;;; Load history
 
-;;; (defvar symbol-file-load-history-loaded nil
-;;;   "Non-nil means we have loaded the file `fns-VERSION.el' in `exec-directory'.
-;;; That file records the part of `load-history' for preloaded files,
-;;; which is cleared out before dumping to make Emacs smaller.")
-
-;;; (defun load-symbol-file-load-history ()
-;;;   "Load the file `fns-VERSION.el' in `exec-directory' if not already done.
-;;; That file records the part of `load-history' for preloaded files,
-;;; which is cleared out before dumping to make Emacs smaller."
-;;;   (unless symbol-file-load-history-loaded
-;;;     (load (expand-file-name
-;;;       ;; fns-XX.YY.ZZ.el does not work on DOS filesystem.
-;;;       (if (eq system-type 'ms-dos)
-;;;           "fns.el"
-;;;         (format "fns-%s.el" emacs-version))
-;;;       exec-directory)
-;;;      ;; The file name fns-%s.el already has a .el extension.
-;;;      nil nil t)
-;;;     (setq symbol-file-load-history-loaded t)))
+;; (defvar symbol-file-load-history-loaded nil
+;;   "Non-nil means we have loaded the file `fns-VERSION.el' in `exec-directory'.
+;; That file records the part of `load-history' for preloaded files,
+;; which is cleared out before dumping to make Emacs smaller.")
+
+;; (defun load-symbol-file-load-history ()
+;;   "Load the file `fns-VERSION.el' in `exec-directory' if not already done.
+;; That file records the part of `load-history' for preloaded files,
+;; which is cleared out before dumping to make Emacs smaller."
+;;   (unless symbol-file-load-history-loaded
+;;     (load (expand-file-name
+;;        ;; fns-XX.YY.ZZ.el does not work on DOS filesystem.
+;;        (if (eq system-type 'ms-dos)
+;;            "fns.el"
+;;          (format "fns-%s.el" emacs-version))
+;;        exec-directory)
+;;       ;; The file name fns-%s.el already has a .el extension.
+;;       nil nil t)
+;;     (setq symbol-file-load-history-loaded t)))
 
 (defun symbol-file (symbol &optional type)
   "Return the input source in which SYMBOL was defined.
@@ -1045,34 +1370,142 @@ definition only or variable definition only.
        (setq files (cdr files)))
       file)))
 
+;;;###autoload
+(defun locate-library (library &optional nosuffix path interactive-call)
+  "Show the precise file name of Emacs library LIBRARY.
+This command searches the directories in `load-path' like `\\[load-library]'
+to find the file that `\\[load-library] RET LIBRARY RET' would load.
+Optional second arg NOSUFFIX non-nil means don't add suffixes `load-suffixes'
+to the specified name LIBRARY.
+
+If the optional third arg PATH is specified, that list of directories
+is used instead of `load-path'.
+
+When called from a program, the file name is normaly returned as a
+string.  When run interactively, the argument INTERACTIVE-CALL is t,
+and the file name is displayed in the echo area."
+  (interactive (list (completing-read "Locate library: "
+                                     'locate-file-completion
+                                     (cons load-path (get-load-suffixes)))
+                    nil nil
+                    t))
+  (let ((file (locate-file library
+                          (or path load-path)
+                          (append (unless nosuffix (get-load-suffixes))
+                                  load-file-rep-suffixes))))
+    (if interactive-call
+       (if file
+           (message "Library is file %s" (abbreviate-file-name file))
+         (message "No library %s in search path" library)))
+    file))
+
 \f
-;;;; Specifying things to do after certain files are loaded.
+;;;; Specifying things to do later.
+
+(defmacro eval-at-startup (&rest body)
+  "Make arrangements to evaluate BODY when Emacs starts up.
+If this is run after Emacs startup, evaluate BODY immediately.
+Always returns nil.
+
+This works by adding a function to `before-init-hook'.
+That function's doc string says which file created it."
+  `(progn
+     (if command-line-processed
+        (progn . ,body)
+       (add-hook 'before-init-hook
+                '(lambda () ,(concat "From " (or load-file-name "no file"))
+                   . ,body)
+                t))
+     nil))
+
+(defun load-history-regexp (file)
+  "Form a regexp to find FILE in `load-history'.
+FILE, a string, is described in the function `eval-after-load'."
+  (if (file-name-absolute-p file)
+      (setq file (file-truename file)))
+  (concat (if (file-name-absolute-p file) "\\`" "\\(\\`\\|/\\)")
+         (regexp-quote file)
+         (if (file-name-extension file)
+             ""
+           ;; Note: regexp-opt can't be used here, since we need to call
+           ;; this before Emacs has been fully started.  2006-05-21
+           (concat "\\(" (mapconcat 'regexp-quote load-suffixes "\\|") "\\)?"))
+         "\\(" (mapconcat 'regexp-quote jka-compr-load-suffixes "\\|")
+         "\\)?\\'"))
+
+(defun load-history-filename-element (file-regexp)
+  "Get the first elt of `load-history' whose car matches FILE-REGEXP.
+Return nil if there isn't one."
+  (let* ((loads load-history)
+        (load-elt (and loads (car loads))))
+    (save-match-data
+      (while (and loads
+                 (or (null (car load-elt))
+                     (not (string-match file-regexp (car load-elt)))))
+       (setq loads (cdr loads)
+             load-elt (and loads (car loads)))))
+    load-elt))
 
 (defun eval-after-load (file form)
   "Arrange that, if FILE is ever loaded, FORM will be run at that time.
-This makes or adds to an entry on `after-load-alist'.
 If FILE is already loaded, evaluate FORM right now.
-It does nothing if FORM is already on the list for FILE.
-FILE must match exactly.  Normally FILE is the name of a library,
-with no directory or extension specified, since that is how `load'
-is normally called.
-FILE can also be a feature (i.e. a symbol), in which case FORM is
-evaluated whenever that feature is `provide'd."
-  (let ((elt (assoc file after-load-alist)))
-    ;; Make sure there is an element for FILE.
-    (unless elt (setq elt (list file)) (push elt after-load-alist))
-    ;; Add FORM to the element if it isn't there.
+
+If a matching file is loaded again, FORM will be evaluated again.
+
+If FILE is a string, it may be either an absolute or a relative file
+name, and may have an extension \(e.g. \".el\") or may lack one, and
+additionally may or may not have an extension denoting a compressed
+format \(e.g. \".gz\").
+
+When FILE is absolute, this first converts it to a true name by chasing
+symbolic links.  Only a file of this name \(see next paragraph regarding
+extensions) will trigger the evaluation of FORM.  When FILE is relative,
+a file whose absolute true name ends in FILE will trigger evaluation.
+
+When FILE lacks an extension, a file name with any extension will trigger
+evaluation.  Otherwise, its extension must match FILE's.  A further
+extension for a compressed format \(e.g. \".gz\") on FILE will not affect
+this name matching.
+
+Alternatively, FILE can be a feature (i.e. a symbol), in which case FORM
+is evaluated whenever that feature is `provide'd.
+
+Usually FILE is just a library name like \"font-lock\" or a feature name
+like 'font-lock.
+
+This function makes or adds to an entry on `after-load-alist'."
+  ;; Add this FORM into after-load-alist (regardless of whether we'll be
+  ;; evaluating it now).
+  (let* ((regexp-or-feature
+         (if (stringp file) (load-history-regexp file) file))
+        (elt (assoc regexp-or-feature after-load-alist)))
+    (unless elt
+      (setq elt (list regexp-or-feature))
+      (push elt after-load-alist))
+    ;; Add FORM to the element unless it's already there.
     (unless (member form (cdr elt))
-      (nconc elt (list form))
-      ;; If the file has been loaded already, run FORM right away.
-      (if (if (symbolp file)
-             (featurep file)
-           ;; Make sure `load-history' contains the files dumped with
-           ;; Emacs for the case that FILE is one of them.
-           ;; (load-symbol-file-load-history)
-           (assoc file load-history))
-         (eval form))))
-  form)
+      (nconc elt (list form)))
+
+    ;; Is there an already loaded file whose name (or `provide' name)
+    ;; matches FILE?
+    (if (if (stringp file)
+           (load-history-filename-element regexp-or-feature)
+         (featurep file))
+       (eval form))))
+
+(defun do-after-load-evaluation (abs-file)
+  "Evaluate all `eval-after-load' forms, if any, for ABS-FILE.
+ABS-FILE, a string, should be the absolute true name of a file just loaded."
+  (let ((after-load-elts after-load-alist)
+       a-l-element file-elements file-element form)
+    (while after-load-elts
+      (setq a-l-element (car after-load-elts)
+           after-load-elts (cdr after-load-elts))
+      (when (and (stringp (car a-l-element))
+                (string-match (car a-l-element) abs-file))
+       (while (setq a-l-element (cdr a-l-element)) ; discard the file name
+         (setq form (car a-l-element))
+         (eval form))))))
 
 (defun eval-next-after-load (file)
   "Read the following input sexp, and run it whenever FILE is loaded.
@@ -1080,7 +1513,9 @@ This makes or adds to an entry on `after-load-alist'.
 FILE should be the name of a library, with no directory name."
   (eval-after-load file (read)))
 \f
-;;; open-network-stream is a wrapper around make-network-process.
+;;;; Process stuff.
+
+;; open-network-stream is a wrapper around make-network-process.
 
 (when (featurep 'make-network-process)
   (defun open-network-stream (name buffer host service)
@@ -1170,8 +1605,7 @@ any other non-digit terminates the character code and is then used as input."))
       ;; or C-q C-x might not return immediately since ESC or C-x might be
       ;; bound to some prefix in function-key-map or key-translation-map.
       (setq translated char)
-      (let ((translation (lookup-key (terminal-local-value 'local-function-key-map nil)
-                                    (vector char))))
+      (let ((translation (lookup-key local-function-key-map (vector char))))
        (if (arrayp translation)
            (setq translated (aref translation 0))))
       (cond ((null translated))
@@ -1208,7 +1642,7 @@ Optional DEFAULT is a default password to use instead of empty input.
 This function echoes `.' for each character that the user types.
 The user ends with RET, LFD, or ESC.  DEL or C-h rubs out.  C-u kills line.
 C-g quits; if `inhibit-quit' was non-nil around this function,
-then it returns nil if the user types C-g.
+then it returns nil if the user types C-g, but quit-flag remains set.
 
 Once the caller uses the password, it can erase the password
 by doing (clear-string STRING)."
@@ -1228,9 +1662,15 @@ by doing (clear-string STRING)."
                (sit-for 1))))
          success)
       (let ((pass nil)
+           ;; Copy it so that add-text-properties won't modify
+           ;; the object that was passed in by the caller.
+           (prompt (copy-sequence prompt))
            (c 0)
            (echo-keystrokes 0)
-           (cursor-in-echo-area t))
+           (cursor-in-echo-area t)
+           (message-log-max nil))
+       (add-text-properties 0 (length prompt)
+                            minibuffer-prompt-properties prompt)
        (while (progn (message "%s%s"
                               prompt
                               (make-string (length pass) ?.))
@@ -1278,6 +1718,42 @@ by doing (clear-string STRING)."
            (sit-for 1)
            t)))
     n))
+
+(defun sit-for (seconds &optional nodisp obsolete)
+  "Perform redisplay, then wait for SECONDS seconds or until input is available.
+SECONDS may be a floating-point value.
+\(On operating systems that do not support waiting for fractions of a
+second, floating-point values are rounded down to the nearest integer.)
+
+If optional arg NODISP is t, don't redisplay, just wait for input.
+Redisplay does not happen if input is available before it starts.
+
+Value is t if waited the full time with no input arriving, and nil otherwise.
+
+An obsolete, but still supported form is
+\(sit-for SECONDS &optional MILLISECONDS NODISP)
+where the optional arg MILLISECONDS specifies an additional wait period,
+in milliseconds; this was useful when Emacs was built without
+floating point support.
+
+\(fn SECONDS &optional NODISP)"
+  (when (or obsolete (numberp nodisp))
+    (setq seconds (+ seconds (* 1e-3 nodisp)))
+    (setq nodisp obsolete))
+  (cond
+   (noninteractive
+    (sleep-for seconds)
+    t)
+   ((input-pending-p)
+    nil)
+   ((<= seconds 0)
+    (or nodisp (redisplay)))
+   (t
+    (or nodisp (redisplay))
+    (let ((read (read-event nil nil seconds)))
+      (or (null read)
+         (progn (push read unread-command-events)
+                nil))))))
 \f
 ;;; Atomic change groups.
 
@@ -1290,6 +1766,7 @@ This works regardless of whether undo is enabled in the buffer.
 This mechanism is transparent to ordinary use of undo;
 if undo is enabled in the buffer and BODY succeeds, the
 user can undo the change normally."
+  (declare (indent 0) (debug t))
   (let ((handle (make-symbol "--change-group-handle--"))
        (success (make-symbol "--change-group-success--")))
     `(let ((,handle (prepare-change-group))
@@ -1373,7 +1850,7 @@ This finishes the change group by reverting all of its changes."
        (when (and (consp elt) (not (eq elt (last pending-undo-list))))
          (error "Undoing to some unrelated state"))
        ;; Undo it all.
-       (while pending-undo-list (undo-more 1))
+       (while (listp pending-undo-list) (undo-more 1))
        ;; Reset the modified cons cell ELT to its original content.
        (when (consp elt)
          (setcar elt old-car)
@@ -1381,6 +1858,8 @@ This finishes the change group by reverting all of its changes."
        ;; Revert the undo info to what it was when we grabbed the state.
        (setq buffer-undo-list elt)))))
 \f
+;;;; Display-related functions.
+
 ;; For compatibility.
 (defalias 'redraw-modeline 'force-mode-line-update)
 
@@ -1519,33 +1998,106 @@ This variable is meaningful on MS-DOG and Windows NT.
 On those systems, it is automatically local in every buffer.
 On other systems, this variable is normally always nil.")
 
-;; This should probably be written in C (i.e., without using `walk-windows').
-(defun get-buffer-window-list (buffer &optional minibuf frame)
-  "Return list of all windows displaying BUFFER, or nil if none.
-BUFFER can be a buffer or a buffer name.
-See `walk-windows' for the meaning of MINIBUF and FRAME."
-  (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
-    (walk-windows (function (lambda (window)
-                             (if (eq (window-buffer window) buffer)
-                                 (setq windows (cons window windows)))))
-                 minibuf frame)
-    windows))
+;; The `assert' macro from the cl package signals
+;; `cl-assertion-failed' at runtime so always define it.
+(put 'cl-assertion-failed 'error-conditions '(error))
+(put 'cl-assertion-failed 'error-message "Assertion failed")
 
-(defun ignore (&rest ignore)
-  "Do nothing and return nil.
-This function accepts any number of arguments, but ignores them."
-  (interactive)
-  nil)
+\f
+;;;; Misc. useful functions.
 
-(defun error (&rest args)
-  "Signal an error, making error message by passing all args to `format'.
-In Emacs, the convention is that error messages start with a capital
-letter but *do not* end with a period.  Please follow this convention
-for the sake of consistency."
-  (while t
-    (signal 'error (list (apply 'format args)))))
+(defun find-tag-default ()
+  "Determine default tag to search for, based on text at point.
+If there is no plausible default, return nil."
+  (save-excursion
+    (while (looking-at "\\sw\\|\\s_")
+      (forward-char 1))
+    (if (or (re-search-backward "\\sw\\|\\s_"
+                               (save-excursion (beginning-of-line) (point))
+                               t)
+           (re-search-forward "\\(\\sw\\|\\s_\\)+"
+                              (save-excursion (end-of-line) (point))
+                              t))
+       (progn
+         (goto-char (match-end 0))
+         (condition-case nil
+             (buffer-substring-no-properties
+              (point)
+              (progn (forward-sexp -1)
+                     (while (looking-at "\\s'")
+                       (forward-char 1))
+                     (point)))
+           (error nil)))
+      nil)))
 
-(defalias 'user-original-login-name 'user-login-name)
+(defun play-sound (sound)
+  "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
+The following keywords are recognized:
+
+  :file FILE - read sound data from FILE.  If FILE isn't an
+absolute file name, it is searched in `data-directory'.
+
+  :data DATA - read sound data from string DATA.
+
+Exactly one of :file or :data must be present.
+
+  :volume VOL - set volume to VOL.  VOL must an integer in the
+range 0..100 or a float in the range 0..1.0.  If not specified,
+don't change the volume setting of the sound device.
+
+  :device DEVICE - play sound on DEVICE.  If not specified,
+a system-dependent default device name is used."
+  (if (fboundp 'play-sound-internal)
+      (play-sound-internal sound)
+    (error "This Emacs binary lacks sound support")))
+
+(defun shell-quote-argument (argument)
+  "Quote an argument for passing as argument to an inferior shell."
+  (if (or (eq system-type 'ms-dos)
+          (and (eq system-type 'windows-nt) (w32-shell-dos-semantics)))
+      ;; Quote using double quotes, but escape any existing quotes in
+      ;; the argument with backslashes.
+      (let ((result "")
+           (start 0)
+           end)
+       (if (or (null (string-match "[^\"]" argument))
+               (< (match-end 0) (length argument)))
+           (while (string-match "[\"]" argument start)
+             (setq end (match-beginning 0)
+                   result (concat result (substring argument start end)
+                                  "\\" (substring argument end (1+ end)))
+                   start (1+ end))))
+       (concat "\"" result (substring argument start) "\""))
+    (if (equal argument "")
+        "''"
+      ;; Quote everything except POSIX filename characters.
+      ;; This should be safe enough even for really weird shells.
+      (let ((result "") (start 0) end)
+        (while (string-match "[^-0-9a-zA-Z_./]" argument start)
+          (setq end (match-beginning 0)
+                result (concat result (substring argument start end)
+                               "\\" (substring argument end (1+ end)))
+                start (1+ end)))
+        (concat result (substring argument start))))))
+
+(defun string-or-null-p (object)
+  "Return t if OBJECT is a string or nil.
+Otherwise, return nil."
+  (or (stringp object) (null object)))
+
+(defun booleanp (object)
+  "Return non-nil if OBJECT is one of the two canonical boolean values: t or nil."
+  (memq object '(nil t)))
+
+(defun field-at-pos (pos)
+  "Return the field at position POS, taking stickiness etc into account"
+  (let ((raw-field (get-char-property (field-beginning pos) 'field)))
+    (if (eq raw-field 'boundary)
+       (get-char-property (1- (field-end pos)) 'field)
+      raw-field)))
+
+\f
+;;;; Support for yanking and text properties.
 
 (defvar yank-excluded-properties)
 
@@ -1615,11 +2167,32 @@ If UNDO is present and non-nil, it is a function that will be called
   (let* ((handler (and (stringp string)
                       (get-text-property 0 'yank-handler string)))
         (param (or (nth 1 handler) string))
-        (opoint (point)))
+        (opoint (point))
+        end)
+
     (setq yank-undo-function t)
     (if (nth 0 handler) ;; FUNCTION
        (funcall (car handler) param)
       (insert param))
+    (setq end (point))
+
+    ;; What should we do with `font-lock-face' properties?
+    (if font-lock-defaults
+       ;; No, just wipe them.
+       (remove-list-of-text-properties opoint end '(font-lock-face))
+      ;; Convert them to `face'.
+      (save-excursion
+       (goto-char opoint)
+       (while (< (point) end)
+         (let ((face (get-text-property (point) 'font-lock-face))
+               run-end)
+           (setq run-end
+                 (next-single-property-change (point) 'font-lock-face nil end))
+           (when face
+             (remove-text-properties (point) run-end '(font-lock-face nil))
+             (put-text-property (point) run-end 'face face))
+           (goto-char run-end)))))
+
     (unless (nth 2 handler) ;; NOEXCLUDE
       (remove-yank-excluded-properties opoint (point)))
     (if (eq yank-undo-function t)  ;; not set by FUNCTION
@@ -1651,7 +2224,7 @@ Strip text properties from the inserted text according to
     (remove-yank-excluded-properties opoint (point))))
 
 \f
-;; Synchronous shell commands.
+;;;; Synchronous shell commands.
 
 (defun start-process-shell-command (name buffer &rest args)
   "Start a program in a subprocess.  Return the process object for it.
@@ -1662,7 +2235,9 @@ BUFFER is the buffer (or buffer name) to associate with the process.
  BUFFER may be also nil, meaning that this process is not associated
  with any buffer
 COMMAND is the name of a shell command.
-Remaining arguments are the arguments for the command.
+Remaining arguments are the arguments for the command; they are all
+spliced together with blanks separating between each two of them, before
+passing the command to the shell.
 Wildcards and redirection are handled as usual in the shell.
 
 \(fn NAME BUFFER COMMAND &rest COMMAND-ARGS)"
@@ -1707,8 +2282,11 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
                  shell-command-switch
                  (mapconcat 'identity (cons command args) " ")))))
 \f
+;;;; Lisp macros to do various things temporarily.
+
 (defmacro with-current-buffer (buffer &rest body)
-  "Execute the forms in BODY with BUFFER as the current buffer.
+  "Execute the forms in BODY with BUFFER temporarily current.
+BUFFER can be a buffer or a buffer name.
 The value returned is the value of the last form in BODY.
 See also `with-temp-buffer'."
   (declare (indent 1) (debug t))
@@ -1756,12 +2334,17 @@ See also `with-temp-buffer'."
 The value returned is the value of the last form in BODY.
 See also `with-temp-buffer'."
   (declare (indent 1) (debug t))
-  `(let ((save-selected-frame (selected-frame)))
-     (unwind-protect
-        (progn (select-frame ,frame)
-               ,@body)
-       (if (frame-live-p save-selected-frame)
-          (select-frame save-selected-frame)))))
+  (let ((old-frame (make-symbol "old-frame"))
+       (old-buffer (make-symbol "old-buffer")))
+    `(let ((,old-frame (selected-frame))
+          (,old-buffer (current-buffer)))
+       (unwind-protect
+          (progn (select-frame ,frame)
+                 ,@body)
+        (if (frame-live-p ,old-frame)
+            (select-frame ,old-frame))
+        (if (buffer-live-p ,old-buffer)
+            (set-buffer ,old-buffer))))))
 
 (defmacro with-temp-file (file &rest body)
   "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
@@ -1833,13 +2416,19 @@ See also `with-temp-file' and `with-output-to-string'."
 (defmacro with-local-quit (&rest body)
   "Execute BODY, allowing quits to terminate BODY but not escape further.
 When a quit terminates BODY, `with-local-quit' returns nil but
-requests another quit.  That quit will be processed, the next time quitting
-is allowed once again."
+requests another quit.  That quit will be processed as soon as quitting
+is allowed once again.  (Immediately, if `inhibit-quit' is nil.)"
   (declare (debug t) (indent 0))
   `(condition-case nil
        (let ((inhibit-quit nil))
         ,@body)
-     (quit (setq quit-flag t) nil)))
+     (quit (setq quit-flag t)
+          ;; This call is to give a chance to handle quit-flag
+          ;; in case inhibit-quit is nil.
+          ;; Without this, it will not be handled until the next function
+          ;; call, and that might allow it to exit thru a condition-case
+          ;; that intends to handle the quit signal next time.
+          (eval '(ignore nil)))))
 
 (defmacro while-no-input (&rest body)
   "Execute BODY only as long as there's no pending input.
@@ -1851,8 +2440,8 @@ If BODY finishes, `while-no-input' returns whatever value BODY produced."
     `(with-local-quit
        (catch ',catch-sym
         (let ((throw-on-input ',catch-sym))
-          (or (not (sit-for 0 0 t))
-            ,@body))))))
+          (or (input-pending-p)
+              ,@body))))))
 
 (defmacro combine-after-change-calls (&rest body)
   "Execute BODY, but don't call the after-change functions till the end.
@@ -1871,96 +2460,8 @@ in BODY."
        (let ((combine-after-change-calls t))
         . ,body)
      (combine-after-change-execute)))
-
-
-(defvar delay-mode-hooks nil
-  "If non-nil, `run-mode-hooks' should delay running the hooks.")
-(defvar delayed-mode-hooks nil
-  "List of delayed mode hooks waiting to be run.")
-(make-variable-buffer-local 'delayed-mode-hooks)
-(put 'delay-mode-hooks 'permanent-local t)
-
-(defvar after-change-major-mode-hook nil
-  "Normal hook run at the very end of major mode functions.")
-
-(defun run-mode-hooks (&rest hooks)
-  "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
-Execution is delayed if `delay-mode-hooks' is non-nil.
-If `delay-mode-hooks' is nil, run `after-change-major-mode-hook'
-after running the mode hooks.
-Major mode functions should use this."
-  (if delay-mode-hooks
-      ;; Delaying case.
-      (dolist (hook hooks)
-       (push hook delayed-mode-hooks))
-    ;; Normal case, just run the hook as before plus any delayed hooks.
-    (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
-    (setq delayed-mode-hooks nil)
-    (apply 'run-hooks hooks)
-    (run-hooks 'after-change-major-mode-hook)))
-
-(defmacro delay-mode-hooks (&rest body)
-  "Execute BODY, but delay any `run-mode-hooks'.
-These hooks will be executed by the first following call to
-`run-mode-hooks' that occurs outside any `delayed-mode-hooks' form.
-Only affects hooks run in the current buffer."
-  (declare (debug t) (indent 0))
-  `(progn
-     (make-local-variable 'delay-mode-hooks)
-     (let ((delay-mode-hooks t))
-       ,@body)))
-
-;; PUBLIC: find if the current mode derives from another.
-
-(defun derived-mode-p (&rest modes)
-  "Non-nil if the current major mode is derived from one of MODES.
-Uses the `derived-mode-parent' property of the symbol to trace backwards."
-  (let ((parent major-mode))
-    (while (and (not (memq parent modes))
-               (setq parent (get parent 'derived-mode-parent))))
-    parent))
-
-(defun find-tag-default ()
-  "Determine default tag to search for, based on text at point.
-If there is no plausible default, return nil."
-  (save-excursion
-    (while (looking-at "\\sw\\|\\s_")
-      (forward-char 1))
-    (if (or (re-search-backward "\\sw\\|\\s_"
-                               (save-excursion (beginning-of-line) (point))
-                               t)
-           (re-search-forward "\\(\\sw\\|\\s_\\)+"
-                              (save-excursion (end-of-line) (point))
-                              t))
-       (progn
-         (goto-char (match-end 0))
-         (condition-case nil
-             (buffer-substring-no-properties
-              (point)
-              (progn (forward-sexp -1)
-                     (while (looking-at "\\s'")
-                       (forward-char 1))
-                     (point)))
-           (error nil)))
-      nil)))
-
-(defmacro with-syntax-table (table &rest body)
-  "Evaluate BODY with syntax table of current buffer set to TABLE.
-The syntax table of the current buffer is saved, BODY is evaluated, and the
-saved table is restored, even in case of an abnormal exit.
-Value is what BODY returns."
-  (declare (debug t))
-  (let ((old-table (make-symbol "table"))
-       (old-buffer (make-symbol "buffer")))
-    `(let ((,old-table (syntax-table))
-          (,old-buffer (current-buffer)))
-       (unwind-protect
-          (progn
-            (set-syntax-table ,table)
-            ,@body)
-        (save-current-buffer
-          (set-buffer ,old-buffer)
-          (set-syntax-table ,old-table))))))
+\f
+;;;; Constructing completion tables.
 
 (defmacro dynamic-completion-table (fun)
   "Use function FUN as a dynamic completion table.
@@ -1988,20 +2489,35 @@ that can be used as the ALIST argument to `try-completion' and
           ((not ,mode) (try-completion ,string (,fun ,string) ,predicate))
           (t (test-completion ,string (,fun ,string) ,predicate)))))))
 
-(defmacro lazy-completion-table (var fun &rest args)
+(defmacro lazy-completion-table (var fun)
+  ;; We used to have `&rest args' where `args' were evaluated late (at the
+  ;; time of the call to `fun'), which was counter intuitive.  But to get
+  ;; them to be evaluated early, we have to either use lexical-let (which is
+  ;; not available in subr.el) or use `(lambda (,str) ...) which prevents the use
+  ;; of lexical-let in the callers.
+  ;; So we just removed the argument.  Callers can then simply use either of:
+  ;;   (lazy-completion-table var (lambda () (fun x y)))
+  ;; or
+  ;;   (lazy-completion-table var `(lambda () (fun ',x ',y)))
+  ;; or
+  ;;   (lexical-let ((x x)) ((y y))
+  ;;     (lazy-completion-table var (lambda () (fun x y))))
+  ;; depending on the behavior they want.
   "Initialize variable VAR as a lazy completion table.
 If the completion table VAR is used for the first time (e.g., by passing VAR
-as an argument to `try-completion'), the function FUN is called with arguments
-ARGS.  FUN must return the completion table that will be stored in VAR.
+as an argument to `try-completion'), the function FUN is called with no
+arguments.  FUN must return the completion table that will be stored in VAR.
 If completion is requested in the minibuffer, FUN will be called in the buffer
 from which the minibuffer was entered.  The return value of
-`lazy-completion-table' must be used to initialize the value of VAR."
-  (declare (debug (symbol lambda-expr def-body)))
+`lazy-completion-table' must be used to initialize the value of VAR.
+
+You should give VAR a non-nil `risky-local-variable' property."
+  (declare (debug (symbol lambda-expr)))
   (let ((str (make-symbol "string")))
     `(dynamic-completion-table
       (lambda (,str)
-        (unless (listp ,var)
-          (setq ,var (,fun ,@args)))
+        (when (functionp ,var)
+          (setq ,var (,fun)))
         ,var))))
 
 (defmacro complete-in-turn (a b)
@@ -2020,7 +2536,7 @@ A and B should not be costly (or side-effecting) expressions."
        (or (test-completion string ,a predicate)
           (test-completion string ,b predicate))))))
 \f
-;;; Matching and substitution
+;;; Matching and match data.
 
 (defvar save-match-data-internal)
 
@@ -2070,8 +2586,9 @@ STRING should be given if the last search was by `string-match' on STRING."
 (defun looking-back (regexp &optional limit greedy)
   "Return non-nil if text before point matches regular expression REGEXP.
 Like `looking-at' except matches before point, and is slower.
-LIMIT if non-nil speeds up the search by specifying how far back the
-match can start.
+LIMIT if non-nil speeds up the search by specifying a minimum
+starting position, to avoid checking matches that would start
+before LIMIT.
 
 If GREEDY is non-nil, extend the match backwards as far as possible,
 stopping when a single additional previous character cannot be part
@@ -2095,6 +2612,47 @@ of a match for REGEXP."
            (looking-at (concat "\\(?:"  regexp "\\)\\'")))))
     (not (null pos))))
 
+(defun subregexp-context-p (regexp pos &optional start)
+  "Return non-nil if POS is in a normal subregexp context in REGEXP.
+A subregexp context is one where a sub-regexp can appear.
+A non-subregexp context is for example within brackets, or within a
+repetition bounds operator `\\=\\{...\\}', or right after a `\\'.
+If START is non-nil, it should be a position in REGEXP, smaller
+than POS, and known to be in a subregexp context."
+  ;; Here's one possible implementation, with the great benefit that it
+  ;; reuses the regexp-matcher's own parser, so it understands all the
+  ;; details of the syntax.  A disadvantage is that it needs to match the
+  ;; error string.
+  (condition-case err
+      (progn
+        (string-match (substring regexp (or start 0) pos) "")
+        t)
+    (invalid-regexp
+     (not (member (cadr err) '("Unmatched [ or [^"
+                               "Unmatched \\{"
+                               "Trailing backslash")))))
+  ;; An alternative implementation:
+  ;; (defconst re-context-re
+  ;;   (let* ((harmless-ch "[^\\[]")
+  ;;          (harmless-esc "\\\\[^{]")
+  ;;          (class-harmless-ch "[^][]")
+  ;;          (class-lb-harmless "[^]:]")
+  ;;          (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?")
+  ;;          (class-lb (concat "\\[\\(" class-lb-harmless
+  ;;                            "\\|" class-lb-colon-maybe-charclass "\\)"))
+  ;;          (class
+  ;;           (concat "\\[^?]?"
+  ;;                   "\\(" class-harmless-ch
+  ;;                   "\\|" class-lb "\\)*"
+  ;;                   "\\[?]"))     ; special handling for bare [ at end of re
+  ;;          (braces "\\\\{[0-9,]+\\\\}"))
+  ;;     (concat "\\`\\(" harmless-ch "\\|" harmless-esc
+  ;;             "\\|" class "\\|" braces "\\)*\\'"))
+  ;;   "Matches any prefix that corresponds to a normal subregexp context.")
+  ;; (string-match re-context-re (substring regexp (or start 0) pos))
+  )
+\f
+;;;; split-string
 
 (defconst split-string-default-separators "[ \f\t\n\r\v]+"
   "The default value of separators for `split-string'.
@@ -2155,6 +2713,8 @@ Modifies the match data; use `save-match-data' if necessary."
              (cons (substring string start)
                    list)))
     (nreverse list)))
+\f
+;;;; Replacement in strings.
 
 (defun subst-char-in-string (fromchar tochar string &optional inplace)
   "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
@@ -2224,76 +2784,42 @@ and replace a sub-expression, e.g.
       ;; Reconstruct a string from the pieces.
       (setq matches (cons (substring string start l) matches)) ; leftover
       (apply #'concat (nreverse matches)))))
+\f
+;;;; invisibility specs
 
-(defun subregexp-context-p (regexp pos &optional start)
-  "Return non-nil if POS is in a normal subregexp context in REGEXP.
-A subregexp context is one where a sub-regexp can appear.
-A non-subregexp context is for example within brackets, or within a
-repetition bounds operator `\\=\\{...\\}', or right after a `\\'.
-If START is non-nil, it should be a position in REGEXP, smaller
-than POS, and known to be in a subregexp context."
-  ;; Here's one possible implementation, with the great benefit that it
-  ;; reuses the regexp-matcher's own parser, so it understands all the
-  ;; details of the syntax.  A disadvantage is that it needs to match the
-  ;; error string.
-  (condition-case err
-      (progn
-        (string-match (substring regexp (or start 0) pos) "")
-        t)
-    (invalid-regexp
-     (not (member (cadr err) '("Unmatched [ or [^"
-                               "Unmatched \\{"
-                               "Trailing backslash")))))
-  ;; An alternative implementation:
-  ;; (defconst re-context-re
-  ;;   (let* ((harmless-ch "[^\\[]")
-  ;;          (harmless-esc "\\\\[^{]")
-  ;;          (class-harmless-ch "[^][]")
-  ;;          (class-lb-harmless "[^]:]")
-  ;;          (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?")
-  ;;          (class-lb (concat "\\[\\(" class-lb-harmless
-  ;;                            "\\|" class-lb-colon-maybe-charclass "\\)"))
-  ;;          (class
-  ;;           (concat "\\[^?]?"
-  ;;                   "\\(" class-harmless-ch
-  ;;                   "\\|" class-lb "\\)*"
-  ;;                   "\\[?]"))     ; special handling for bare [ at end of re
-  ;;          (braces "\\\\{[0-9,]+\\\\}"))
-  ;;     (concat "\\`\\(" harmless-ch "\\|" harmless-esc
-  ;;             "\\|" class "\\|" braces "\\)*\\'"))
-  ;;   "Matches any prefix that corresponds to a normal subregexp context.")
-  ;; (string-match re-context-re (substring regexp (or start 0) pos))
-  )
+(defun add-to-invisibility-spec (element)
+  "Add ELEMENT to `buffer-invisibility-spec'.
+See documentation for `buffer-invisibility-spec' for the kind of elements
+that can be added."
+  (if (eq buffer-invisibility-spec t)
+      (setq buffer-invisibility-spec (list t)))
+  (setq buffer-invisibility-spec
+       (cons element buffer-invisibility-spec)))
+
+(defun remove-from-invisibility-spec (element)
+  "Remove ELEMENT from `buffer-invisibility-spec'."
+  (if (consp buffer-invisibility-spec)
+    (setq buffer-invisibility-spec (delete element buffer-invisibility-spec))))
 \f
-(defun shell-quote-argument (argument)
-  "Quote an argument for passing as argument to an inferior shell."
-  (if (eq system-type 'ms-dos)
-      ;; Quote using double quotes, but escape any existing quotes in
-      ;; the argument with backslashes.
-      (let ((result "")
-           (start 0)
-           end)
-       (if (or (null (string-match "[^\"]" argument))
-               (< (match-end 0) (length argument)))
-           (while (string-match "[\"]" argument start)
-             (setq end (match-beginning 0)
-                   result (concat result (substring argument start end)
-                                  "\\" (substring argument end (1+ end)))
-                   start (1+ end))))
-       (concat "\"" result (substring argument start) "\""))
-    (if (eq system-type 'windows-nt)
-       (concat "\"" argument "\"")
-      (if (equal argument "")
-         "''"
-       ;; Quote everything except POSIX filename characters.
-       ;; This should be safe enough even for really weird shells.
-       (let ((result "") (start 0) end)
-         (while (string-match "[^-0-9a-zA-Z_./]" argument start)
-           (setq end (match-beginning 0)
-                 result (concat result (substring argument start end)
-                                "\\" (substring argument end (1+ end)))
-                 start (1+ end)))
-         (concat result (substring argument start)))))))
+;;;; Syntax tables.
+
+(defmacro with-syntax-table (table &rest body)
+  "Evaluate BODY with syntax table of current buffer set to TABLE.
+The syntax table of the current buffer is saved, BODY is evaluated, and the
+saved table is restored, even in case of an abnormal exit.
+Value is what BODY returns."
+  (declare (debug t))
+  (let ((old-table (make-symbol "table"))
+       (old-buffer (make-symbol "buffer")))
+    `(let ((,old-table (syntax-table))
+          (,old-buffer (current-buffer)))
+       (unwind-protect
+          (progn
+            (set-syntax-table ,table)
+            ,@body)
+        (save-current-buffer
+          (set-buffer ,old-buffer)
+          (set-syntax-table ,old-table))))))
 
 (defun make-syntax-table (&optional oldtable)
   "Return a new syntax table.
@@ -2316,247 +2842,8 @@ If POS is outside the buffer's accessible portion, return nil."
   "Return the syntax class part of the syntax descriptor SYNTAX.
 If SYNTAX is nil, return nil."
   (and syntax (logand (car syntax) 65535)))
-
-(defun add-to-invisibility-spec (element)
-  "Add ELEMENT to `buffer-invisibility-spec'.
-See documentation for `buffer-invisibility-spec' for the kind of elements
-that can be added."
-  (if (eq buffer-invisibility-spec t)
-      (setq buffer-invisibility-spec (list t)))
-  (setq buffer-invisibility-spec
-       (cons element buffer-invisibility-spec)))
-
-(defun remove-from-invisibility-spec (element)
-  "Remove ELEMENT from `buffer-invisibility-spec'."
-  (if (consp buffer-invisibility-spec)
-    (setq buffer-invisibility-spec (delete element buffer-invisibility-spec))))
-\f
-(defun global-set-key (key command)
-  "Give KEY a global binding as COMMAND.
-COMMAND is the command definition to use; usually it is
-a symbol naming an interactively-callable function.
-KEY is a key sequence; noninteractively, it is a string or vector
-of characters or event types, and non-ASCII characters with codes
-above 127 (such as ISO Latin-1) can be included if you use a vector.
-
-Note that if KEY has a local binding in the current buffer,
-that local binding will continue to shadow any global binding
-that you make with this function."
-  (interactive "KSet key globally: \nCSet key %s to command: ")
-  (or (vectorp key) (stringp key)
-      (signal 'wrong-type-argument (list 'arrayp key)))
-  (define-key (current-global-map) key command))
-
-(defun local-set-key (key command)
-  "Give KEY a local binding as COMMAND.
-COMMAND is the command definition to use; usually it is
-a symbol naming an interactively-callable function.
-KEY is a key sequence; noninteractively, it is a string or vector
-of characters or event types, and non-ASCII characters with codes
-above 127 (such as ISO Latin-1) can be included if you use a vector.
-
-The binding goes in the current buffer's local map,
-which in most cases is shared with all other buffers in the same major mode."
-  (interactive "KSet key locally: \nCSet key %s locally to command: ")
-  (let ((map (current-local-map)))
-    (or map
-       (use-local-map (setq map (make-sparse-keymap))))
-    (or (vectorp key) (stringp key)
-       (signal 'wrong-type-argument (list 'arrayp key)))
-    (define-key map key command)))
-
-(defun global-unset-key (key)
-  "Remove global binding of KEY.
-KEY is a string or vector representing a sequence of keystrokes."
-  (interactive "kUnset key globally: ")
-  (global-set-key key nil))
-
-(defun local-unset-key (key)
-  "Remove local binding of KEY.
-KEY is a string or vector representing a sequence of keystrokes."
-  (interactive "kUnset key locally: ")
-  (if (current-local-map)
-      (local-set-key key nil))
-  nil)
 \f
-;; We put this here instead of in frame.el so that it's defined even on
-;; systems where frame.el isn't loaded.
-(defun frame-configuration-p (object)
-  "Return non-nil if OBJECT seems to be a frame configuration.
-Any list whose car is `frame-configuration' is assumed to be a frame
-configuration."
-  (and (consp object)
-       (eq (car object) 'frame-configuration)))
-
-(defun functionp (object)
-  "Non-nil if OBJECT is any kind of function or a special form.
-Also non-nil if OBJECT is a symbol and its function definition is
-\(recursively) a function or special form.  This does not include
-macros."
-  (or (and (symbolp object) (fboundp object)
-          (condition-case nil
-              (setq object (indirect-function object))
-            (error nil))
-          (eq (car-safe object) 'autoload)
-          (not (car-safe (cdr-safe (cdr-safe (cdr-safe (cdr-safe object)))))))
-      (subrp object) (byte-code-function-p object)
-      (eq (car-safe object) 'lambda)))
-
-(defun assq-delete-all (key alist)
-  "Delete from ALIST all elements whose car is `eq' to KEY.
-Return the modified alist.
-Elements of ALIST that are not conses are ignored."
-  (while (and (consp (car alist))
-             (eq (car (car alist)) key))
-    (setq alist (cdr alist)))
-  (let ((tail alist) tail-cdr)
-    (while (setq tail-cdr (cdr tail))
-      (if (and (consp (car tail-cdr))
-              (eq (car (car tail-cdr)) key))
-         (setcdr tail (cdr tail-cdr))
-       (setq tail tail-cdr))))
-  alist)
-
-(defun rassq-delete-all (value alist)
-  "Delete from ALIST all elements whose cdr is `eq' to VALUE.
-Return the modified alist.
-Elements of ALIST that are not conses are ignored."
-  (while (and (consp (car alist))
-             (eq (cdr (car alist)) value))
-    (setq alist (cdr alist)))
-  (let ((tail alist) tail-cdr)
-    (while (setq tail-cdr (cdr tail))
-      (if (and (consp (car tail-cdr))
-              (eq (cdr (car tail-cdr)) value))
-         (setcdr tail (cdr tail-cdr))
-       (setq tail tail-cdr))))
-  alist)
-
-(defun make-temp-file (prefix &optional dir-flag suffix)
-  "Create a temporary file.
-The returned file name (created by appending some random characters at the end
-of PREFIX, and expanding against `temporary-file-directory' if necessary),
-is guaranteed to point to a newly created empty file.
-You can then use `write-region' to write new data into the file.
-
-If DIR-FLAG is non-nil, create a new empty directory instead of a file.
-
-If SUFFIX is non-nil, add that at the end of the file name."
-  (let ((umask (default-file-modes))
-       file)
-    (unwind-protect
-       (progn
-         ;; Create temp files with strict access rights.  It's easy to
-         ;; loosen them later, whereas it's impossible to close the
-         ;; time-window of loose permissions otherwise.
-         (set-default-file-modes ?\700)
-         (while (condition-case ()
-                    (progn
-                      (setq file
-                            (make-temp-name
-                             (expand-file-name prefix temporary-file-directory)))
-                      (if suffix
-                          (setq file (concat file suffix)))
-                      (if dir-flag
-                          (make-directory file)
-                        (write-region "" nil file nil 'silent nil 'excl))
-                      nil)
-                  (file-already-exists t))
-           ;; the file was somehow created by someone else between
-           ;; `make-temp-name' and `write-region', let's try again.
-           nil)
-         file)
-      ;; Reset the umask.
-      (set-default-file-modes umask))))
-
-\f
-;; If a minor mode is not defined with define-minor-mode,
-;; add it here explicitly.
-;; isearch-mode is deliberately excluded, since you should
-;; not call it yourself.
-(defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
-                                        overwrite-mode view-mode
-                                         hs-minor-mode)
-  "List of all minor mode functions.")
-
-(defun add-minor-mode (toggle name &optional keymap after toggle-fun)
-  "Register a new minor mode.
-
-This is an XEmacs-compatibility function.  Use `define-minor-mode' instead.
-
-TOGGLE is a symbol which is the name of a buffer-local variable that
-is toggled on or off to say whether the minor mode is active or not.
-
-NAME specifies what will appear in the mode line when the minor mode
-is active.  NAME should be either a string starting with a space, or a
-symbol whose value is such a string.
-
-Optional KEYMAP is the keymap for the minor mode that will be added
-to `minor-mode-map-alist'.
-
-Optional AFTER specifies that TOGGLE should be added after AFTER
-in `minor-mode-alist'.
-
-Optional TOGGLE-FUN is an interactive function to toggle the mode.
-It defaults to (and should by convention be) TOGGLE.
-
-If TOGGLE has a non-nil `:included' property, an entry for the mode is
-included in the mode-line minor mode menu.
-If TOGGLE has a `:menu-tag', that is used for the menu item's label."
-  (unless (memq toggle minor-mode-list)
-    (push toggle minor-mode-list))
-
-  (unless toggle-fun (setq toggle-fun toggle))
-  (unless (eq toggle-fun toggle)
-    (put toggle :minor-mode-function toggle-fun))
-  ;; Add the name to the minor-mode-alist.
-  (when name
-    (let ((existing (assq toggle minor-mode-alist)))
-      (if existing
-         (setcdr existing (list name))
-       (let ((tail minor-mode-alist) found)
-         (while (and tail (not found))
-           (if (eq after (caar tail))
-               (setq found tail)
-             (setq tail (cdr tail))))
-         (if found
-             (let ((rest (cdr found)))
-               (setcdr found nil)
-               (nconc found (list (list toggle name)) rest))
-           (setq minor-mode-alist (cons (list toggle name)
-                                        minor-mode-alist)))))))
-  ;; Add the toggle to the minor-modes menu if requested.
-  (when (get toggle :included)
-    (define-key mode-line-mode-menu
-      (vector toggle)
-      (list 'menu-item
-           (concat
-            (or (get toggle :menu-tag)
-                (if (stringp name) name (symbol-name toggle)))
-            (let ((mode-name (if (symbolp name) (symbol-value name))))
-              (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
-                  (concat " (" (match-string 0 mode-name) ")"))))
-           toggle-fun
-           :button (cons :toggle toggle))))
-
-  ;; Add the map to the minor-mode-map-alist.
-  (when keymap
-    (let ((existing (assq toggle minor-mode-map-alist)))
-      (if existing
-         (setcdr existing keymap)
-       (let ((tail minor-mode-map-alist) found)
-         (while (and tail (not found))
-           (if (eq after (caar tail))
-               (setq found tail)
-             (setq tail (cdr tail))))
-         (if found
-             (let ((rest (cdr found)))
-               (setcdr found nil)
-               (nconc found (list (cons toggle keymap)) rest))
-           (setq minor-mode-map-alist (cons (cons toggle keymap)
-                                            minor-mode-map-alist))))))))
-\f
-;; Clones ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;; Text clones
 
 (defun text-clone-maintain (ol1 after beg end &optional len)
   "Propagate the changes made under the overlay OL1 to the other clones.
@@ -2650,27 +2937,11 @@ clone should be incorporated in the clone."
     ;;(overlay-put ol2 'face 'underline)
     (overlay-put ol2 'evaporate t)
     (overlay-put ol2 'text-clones dups)))
+\f
+;;;; Mail user agents.
 
-(defun play-sound (sound)
-  "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
-The following keywords are recognized:
-
-  :file FILE - read sound data from FILE.  If FILE isn't an
-absolute file name, it is searched in `data-directory'.
-
-  :data DATA - read sound data from string DATA.
-
-Exactly one of :file or :data must be present.
-
-  :volume VOL - set volume to VOL.  VOL must an integer in the
-range 0..100 or a float in the range 0..1.0.  If not specified,
-don't change the volume setting of the sound device.
-
-  :device DEVICE - play sound on DEVICE.  If not specified,
-a system-dependent default device name is used."
-  (if (fboundp 'play-sound-internal)
-      (play-sound-internal sound)
-    (error "This Emacs binary lacks sound support")))
+;; Here we include just enough for other packages to be able
+;; to define them.
 
 (defun define-mail-user-agent (symbol composefunc sendfunc
                                      &optional abortfunc hookvar)
@@ -2706,8 +2977,8 @@ The properties used on SYMBOL are `composefunc', `sendfunc',
   (put symbol 'sendfunc sendfunc)
   (put symbol 'abortfunc (or abortfunc 'kill-buffer))
   (put symbol 'hookvar (or hookvar 'mail-send-hook)))
-
-;; Standardized progress reporting
+\f
+;;;; Progress reporters.
 
 ;; Progress reporter has the following structure:
 ;;
@@ -2864,7 +3135,7 @@ convenience wrapper around `make-progress-reporter' and friends.
        nil ,@(cdr (cdr spec)))))
 
 \f
-;;;; Compare Version Strings
+;;;; Comparing version strings.
 
 (defvar version-separator "."
   "*Specify the string used to separate the version elements.
@@ -2873,11 +3144,11 @@ Usually the separator is \".\", but it can be any other string.")
 
 
 (defvar version-regexp-alist
-  '(("^[-_+]?a\\(lpha\\)?$"   . -3)
-    ("^[-_+]$" . -3)   ; treat "1.2.3-20050920" and "1.2-3" as alpha releases
-    ("^[-_+]cvs$" . -3)        ; treat "1.2.3-CVS" as alpha release
-    ("^[-_+]?b\\(eta\\)?$"    . -2)
-    ("^[-_+]?\\(pre\\|rc\\)$" . -1))
+  '(("^[-_+ ]?a\\(lpha\\)?$"   . -3)
+    ("^[-_+]$"                 . -3)   ; treat "1.2.3-20050920" and "1.2-3" as alpha releases
+    ("^[-_+ ]cvs$"             . -3)   ; treat "1.2.3-CVS" as alpha release
+    ("^[-_+ ]?b\\(eta\\)?$"    . -2)
+    ("^[-_+ ]?\\(pre\\|rc\\)$" . -1))
   "*Specify association between non-numeric version part and a priority.
 
 This association is used to handle version string like \"1.0pre2\",
@@ -2888,10 +3159,10 @@ non-numeric part to an integer.  For example:
    \"1.0pre2\"         (1  0 -1 2)
    \"1.0PRE2\"         (1  0 -1 2)
    \"22.8beta3\"       (22 8 -2 3)
-   \"22.8Beta3\"       (22 8 -2 3)
+   \"22.8 Beta3\"      (22 8 -2 3)
    \"0.9alpha1\"       (0  9 -3 1)
    \"0.9AlphA1\"       (0  9 -3 1)
-   \"0.9alpha\"        (0  9 -3)
+   \"0.9 alpha\"       (0  9 -3)
 
 Each element has the following form:
 
@@ -2943,8 +3214,13 @@ As an example of version convertion:
    \"0.9alpha\"        (0  9 -3)
 
 See documentation for `version-separator' and `version-regexp-alist'."
-  (or (and (stringp ver) (not (string= ver "")))
+  (or (and (stringp ver) (> (length ver) 0))
       (error "Invalid version string: '%s'" ver))
+  ;; Change .x.y to 0.x.y
+  (if (and (>= (length ver) (length version-separator))
+          (string-equal (substring ver 0 (length version-separator))
+                   version-separator))
+      (setq ver (concat "0" ver)))
   (save-match-data
     (let ((i 0)
          (case-fold-search t)          ; ignore case in matching