gnus.texi (Adaptive Scoring): Fix typo.
[bpt/emacs.git] / lisp / emacs-lisp / package.el
index c603544..c1c4e2b 100644 (file)
@@ -43,9 +43,6 @@
 ;; currently register any of these, so this feature does not actually
 ;; work.)
 
-;; This code supports a single package repository, ELPA.  All packages
-;; must be registered there.
-
 ;; A package is described by its name and version.  The distribution
 ;; format is either  a tar file or a single .el file.
 
 ;; which consists of a call to define-package.  It may also contain a
 ;; "dir" file and the info files it references.
 
-;; A .el file will be named "NAME-VERSION.el" in ELPA, but will be
+;; A .el file is named "NAME-VERSION.el" in the remote archive, but is
 ;; installed as simply "NAME.el" in a directory named "NAME-VERSION".
 
-;; The downloader will download all dependent packages.  It will also
-;; byte-compile the package's lisp at install time.
+;; The downloader downloads all dependent packages.  By default,
+;; packages come from the official GNU sources, but others may be
+;; added by customizing the `package-archives' alist.  Packages get
+;; byte-compiled at install time.
 
 ;; At activation time we will set up the load-path and the info path,
 ;; and we will load the package's autoloads.  If a package's
@@ -207,6 +206,7 @@ If VERSION is a string, only that version is ever loaded.
  Hence, the package is \"held\" at that version.
 If VERSION is nil, the package is not loaded (it is \"disabled\")."
   :type '(repeat symbol)
+  :risky t
   :group 'package
   :version "24.1")
 
@@ -216,11 +216,18 @@ If VERSION is nil, the package is not loaded (it is \"disabled\")."
 (declare-function lm-header "lisp-mnt" (header))
 (declare-function lm-commentary "lisp-mnt" (&optional file))
 (declare-function dired-delete-file "dired" (file &optional recursive trash))
-
-(defconst package-archive-base "http://elpa.gnu.org/packages/"
-  "Base URL for the Emacs Lisp Package Archive (ELPA).
-Ordinarily you should not need to change this.
-Note that some code in package.el assumes that this is an http: URL.")
+(defvar url-http-end-of-headers)
+
+(defcustom package-archives '(("gnu" . "http://elpa.gnu.org/packages/"))
+  "An alist of archives from which to fetch.
+The default value points to the GNU Emacs package repository.
+Each element has the form (ID . URL), where ID is an identifier
+string for an archive and URL is a http: URL (a string)."
+  :type '(alist :key-type (string :tag "Archive name")
+                :value-type (string :tag "Archive URL"))
+  :risky t
+  :group 'package
+  :version "24.1")
 
 (defconst package-archive-version 1
   "Version number of the package archive understood by this file.
@@ -234,8 +241,10 @@ Lower version numbers than this will probably be understood as well.")
   "Cache of the contents of the Emacs Lisp Package Archive.
 This is an alist mapping package names (symbols) to package
 descriptor vectors.  These are like the vectors for `package-alist'
-but have an extra entry which is 'tar for tar packages and
-'single for single-file packages.")
+but have extra entries: one which is 'tar for tar packages and
+'single for single-file packages, and one which is the name of
+the archive from which it came.")
+(put 'package-archive-contents 'risky-local-variable t)
 
 (defcustom package-user-dir (locate-user-emacs-file "elpa")
   "Directory containing the user's Emacs Lisp packages.
@@ -243,6 +252,7 @@ The directory name should be absolute.
 Apart from this directory, Emacs also looks for system-wide
 packages in `package-directory-list'."
   :type 'directory
+  :risky t
   :group 'package
   :version "24.1")
 
@@ -259,57 +269,47 @@ Each directory name should be absolute.
 These directories contain packages intended for system-wide; in
 contrast, `package-user-dir' contains packages for personal use."
   :type '(repeat directory)
+  :risky t
   :group 'package
   :version "24.1")
 
-(defun package-version-split (string)
-  "Split a package string into a version list."
-  (mapcar 'string-to-int (split-string string "[.]")))
-
-(defconst package--builtins-base
-  ;; We use package-version split here to make sure to pick up the
-  ;; minor version.
-  `((emacs . [,(package-version-split emacs-version) nil
-             "GNU Emacs"])
-    (package . [,(package-version-split package-el-version)
-               nil "Simple package system for GNU Emacs"]))
-  "Packages which are always built-in.")
-
-(defvar package--builtins
-  (delq nil
-       (append
-        package--builtins-base
-        (if (>= emacs-major-version 22)
-            ;; FIXME: emacs 22 includes tramp, rcirc, maybe
-            ;; other things...
-            '((erc . [(5 2) nil "An Emacs Internet Relay Chat client"])
-              ;; The external URL is version 1.15, so make sure the
-              ;; built-in one looks newer.
-              (url . [(1 16) nil "URL handling libary"])))
-        (if (>= emacs-major-version 23)
-            '(;; Strangely, nxml-version is missing in Emacs 23.
-              ;; We pick the merge date as the version.
-              (nxml . [(20071123) nil "Major mode for editing XML documents."])
-              (bubbles . [(0 5) nil "Puzzle game for Emacs."])))))
-  "Alist of all built-in packages.
-Maps the package name to a vector [VERSION REQS DOCSTRING].")
-
-(defvar package-alist package--builtins
+;; The value is precomputed in finder-inf.el, but don't load that
+;; until it's needed (i.e. when `package-intialize' is called).
+(defvar package--builtins nil
+  "Alist of built-in packages.
+Each element has the form (PKG . DESC), where PKG is a package
+name (a symbol) and DESC is a vector that describes the package.
+
+The vector DESC has the form [VERSION REQS DOCSTRING].
+  VERSION is a version list.
+  REQS is a list of packages (symbols) required by the package.
+  DOCSTRING is a brief description of the package.")
+(put 'package--builtins 'risky-local-variable t)
+
+(defvar package-alist nil
   "Alist of all packages available for activation.
-This maps the package name to a vector [VERSION REQS DOCSTRING].
+Each element has the form (PKG . DESC), where PKG is a package
+name (a symbol) and DESC is a vector that describes the package.
+
+The vector DESC has the form [VERSION REQS DOCSTRING].
+  VERSION is a version list.
+  REQS is a list of packages (symbols) required by the package.
+  DOCSTRING is a brief description of the package.
 
-The value is generated by `package-load-descriptor', usually
-called via `package-initialize'.  For user customizations of
-which packages to load/activate, see `package-load-list'.")
+This variable is set automatically by `package-load-descriptor',
+called via `package-initialize'.  To change which packages are
+loaded and/or activated, customize `package-load-list'.")
+(put 'package-archive-contents 'risky-local-variable t)
 
-(defvar package-activated-list
-  (mapcar #'car package-alist)
+(defvar package-activated-list nil
   "List of the names of currently activated packages.")
+(put 'package-activated-list 'risky-local-variable t)
 
 (defvar package-obsolete-alist nil
   "Representation of obsolete packages.
 Like `package-alist', but maps package name to a second alist.
 The inner alist is keyed by version.")
+(put 'package-obsolete-alist 'risky-local-variable t)
 
 (defconst package-subdirectory-regexp
   "^\\([^.].*\\)-\\([0-9]+\\(?:[.][0-9]+\\)*\\)$"
@@ -321,39 +321,6 @@ The second subexpression is the version string.")
   "Turn a list of version numbers into a version string."
   (mapconcat 'int-to-string l "."))
 
-(defun package--version-first-nonzero (l)
-  (while (and l (= (car l) 0))
-    (setq l (cdr l)))
-  (if l (car l) 0))
-
-(defun package-version-compare (v1 v2 fun)
-  "Compare two version lists according to FUN.
-FUN can be <, <=, =, >, >=, or /=."
-  (while (and v1 v2 (= (car v1) (car v2)))
-    (setq v1 (cdr v1)
-         v2 (cdr v2)))
-  (if v1
-      (if v2
-         ;; Both not null; we know the cars are not =.
-         (funcall fun (car v1) (car v2))
-       ;; V1 not null, V2 null.
-       (funcall fun (package--version-first-nonzero v1) 0))
-    (if v2
-       ;; V1 null, V2 not null.
-       (funcall fun 0 (package--version-first-nonzero v2))
-      ;; Both null.
-      (funcall fun 0 0))))
-
-(defun package--test-version-compare ()
-  "Test suite for `package-version-compare'."
-  (unless (and (package-version-compare '(0) '(0) '=)
-              (not (package-version-compare '(1) '(0) '=))
-              (package-version-compare '(1 0 1) '(1) '>=)
-              (package-version-compare '(1 0 1) '(1) '>)
-              (not (package-version-compare '(0 9 1) '(1 0 2) '>=)))
-    (error "Failed"))
-  t)
-
 (defun package-strip-version (dirname)
   "Strip the version from a combined package name and version.
 E.g., if given \"quux-23.0\", will return \"quux\""
@@ -361,16 +328,14 @@ E.g., if given \"quux-23.0\", will return \"quux\""
       (match-string 1 dirname)))
 
 (defun package-load-descriptor (dir package)
-  "Load the description file for a package.
-DIR is the directory in which to find the package subdirectory,
-and PACKAGE is the name of the package subdirectory.
-Return nil if the package could not be found."
-  (let ((pkg-dir (expand-file-name package dir)))
-    (if (file-directory-p pkg-dir)
-       (load (expand-file-name (concat (package-strip-version package)
-                                       "-pkg")
-                               pkg-dir)
-             nil t))))
+  "Load the description file in directory DIR for package PACKAGE."
+  (let* ((pkg-dir (expand-file-name package dir))
+        (pkg-file (expand-file-name
+                   (concat (package-strip-version package) "-pkg")
+                   pkg-dir)))
+    (when (and (file-directory-p pkg-dir)
+              (file-exists-p (concat pkg-file ".el")))
+      (load pkg-file nil t))))
 
 (defun package-load-all-descriptors ()
   "Load descriptors for installed Emacs Lisp packages.
@@ -399,9 +364,8 @@ updates `package-alist' and `package-obsolete-alist'."
                   ((eq force t)
                    t)
                   ((stringp force) ; held
-                   (package-version-compare (package-version-split version)
-                                            (package-version-split force)
-                                            '=))
+                   (version-list-= (version-to-list version)
+                                   (version-to-list force)))
                   (t
                    (error "Invalid element in `package-load-list'")))
              (package-load-descriptor dir subdir))))))))
@@ -458,8 +422,7 @@ updates `package-alist' and `package-obsolete-alist'."
 (defun package--built-in (package version)
   "Return true if the package is built-in to Emacs."
   (let ((elt (assq package package--builtins)))
-    (and elt
-        (package-version-compare (package-desc-vers (cdr elt)) version '=))))
+    (and elt (version-list-= (package-desc-vers (cdr elt)) version))))
 
 ;; FIXME: return a reason instead?
 (defun package-activate (package version)
@@ -477,7 +440,7 @@ Return nil if the package could not be activated."
           (req-list (package-desc-reqs (cdr pkg-desc)))
           ;; If the package was never activated, do it now.
           (keep-going (or (not (memq package package-activated-list))
-                          (package-version-compare this-version version '>))))
+                          (version-list-< version this-version))))
       (while (and req-list keep-going)
        (let* ((req (car req-list))
               (req-name (car req))
@@ -491,7 +454,7 @@ Return nil if the package could not be activated."
        ;; can also get here if the requested package was already
        ;; activated.  Return non-nil in the latter case.
        (and (memq package package-activated-list)
-            (package-version-compare this-version version '>=))))))
+            (version-list-<= version this-version))))))
 
 (defun package-mark-obsolete (package pkg-vec)
   "Put package on the obsolete list, if not already there."
@@ -508,34 +471,34 @@ Return nil if the package could not be activated."
                                            pkg-vec)))
                  package-obsolete-alist)))))
 
-;; (define-package "emacs" "21.4.1" "GNU Emacs core package.")
-;; (define-package "erc" "5.1" "ERC - irc client" '((emacs "21.0")))
 (defun define-package (name-str version-string
-                               &optional docstring requirements)
+                               &optional docstring requirements
+                               &rest extra-properties)
   "Define a new package.
 NAME is the name of the package, a string.
 VERSION-STRING is the version of the package, a dotted sequence
 of integers.
 DOCSTRING is the optional description.
 REQUIREMENTS is a list of requirements on other packages.
-Each requirement is of the form (OTHER-PACKAGE \"VERSION\")."
+Each requirement is of the form (OTHER-PACKAGE \"VERSION\").
+
+EXTRA-PROPERTIES is currently unused."
   (let* ((name (intern name-str))
         (pkg-desc (assq name package-alist))
-        (new-version (package-version-split version-string))
+        (new-version (version-to-list version-string))
         (new-pkg-desc
          (cons name
                (vector new-version
                        (mapcar
                         (lambda (elt)
                           (list (car elt)
-                                (package-version-split (car (cdr elt)))))
+                                (version-to-list (car (cdr elt)))))
                         requirements)
                        docstring))))
     ;; Only redefine a package if the redefinition is newer.
     (if (or (not pkg-desc)
-           (package-version-compare new-version
-                                    (package-desc-vers (cdr pkg-desc))
-                                    '>))
+           (version-list-< (package-desc-vers (cdr pkg-desc))
+                           new-version))
        (progn
          (when pkg-desc
            ;; Remove old package and declare it obsolete.
@@ -546,9 +509,8 @@ Each requirement is of the form (OTHER-PACKAGE \"VERSION\")."
       ;; You can have two packages with the same version, for instance
       ;; one in the system package directory and one in your private
       ;; directory.  We just let the first one win.
-      (unless (package-version-compare new-version
-                                      (package-desc-vers (cdr pkg-desc))
-                                      '=)
+      (unless (version-list-= new-version
+                             (package-desc-vers (cdr pkg-desc)))
        ;; The package is born obsolete.
        (package-mark-obsolete (car new-pkg-desc) (cdr new-pkg-desc))))))
 
@@ -613,20 +575,23 @@ Otherwise it uses an external `tar' program.
       (let ((load-path (cons pkg-dir load-path)))
        (byte-recompile-directory pkg-dir 0 t)))))
 
+(defun package--write-file-no-coding (file-name excl)
+  (let ((buffer-file-coding-system 'no-conversion))
+    (write-region (point-min) (point-max) file-name nil nil nil excl)))
+
 (defun package-unpack-single (file-name version desc requires)
   "Install the contents of the current buffer as a package."
   ;; Special case "package".
   (if (string= file-name "package")
-      (write-region (point-min) (point-max)
-                   (expand-file-name (concat file-name ".el")
-                                     package-user-dir)
-                   nil nil nil nil)
+      (package--write-file-no-coding
+       (expand-file-name (concat file-name ".el") package-user-dir)
+       nil)
     (let* ((pkg-dir  (expand-file-name (concat file-name "-" version)
                                       package-user-dir))
           (el-file  (expand-file-name (concat file-name ".el") pkg-dir))
           (pkg-file (expand-file-name (concat file-name "-pkg.el") pkg-dir)))
       (make-directory pkg-dir t)
-      (write-region (point-min) (point-max) el-file nil nil nil 'excl)
+      (package--write-file-no-coding el-file 'excl)
       (let ((print-level nil)
            (print-length nil))
        (write-region
@@ -670,7 +635,7 @@ It will move point to somewhere in the headers."
 (defun package-download-single (name version desc requires)
   "Download and install a single-file package."
   (let ((buffer (url-retrieve-synchronously
-                (concat package-archive-base
+                (concat (package-archive-url name)
                         (symbol-name name) "-" version ".el"))))
     (with-current-buffer buffer
       (package-handle-response)
@@ -683,7 +648,7 @@ It will move point to somewhere in the headers."
 (defun package-download-tar (name version)
   "Download and install a tar package."
   (let ((tar-buffer (url-retrieve-synchronously
-                    (concat package-archive-base
+                    (concat (package-archive-url name)
                             (symbol-name name) "-" version ".tar"))))
     (with-current-buffer tar-buffer
       (package-handle-response)
@@ -692,14 +657,25 @@ It will move point to somewhere in the headers."
       (package-unpack name version)
       (kill-buffer tar-buffer))))
 
-(defun package-installed-p (package version)
+(defun package-installed-p (package &optional min-version)
   (let ((pkg-desc (assq package package-alist)))
     (and pkg-desc
-        (package-version-compare version
-                                 (package-desc-vers (cdr pkg-desc))
-                                 '>=))))
-
-(defun package-compute-transaction (result requirements)
+        (version-list-<= min-version
+                         (package-desc-vers (cdr pkg-desc))))))
+
+(defun package-compute-transaction (package-list requirements)
+  "Return a list of packages to be installed, including PACKAGE-LIST.
+PACKAGE-LIST should be a list of package names (symbols).
+
+REQUIREMENTS should be a list of additional requirements; each
+element in this list should have the form (PACKAGE VERSION),
+where PACKAGE is a package name and VERSION is the required
+version of that package (as a list).
+
+This function recursively computes the requirements of the
+packages in REQUIREMENTS, and returns a list of all the packages
+that must be installed.  Packages that are already installed are
+not included in this list."
   (dolist (elt requirements)
     (let* ((next-pkg (car elt))
           (next-version (cadr elt)))
@@ -715,9 +691,7 @@ It will move point to somewhere in the headers."
                          (symbol-name next-pkg)))
                  ((null (stringp hold))
                   (error "Invalid element in `package-load-list'"))
-                 ((package-version-compare next-version
-                                           (package-version-split hold)
-                                           '>)
+                 ((version-list-< (version-to-list hold) next-version)
                   (error "Package '%s' held at version %s, \
 but version %s required"
                          (symbol-name next-pkg) hold
@@ -725,33 +699,32 @@ but version %s required"
          (unless pkg-desc
            (error "Package '%s' is not available for installation"
                   (symbol-name next-pkg)))
-         (unless (package-version-compare (package-desc-vers (cdr pkg-desc))
-                                          next-version
-                                          '>=)
+         (unless (version-list-<= next-version
+                                  (package-desc-vers (cdr pkg-desc)))
            (error
             "Need package '%s' with version %s, but only %s is available"
             (symbol-name next-pkg) (package-version-join next-version)
             (package-version-join (package-desc-vers (cdr pkg-desc)))))
          ;; Only add to the transaction if we don't already have it.
-         (unless (memq next-pkg result)
-           (setq result (cons next-pkg result)))
-         (setq result
-               (package-compute-transaction result
+         (unless (memq next-pkg package-list)
+           (setq package-list (cons next-pkg package-list)))
+         (setq package-list
+               (package-compute-transaction package-list
                                             (package-desc-reqs
                                              (cdr pkg-desc))))))))
-  result)
+  package-list)
 
 (defun package-read-from-string (str)
   "Read a Lisp expression from STR.
 Signal an error if the entire string was not used."
   (let* ((read-data (read-from-string str))
-          (more-left
-             (condition-case nil
-                       ;; The call to `ignore' suppresses a compiler warning.
-                       (progn (ignore (read-from-string
-                                       (substring str (cdr read-data))))
-                                   t)
-                   (end-of-file nil))))
+        (more-left
+         (condition-case nil
+             ;; The call to `ignore' suppresses a compiler warning.
+             (progn (ignore (read-from-string
+                             (substring str (cdr read-data))))
+                    t)
+           (end-of-file nil))))
     (if more-left
         (error "Can't read whole string")
       (car read-data))))
@@ -761,41 +734,53 @@ Signal an error if the entire string was not used."
 Will return the data from the file, or nil if the file does not exist.
 Will throw an error if the archive version is too new."
   (let ((filename (expand-file-name file package-user-dir)))
-    (if (file-exists-p filename)
-       (with-temp-buffer
-         (insert-file-contents-literally filename)
-         (let ((contents (package-read-from-string
-                          (buffer-substring-no-properties (point-min)
-                                                          (point-max)))))
-           (if (> (car contents) package-archive-version)
-               (error "Package archive version %d is greater than %d - upgrade package.el"
-                      (car contents) package-archive-version))
-           (cdr contents))))))
-
-(defun package-read-archive-contents ()
-  "Re-read `archive-contents' and `builtin-packages', if they exist.
-Set `package-archive-contents' and `package--builtins' if successful.
-Throw an error if the archive version is too new."
-  (let ((archive-contents (package--read-archive-file "archive-contents"))
-       (builtins (package--read-archive-file "builtin-packages")))
-    (if archive-contents
-       ;; Version 1 of 'archive-contents' is identical to our
-       ;; internal representation.
-       (setq package-archive-contents archive-contents))
-    (if builtins
-       ;; Version 1 of 'builtin-packages' is a list where the car is
-       ;; a split emacs version and the cdr is an alist suitable for
-       ;; package--builtins.
-       (let ((our-version (package-version-split emacs-version))
-             (result package--builtins-base))
-         (setq package--builtins
-               (dolist (elt builtins result)
-                 (if (package-version-compare our-version (car elt) '>=)
-                     (setq result (append (cdr elt) result)))))))))
-
-(defun package-download-transaction (transaction)
-  "Download and install all the packages in the given transaction."
-  (dolist (elt transaction)
+    (when (file-exists-p filename)
+      (with-temp-buffer
+       (insert-file-contents-literally filename)
+       (let ((contents (read (current-buffer))))
+         (if (> (car contents) package-archive-version)
+             (error "Package archive version %d is higher than %d"
+                    (car contents) package-archive-version))
+         (cdr contents))))))
+
+(defun package-read-all-archive-contents ()
+  "Re-read `archive-contents', if it exists.
+If successful, set `package-archive-contents'."
+  (dolist (archive package-archives)
+    (package-read-archive-contents (car archive))))
+
+(defun package-read-archive-contents (archive)
+  "Re-read archive contents for ARCHIVE.
+If successful, set the variable `package-archive-contents'.
+If the archive version is too new, signal an error."
+  ;; Version 1 of 'archive-contents' is identical to our internal
+  ;; representation.
+  (let* ((dir (concat "archives/" archive))
+        (contents-file (concat dir "/archive-contents"))
+        contents)
+    (when (setq contents (package--read-archive-file contents-file))
+      (dolist (package contents)
+       (package--add-to-archive-contents package archive)))))
+
+(defun package--add-to-archive-contents (package archive)
+  "Add the PACKAGE from the given ARCHIVE if necessary.
+Also, add the originating archive to the end of the package vector."
+  (let* ((name    (car package))
+         (version (aref (cdr package) 0))
+         (entry   (cons (car package)
+                       (vconcat (cdr package) (vector archive))))
+         (existing-package (cdr (assq name package-archive-contents))))
+    (when (or (not existing-package)
+              (version-list-< (aref existing-package 0) version))
+      (add-to-list 'package-archive-contents entry))))
+
+(defun package-download-transaction (package-list)
+  "Download and install all the packages in PACKAGE-LIST.
+PACKAGE-LIST should be a list of package names (symbols).
+This function assumes that all package requirements in
+PACKAGE-LIST are satisfied, i.e. that PACKAGE-LIST is computed
+using `package-compute-transaction'."
+  (dolist (elt package-list)
     (let* ((desc (cdr (assq elt package-archive-contents)))
           ;; As an exception, if package is "held" in
           ;; `package-load-list', download the held version.
@@ -817,26 +802,21 @@ Throw an error if the archive version is too new."
 (defun package-install (name)
   "Install the package named NAME.
 Interactively, prompt for the package name.
-The package is found on the archive site, see `package-archive-base'."
+The package is found on one of the archives in `package-archives'."
   (interactive
-   (list (progn
-          ;; Make sure we're using the most recent download of the
-          ;; archive.  Maybe we should be updating the archive first?
-          (package-read-archive-contents)
-          (intern (completing-read "Install package: "
-                                   (mapcar (lambda (elt)
-                                             (cons (symbol-name (car elt))
-                                                   nil))
-                                           package-archive-contents)
-                                   nil t)))))
+   (list (intern (completing-read "Install package: "
+                                 (mapcar (lambda (elt)
+                                           (cons (symbol-name (car elt))
+                                                 nil))
+                                         package-archive-contents)
+                                 nil t))))
   (let ((pkg-desc (assq name package-archive-contents)))
     (unless pkg-desc
-      (error "Package '%s' not available for installation"
+      (error "Package '%s' is not available for installation"
             (symbol-name name)))
-    (let ((transaction
-          (package-compute-transaction (list name)
-                                       (package-desc-reqs (cdr pkg-desc)))))
-      (package-download-transaction transaction)))
+    (package-download-transaction
+     (package-compute-transaction (list name)
+                                 (package-desc-reqs (cdr pkg-desc)))))
   ;; Try to activate it.
   (package-initialize))
 
@@ -851,61 +831,60 @@ Otherwise return nil."
            v-str))))
 
 (defun package-buffer-info ()
-  "Return a vector of information about the package in the current buffer.
-The vector looks like [FILENAME REQUIRES DESCRIPTION VERSION COMMENTARY]
-FILENAME is the file name, a string.  It does not have the \".el\" extension.
+  "Return a vector describing the package in the current buffer.
+The vector has the form
+
+   [FILENAME REQUIRES DESCRIPTION VERSION COMMENTARY]
+
+FILENAME is the file name, a string, sans the \".el\" extension.
 REQUIRES is a requires list, or nil.
-DESCRIPTION is the package description (a string).
+DESCRIPTION is the package description, a string.
 VERSION is the version, a string.
 COMMENTARY is the commentary section, a string, or nil if none.
-Throws an exception if the buffer does not contain a conforming package.
-If there is a package, narrows the buffer to the file's boundaries.
-May narrow buffer or move point even on failure."
+
+If the buffer does not contain a conforming package, signal an
+error.  If there is a package, narrow the buffer to the file's
+boundaries."
   (goto-char (point-min))
-  (if (re-search-forward "^;;; \\([^ ]*\\)\\.el --- \\(.*\\)$" nil t)
-      (let ((file-name (match-string 1))
-           (desc (match-string 2))
-           (start (progn (beginning-of-line) (point))))
-       (if (search-forward (concat ";;; " file-name ".el ends here"))
-           (progn
-             ;; Try to include a trailing newline.
-             (forward-line)
-             (narrow-to-region start (point))
-             (require 'lisp-mnt)
-             ;; Use some headers we've invented to drive the process.
-             (let* ((requires-str (lm-header "package-requires"))
-                    (requires (if requires-str
-                                  (package-read-from-string requires-str)))
-                    ;; Prefer Package-Version, because if it is
-                    ;; defined the package author probably wants us
-                    ;; to use it.  Otherwise try Version.
-                    (pkg-version
-                     (or (package-strip-rcs-id (lm-header "package-version"))
-                         (package-strip-rcs-id (lm-header "version"))))
-                    (commentary (lm-commentary)))
-               (unless pkg-version
-                 (error
-                  "Package does not define a usable \"Version\" or \"Package-Version\" header"))
-               ;; Turn string version numbers into list form.
-               (setq requires
-                     (mapcar
-                      (lambda (elt)
-                        (list (car elt)
-                              (package-version-split (car (cdr elt)))))
-                      requires))
-               (set-text-properties 0 (length file-name) nil file-name)
-               (set-text-properties 0 (length pkg-version) nil pkg-version)
-               (set-text-properties 0 (length desc) nil desc)
-               (vector file-name requires desc pkg-version commentary)))
-         (error "Package missing a terminating comment")))
-    (error "No starting comment for package")))
+  (unless (re-search-forward "^;;; \\([^ ]*\\)\\.el --- \\(.*\\)$" nil t)
+    (error "Packages lacks a file header"))
+  (let ((file-name (match-string-no-properties 1))
+       (desc      (match-string-no-properties 2))
+       (start     (line-beginning-position)))
+    (unless (search-forward (concat ";;; " file-name ".el ends here"))
+      (error "Package lacks a terminating comment"))
+    ;; Try to include a trailing newline.
+    (forward-line)
+    (narrow-to-region start (point))
+    (require 'lisp-mnt)
+    ;; Use some headers we've invented to drive the process.
+    (let* ((requires-str (lm-header "package-requires"))
+          (requires (if requires-str
+                        (package-read-from-string requires-str)))
+          ;; Prefer Package-Version; if defined, the package author
+          ;; probably wants us to use it.  Otherwise try Version.
+          (pkg-version
+           (or (package-strip-rcs-id (lm-header "package-version"))
+               (package-strip-rcs-id (lm-header "version"))))
+          (commentary (lm-commentary)))
+      (unless pkg-version
+       (error
+        "Package lacks a \"Version\" or \"Package-Version\" header"))
+      ;; Turn string version numbers into list form.
+      (setq requires
+           (mapcar
+            (lambda (elt)
+              (list (car elt)
+                    (version-to-list (car (cdr elt)))))
+            requires))
+      (vector file-name requires desc pkg-version commentary))))
 
 (defun package-tar-file-info (file)
   "Find package information for a tar file.
 FILE is the name of the tar file to examine.
 The return result is a vector like `package-buffer-info'."
   (unless (string-match "^\\(.+\\)-\\([0-9.]+\\)\\.tar$" file)
-    (error "`%s' doesn't have a package-ish name" file))
+    (error "Invalid package name `%s'" file))
   (let* ((pkg-name (file-name-nondirectory (match-string-no-properties 1 file)))
         (pkg-version (match-string-no-properties 2 file))
         ;; Extract the package descriptor.
@@ -916,20 +895,19 @@ The return result is a vector like `package-buffer-info'."
                                    pkg-name "-pkg.el")))
         (pkg-def-parsed (package-read-from-string pkg-def-contents)))
     (unless (eq (car pkg-def-parsed) 'define-package)
-      (error "%s-pkg.el doesn't contain `define-package' sexp" pkg-name))
-    (let ((name-str (nth 1 pkg-def-parsed))
+      (error "No `define-package' sexp is present in `%s-pkg.el'" pkg-name))
+    (let ((name-str       (nth 1 pkg-def-parsed))
          (version-string (nth 2 pkg-def-parsed))
-         (docstring (nth 3 pkg-def-parsed))
-         (requires (nth 4 pkg-def-parsed))
-
+         (docstring      (nth 3 pkg-def-parsed))
+         (requires       (nth 4 pkg-def-parsed))
          (readme (shell-command-to-string
                   ;; Requires GNU tar.
                   (concat "tar -xOf " file " "
                           pkg-name "-" pkg-version "/README"))))
       (unless (equal pkg-version version-string)
-       (error "Inconsistent versions!"))
+       (error "Package has inconsistent versions"))
       (unless (equal pkg-name name-str)
-       (error "Inconsistent names!"))
+       (error "Package has inconsistent names"))
       ;; Kind of a hack.
       (if (string-match ": Not found in archive" readme)
          (setq readme nil))
@@ -937,18 +915,27 @@ The return result is a vector like `package-buffer-info'."
       (if (eq (car requires) 'quote)
          (setq requires (car (cdr requires))))
       (setq requires
-           (mapcar
-            (lambda (elt)
-              (list (car elt)
-                    (package-version-split (car (cdr elt)))))
-            requires))
+           (mapcar (lambda (elt)
+                     (list (car elt)
+                           (version-to-list (cadr elt))))
+                   requires))
       (vector pkg-name requires docstring version-string readme))))
 
-(defun package-install-buffer-internal (pkg-info type)
+;;;###autoload
+(defun package-install-from-buffer (pkg-info type)
+  "Install a package from the current buffer.
+When called interactively, the current buffer is assumed to be a
+single .el file that follows the packaging guidelines; see info
+node `(elisp)Packaging'.
+
+When called from Lisp, PKG-INFO is a vector describing the
+information, of the type returned by `package-buffer-info'; and
+TYPE is the package type (either `single' or `tar')."
+  (interactive (list (package-buffer-info) 'single))
   (save-excursion
     (save-restriction
       (let* ((file-name (aref pkg-info 0))
-            (requires (aref pkg-info 1))
+            (requires  (aref pkg-info 1))
             (desc (if (string= (aref pkg-info 2) "")
                       "No description available."
                     (aref pkg-info 2)))
@@ -967,15 +954,6 @@ The return result is a vector like `package-buffer-info'."
        ;; Try to activate it.
        (package-initialize)))))
 
-;;;###autoload
-(defun package-install-from-buffer ()
-  "Install a package from the current buffer.
-The package is assumed to be a single .el file which
-follows the elisp comment guidelines; see
-info node `(elisp)Library Headers'."
-  (interactive)
-  (package-install-buffer-internal (package-buffer-info) 'single))
-
 ;;;###autoload
 (defun package-install-file (file)
   "Install a package from a file.
@@ -984,9 +962,10 @@ The file can either be a tar file or an Emacs Lisp file."
   (with-temp-buffer
     (insert-file-contents-literally file)
     (cond
-     ((string-match "\\.el$" file) (package-install-from-buffer))
+     ((string-match "\\.el$" file)
+      (package-install-from-buffer (package-buffer-info) 'single))
      ((string-match "\\.tar$" file)
-      (package-install-buffer-internal (package-tar-file-info file) 'tar))
+      (package-install-from-buffer (package-tar-file-info file) 'tar))
      (t (error "Unrecognized extension `%s'" (file-name-extension file))))))
 
 (defun package-delete (name version)
@@ -996,20 +975,28 @@ The file can either be a tar file or an Emacs Lisp file."
                     ;; FIXME: query user?
                     'always))
 
-(defun package--download-one-archive (file)
-  "Download a single archive file and cache it locally."
-  (let ((buffer (url-retrieve-synchronously
-                (concat package-archive-base file))))
+(defun package-archive-url (name)
+  "Return the archive containing the package NAME."
+  (let ((desc (cdr (assq (intern-soft name) package-archive-contents))))
+    (cdr (assoc (aref desc (- (length desc) 1)) package-archives))))
+
+(defun package--download-one-archive (archive file)
+  "Download an archive file FILE from ARCHIVE, and cache it locally."
+  (let* ((archive-name (car archive))
+         (archive-url  (cdr archive))
+        (dir (expand-file-name "archives" package-user-dir))
+        (dir (expand-file-name archive-name dir))
+         (buffer (url-retrieve-synchronously (concat archive-url file))))
     (with-current-buffer buffer
       (package-handle-response)
       (re-search-forward "^$" nil 'move)
       (forward-char)
       (delete-region (point-min) (point))
-      (setq buffer-file-name (concat (file-name-as-directory package-user-dir)
-                                    file))
+      (make-directory dir t)
+      (setq buffer-file-name (expand-file-name file dir))
       (let ((version-control 'never))
-       (save-buffer))
-      (kill-buffer buffer))))
+       (save-buffer)))
+    (kill-buffer buffer)))
 
 (defun package-refresh-contents ()
   "Download the ELPA archive description if needed.
@@ -1019,18 +1006,24 @@ download."
   (interactive)
   (unless (file-exists-p package-user-dir)
     (make-directory package-user-dir t))
-  (package--download-one-archive "archive-contents")
-  (package--download-one-archive "builtin-packages")
-  (package-read-archive-contents))
+  (dolist (archive package-archives)
+    (condition-case nil
+       (package--download-one-archive archive "archive-contents")
+      (error (message "Failed to download `%s' archive."
+                     (car archive)))))
+  (package-read-all-archive-contents))
 
 ;;;###autoload
 (defun package-initialize ()
   "Load Emacs Lisp packages, and activate them.
 The variable `package-load-list' controls which packages to load."
   (interactive)
+  (require 'finder-inf nil t)
+  (setq package-alist package--builtins)
+  (setq package-activated-list (mapcar #'car package-alist))
   (setq package-obsolete-alist nil)
   (package-load-all-descriptors)
-  (package-read-archive-contents)
+  (package-read-all-archive-contents)
   ;; Try to activate all our packages.
   (mapc (lambda (elt)
          (package-activate (car elt) (package-desc-vers (cdr elt))))
@@ -1056,9 +1049,7 @@ The variable `package-load-list' controls which packages to load."
                                        guess)
                              "Describe package: ")
                            packages nil t nil nil guess))
-     (list (if (equal val "")
-              guess
-            (intern val)))))
+     (list (if (equal val "") guess (intern val)))))
   (if (or (null package) (null (symbolp package)))
       (message "You did not specify a package")
     (help-setup-xref (list #'describe-package package)
@@ -1068,38 +1059,65 @@ The variable `package-load-list' controls which packages to load."
        (describe-package-1 package)))))
 
 (defun describe-package-1 (package)
-  (let ((desc (cdr (assq package package-alist)))
-       reqs version installable)
+  (require 'lisp-mnt)
+  (let ((package-name (symbol-name package))
+       (built-in (assq package package--builtins))
+       desc pkg-dir reqs version installable)
     (prin1 package)
     (princ " is ")
-    (cond
-     (desc
-      ;; This package is loaded (i.e. in `package-alist').
-      (let (pkg-dir)
-       (setq version (package-version-join (package-desc-vers desc)))
-       (if (assq package package--builtins)
-           (princ "a built-in package.\n\n")
-         (setq pkg-dir (package--dir (symbol-name package) version))
-         (if pkg-dir
-             (progn
-               (insert "a package installed in `")
-               (help-insert-xref-button (file-name-as-directory pkg-dir)
-                                        'help-package-def pkg-dir)
-               (insert "'.\n\n"))
-           ;; This normally does not happen.
-           (insert "a deleted package.\n\n")
-           (setq version nil)))))
-     (t
-      ;; An uninstalled package.
-      (setq desc (cdr (assq package package-archive-contents))
+    (if (setq desc (cdr (assq package package-alist)))
+       ;; This package is loaded (i.e. in `package-alist').
+       (progn
+         (setq version (package-version-join (package-desc-vers desc)))
+         (cond (built-in
+                (princ "a built-in package.\n\n"))
+               ((setq pkg-dir (package--dir package-name version))
+                (insert "an installed package.\n\n"))
+               (t ;; This normally does not happen.
+                (insert "a deleted package.\n\n")
+                (setq version nil))))
+      ;; This package is not installed.
+      (setq desc    (cdr (assq package package-archive-contents))
            version (package-version-join (package-desc-vers desc))
            installable t)
-      (insert "an installable package.\n\n")))
-    (if version
-       (insert "      Version: " version "\n"))
+      (insert "an uninstalled package.\n\n"))
+
+    (insert "     " (propertize "Status" 'font-lock-face 'bold) ": ")
+    (cond (pkg-dir
+          (insert (propertize "Installed"
+                              'font-lock-face 'font-lock-comment-face))
+          (insert " in `")
+          ;; Todo: Add button for uninstalling.
+          (help-insert-xref-button (file-name-as-directory pkg-dir)
+                                   'help-package-def pkg-dir)
+          (insert "'."))
+         (installable
+          (insert "Available -- ")
+          (let ((button-text (if (display-graphic-p)
+                                 "Install"
+                               "[Install]"))
+                (button-face (if (display-graphic-p)
+                                 '(:box (:line-width 2 :color "dark grey")
+                                        :background "light grey"
+                                        :foreground "black")
+                               'link)))
+            (insert-text-button button-text
+                                'face button-face
+                                'follow-link t
+                                'package-symbol package
+                                'action 'package-install-button-action)))
+         (built-in
+          (insert (propertize "Built-in"
+                              'font-lock-face 'font-lock-builtin-face) "."))
+         (t (insert "Deleted.")))
+    (insert "\n")
+    (and version
+        (> (length version) 0)
+        (insert "    "
+                (propertize "Version" 'font-lock-face 'bold) ": " version "\n"))
     (setq reqs (package-desc-reqs desc))
     (when reqs
-      (insert "     Requires: ")
+      (insert "   " (propertize "Requires" 'font-lock-face 'bold) ": ")
       (let ((first t)
            name vers text)
        (dolist (req reqs)
@@ -1114,28 +1132,53 @@ The variable `package-load-list' controls which packages to load."
                (t (insert ", ")))
          (help-insert-xref-button text 'help-package name))
        (insert "\n")))
-    (insert "  Description: " (package-desc-doc desc) "\n")
-    ;; Todo: button for uninstalling a package.
-    (when installable
-      (let ((button-text (if (display-graphic-p)
-                            "Install"
-                          "[Install]"))
-           (button-face (if (display-graphic-p)
-                            '(:box (:line-width 2 :color "dark grey")
-                                   :background "light grey"
-                                   :foreground "black")
-                          'link)))
-       (insert "\n")
-       (insert-text-button button-text
-                           'face button-face
-                           'follow-link t
-                           'package-symbol package
-                           'action (lambda (button)
-                                     (package-install
-                                      (button-get button 'package-symbol))
-                                     (revert-buffer nil t)
-                                     (goto-char (point-min))))
-       (insert "\n")))))
+    (insert "    " (propertize "Summary" 'font-lock-face 'bold)
+           ": " (package-desc-doc desc) "\n\n")
+
+    (if (assq package package--builtins)
+       ;; For built-in packages, insert the commentary.
+       (let ((fn (locate-file (concat package-name ".el") load-path
+                              load-file-rep-suffixes))
+             (opoint (point)))
+         (insert (or (lm-commentary fn) ""))
+         (save-excursion
+           (goto-char opoint)
+           (when (re-search-forward "^;;; Commentary:\n" nil t)
+             (replace-match ""))
+           (while (re-search-forward "^\\(;+ ?\\)" nil t)
+             (replace-match ""))))
+      (let ((readme (expand-file-name (concat package-name "-readme.txt")
+                                     package-user-dir)))
+       ;; For elpa packages, try downloading the commentary.  If that
+       ;; fails, try an existing readme file in `package-user-dir'.
+       (cond ((let ((buffer (ignore-errors
+                              (url-retrieve-synchronously
+                               (concat (package-archive-url package)
+                                       package-name "-readme.txt"))))
+                    response)
+                (when buffer
+                  (with-current-buffer buffer
+                    (setq response (url-http-parse-response))
+                    (if (or (< response 200) (>= response 300))
+                        (setq response nil)
+                      (setq buffer-file-name
+                            (expand-file-name readme package-user-dir))
+                      (delete-region (point-min) (1+ url-http-end-of-headers))
+                      (save-buffer)))
+                  (when response
+                    (insert-buffer-substring buffer)
+                    (kill-buffer buffer)
+                    t))))
+             ((file-readable-p readme)
+              (insert-file-contents readme)
+              (goto-char (point-max))))))))
+
+(defun package-install-button-action (button)
+  (let ((package (button-get button 'package-symbol)))
+    (when (y-or-n-p (format "Install package `%s'? " package))
+      (package-install package)
+      (revert-buffer nil t)
+      (goto-char (point-min)))))
 
 \f
 ;;;; Package menu mode.
@@ -1152,12 +1195,14 @@ The variable `package-load-list' controls which packages to load."
     (define-key map "\177" 'package-menu-backup-unmark)
     (define-key map "d" 'package-menu-mark-delete)
     (define-key map "i" 'package-menu-mark-install)
-    (define-key map "g" 'package-menu-revert)
+    (define-key map "g" 'revert-buffer)
     (define-key map "r" 'package-menu-refresh)
     (define-key map "~" 'package-menu-mark-obsolete-for-deletion)
     (define-key map "x" 'package-menu-execute)
     (define-key map "h" 'package-menu-quick-help)
-    (define-key map "?" 'package-menu-view-commentary)
+    (define-key map "?" 'package-menu-describe-package)
+    (define-key map [follow-link] 'mouse-face)
+    (define-key map [mouse-2] 'mouse-select-window)
     (define-key map [menu-bar package-menu] (cons "Package" menu-map))
     (define-key menu-map [mq]
       '(menu-item "Quit" quit-window
@@ -1184,7 +1229,7 @@ The variable `package-load-list' controls which packages to load."
                  :help "Mark a package for installation and move to the next line"))
     (define-key menu-map [s3] '("--"))
     (define-key menu-map [mg]
-      '(menu-item "Update package list" package-menu-revert
+      '(menu-item "Update package list" revert-buffer
                  :help "Update the list of packages"))
     (define-key menu-map [mr]
       '(menu-item "Refresh package list" package-menu-refresh
@@ -1209,6 +1254,7 @@ The variable `package-load-list' controls which packages to load."
 (defvar package-menu-sort-button-map
   (let ((map (make-sparse-keymap)))
     (define-key map [header-line mouse-1] 'package-menu-sort-by-column)
+    (define-key map [header-line mouse-2] 'package-menu-sort-by-column)
     (define-key map [follow-link] 'mouse-face)
     map)
   "Local keymap for package menu sort buttons.")
@@ -1226,10 +1272,33 @@ Letters do not insert themselves; instead, they are commands.
   (setq mode-name "Package Menu")
   (setq truncate-lines t)
   (setq buffer-read-only t)
-  ;; Support Emacs 21.
-  (if (fboundp 'run-mode-hooks)
-      (run-mode-hooks 'package-menu-mode-hook)
-    (run-hooks 'package-menu-mode-hook)))
+  (setq revert-buffer-function 'package-menu-revert)
+  (setq header-line-format
+       (mapconcat
+        (lambda (pair)
+          (let ((column (car pair))
+                (name (cdr pair)))
+            (concat
+             ;; Insert a space that aligns the button properly.
+             (propertize " " 'display (list 'space :align-to column)
+                         'face 'fixed-pitch)
+             ;; Set up the column button.
+             (propertize name
+                         'column-name name
+                         'help-echo "mouse-1: sort by column"
+                         'mouse-face 'highlight
+                         'keymap package-menu-sort-button-map))))
+        ;; We take a trick from buff-menu and have a dummy leading
+        ;; space to align the header line with the beginning of the
+        ;; text.  This doesn't really work properly on Emacs 21, but
+        ;; it is close enough.
+        '((0 . "")
+          (2 . "Package")
+          (20 . "Version")
+          (32 . "Status")
+          (43 . "Description"))
+        ""))
+  (run-mode-hooks 'package-menu-mode-hook))
 
 (defun package-menu-refresh ()
   "Download the ELPA archive.
@@ -1238,13 +1307,19 @@ the Emacs Lisp Package Archive, and then refreshes the
 package menu.  This lets you see what new packages are
 available for download."
   (interactive)
+  (unless (eq major-mode 'package-menu-mode)
+    (error "The current buffer is not a Package Menu"))
   (package-refresh-contents)
-  (package-list-packages-internal))
+  (package--generate-package-list))
 
-(defun package-menu-revert ()
-  "Update the list of packages."
+(defun package-menu-revert (&optional arg noconfirm)
+  "Update the list of packages.
+This function is the `revert-buffer-function' for Package Menu
+buffers.  The arguments are ignored."
   (interactive)
-  (package-list-packages-internal))
+  (unless (eq major-mode 'package-menu-mode)
+    (error "The current buffer is not a Package Menu"))
+  (package--generate-package-list))
 
 (defun package-menu-describe-package ()
   "Describe the package in the current line."
@@ -1301,31 +1376,8 @@ available for download."
   (interactive)
   (message "n-ext, i-nstall, d-elete, u-nmark, x-ecute, r-efresh, h-elp"))
 
-(defun package-menu-view-commentary ()
-  "Display information about this package.
-For single-file packages, shows the commentary section from the header.
-For larger packages, shows the README file."
-  (interactive)
-  (let* (start-point ok
-        (pkg-name (package-menu-get-package))
-        (buffer (url-retrieve-synchronously (concat package-archive-base
-                                                    pkg-name
-                                                    "-readme.txt"))))
-    (with-current-buffer buffer
-      ;; FIXME: it would be nice to work with any URL type.
-      (setq start-point url-http-end-of-headers)
-      (setq ok (eq (url-http-parse-response) 200)))
-    (let ((new-buffer (get-buffer-create "*Package Info*")))
-      (with-current-buffer new-buffer
-       (let ((buffer-read-only nil))
-         (erase-buffer)
-         (insert "Package information for " pkg-name "\n\n")
-         (if ok
-             (insert-buffer-substring buffer start-point)
-           (insert "This package does not have a README file or commentary comment.\n"))
-         (goto-char (point-min))
-         (view-mode)))
-      (display-buffer new-buffer t))))
+(define-obsolete-function-alias
+  'package-menu-view-commentary 'package-menu-describe-package "24.1")
 
 ;; Return the name of the package on the current line.
 (defun package-menu-get-package ()
@@ -1355,7 +1407,6 @@ Note that after installing packages you will want to restart
 Emacs."
   (interactive)
   (goto-char (point-min))
-  (forward-line 2)
   (while (not (eobp))
     (let ((cmd (char-after))
          (pkg-name (package-menu-get-package))
@@ -1380,7 +1431,7 @@ Emacs."
 
 (defun package-print-package (package version key desc)
   (let ((face
-        (cond ((eq package 'emacs) 'font-lock-builtin-face)
+        (cond ((string= key "built-in") 'font-lock-builtin-face)
               ((string= key "available") 'default)
               ((string= key "held") 'font-lock-constant-face)
               ((string= key "disabled") 'font-lock-warning-face)
@@ -1402,7 +1453,9 @@ Emacs."
     ;; FIXME: this 'when' is bogus...
     (when desc
       (indent-to 43 1)
-      (insert (propertize desc 'font-lock-face face)))
+      (let ((opoint (point)))
+       (insert (propertize desc 'font-lock-face face))
+       (upcase-region opoint (min (point) (1+ opoint)))))
     (insert "\n")))
 
 (defun package-list-maybe-add (package version status description result)
@@ -1411,139 +1464,158 @@ Emacs."
                       result)))
   result)
 
-;; This decides how we should sort; nil means by package name.
-(defvar package-menu-sort-key nil)
+(defvar package-menu-package-list nil
+  "List of packages to display in the Package Menu buffer.
+A value of nil means to display all packages.")
 
-(defun package-list-packages-internal ()
-  (package-initialize)                 ; FIXME: do this here?
-  (with-current-buffer (get-buffer-create "*Packages*")
+(defvar package-menu-sort-key nil
+  "Sort key for the current Package Menu buffer.")
+
+(defun package--generate-package-list ()
+  "Populate the current Package Menu buffer."
+  (package-initialize)
+  (let ((inhibit-read-only t)
+       info-list name desc hold builtin)
     (setq buffer-read-only nil)
     (erase-buffer)
-    (let ((info-list)
-         name desc hold)
-      ;; List installed packages
-      (dolist (elt package-alist)
-       (setq name (car elt)
-             desc (cdr elt)
-             hold (assq name package-load-list))
+    ;; List installed packages
+    (dolist (elt package-alist)
+      (setq name (car elt))
+      (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
+                (or (null package-menu-package-list)
+                    (memq name package-menu-package-list)))
+       (setq desc (cdr elt)
+             hold (cadr (assq name package-load-list))
+             builtin (cdr (assq name package--builtins)))
        (setq info-list
-             (package-list-maybe-add name (package-desc-vers desc)
-                                     ;; FIXME: it turns out to be
-                                     ;; tricky to see if this package
-                                     ;; is presently activated.
-                                     (if (stringp (cadr hold))
-                                         "held"
-                                       "installed")
-                                     (package-desc-doc desc)
-                                     info-list)))
-      ;; List available packages
-      (dolist (elt package-archive-contents)
-       (setq name (car elt)
-             desc (cdr elt)
-             hold (assq name package-load-list))
-       (unless (and hold (stringp (cadr hold))
-                    (package-installed-p
-                     name (package-version-split (cadr hold))))
-         (setq info-list
-               (package-list-maybe-add name
-                                       (package-desc-vers desc)
-                                       (if (and hold (null (cadr hold)))
-                                           "disabled"
-                                         "available")
-                                       (package-desc-doc (cdr elt))
-                                       info-list))))
-      ;; List obsolete packages
-      (mapc (lambda (elt)
-             (mapc (lambda (inner-elt)
-                     (setq info-list
-                           (package-list-maybe-add (car elt)
-                                                   (package-desc-vers
-                                                    (cdr inner-elt))
-                                                   "obsolete"
-                                                   (package-desc-doc
-                                                    (cdr inner-elt))
-                                                   info-list)))
-                   (cdr elt)))
-           package-obsolete-alist)
-      (let ((selector (cond
-                      ((string= package-menu-sort-key "Version")
-                       ;; FIXME this doesn't work.
-                       #'(lambda (e) (cdr (car e))))
-                      ((string= package-menu-sort-key "Status")
-                       #'(lambda (e) (car (cdr e))))
-                      ((string= package-menu-sort-key "Description")
-                       #'(lambda (e) (car (cdr (cdr e)))))
-                      (t ; "Package" is default.
-                       #'(lambda (e) (symbol-name (car (car e))))))))
+             (package-list-maybe-add
+              name (package-desc-vers desc)
+              ;; FIXME: it turns out to be tricky to see if this
+              ;; package is presently activated.
+              (cond ((stringp hold) "held")
+                    ((and builtin
+                          (version-list-=
+                           (package-desc-vers builtin)
+                           (package-desc-vers desc)))
+                     "built-in")
+                    (t "installed"))
+              (package-desc-doc desc)
+              info-list))))
+
+    ;; List available and disabled packages
+    (dolist (elt package-archive-contents)
+      (setq name (car elt)
+           desc (cdr elt)
+           hold (assq name package-load-list))
+      (when (or (null package-menu-package-list)
+               (memq name package-menu-package-list))
        (setq info-list
-             (sort info-list
-                   (lambda (left right)
-                     (let ((vleft (funcall selector left))
-                           (vright (funcall selector right)))
-                       (string< vleft vright))))))
-      (mapc (lambda (elt)
-             (package-print-package (car (car elt))
-                                    (cdr (car elt))
-                                    (car (cdr elt))
-                                    (car (cdr (cdr elt)))))
-           info-list))
+             (package-list-maybe-add name
+                                     (package-desc-vers desc)
+                                     (if (and hold (null (cadr hold)))
+                                         "disabled"
+                                       "available")
+                                     (package-desc-doc (cdr elt))
+                                     info-list))))
+    ;; List obsolete packages
+    (mapc (lambda (elt)
+           (mapc (lambda (inner-elt)
+                   (setq info-list
+                         (package-list-maybe-add (car elt)
+                                                 (package-desc-vers
+                                                  (cdr inner-elt))
+                                                 "obsolete"
+                                                 (package-desc-doc
+                                                  (cdr inner-elt))
+                                                 info-list)))
+                 (cdr elt)))
+         package-obsolete-alist)
+
+    (setq info-list
+         (sort info-list
+               (cond ((string= package-menu-sort-key "Package")
+                      'package-menu--name-predicate)
+                     ((string= package-menu-sort-key "Version")
+                      'package-menu--version-predicate)
+                     ((string= package-menu-sort-key "Description")
+                      'package-menu--description-predicate)
+                     (t ; By default, sort by package status
+                      'package-menu--status-predicate))))
+
+    (dolist (elt info-list)
+      (package-print-package (car (car elt))
+                            (cdr (car elt))
+                            (car (cdr elt))
+                            (car (cdr (cdr elt)))))
     (goto-char (point-min))
+    (set-buffer-modified-p nil)
     (current-buffer)))
 
+(defun package-menu--version-predicate (left right)
+  (let ((vleft  (or (cdr (car left))  '(0)))
+       (vright (or (cdr (car right)) '(0))))
+    (if (version-list-= vleft vright)
+       (package-menu--name-predicate left right)
+      (version-list-< vleft vright))))
+
+(defun package-menu--status-predicate (left right)
+  (let ((sleft  (cadr left))
+       (sright (cadr right)))
+    (cond ((string= sleft sright)
+          (package-menu--name-predicate left right))
+         ((string= sleft  "available") t)
+         ((string= sright "available") nil)
+         ((string= sleft  "installed") t)
+         ((string= sright "installed") nil)
+         ((string= sleft  "held") t)
+         ((string= sright "held") nil)
+         ((string= sleft  "built-in") t)
+         ((string= sright "built-in") nil)
+         ((string= sleft  "obsolete") t)
+         ((string= sright  "obsolete") nil)
+         (t (string< sleft sright)))))
+
+(defun package-menu--description-predicate (left right)
+  (let ((sleft  (car (cddr left)))
+       (sright (car (cddr right))))
+    (if (string= sleft sright)
+       (package-menu--name-predicate left right)
+      (string< sleft sright))))
+
+(defun package-menu--name-predicate (left right)
+  (string< (symbol-name (caar left))
+          (symbol-name (caar right))))
+
 (defun package-menu-sort-by-column (&optional e)
-  "Sort the package menu by the last column clicked on."
-  (interactive (list last-input-event))
-  (if e (mouse-select-window e))
+  "Sort the package menu by the column of the mouse click E."
+  (interactive "e")
   (let* ((pos (event-start e))
         (obj (posn-object pos))
         (col (if obj
                  (get-text-property (cdr obj) 'column-name (car obj))
-               (get-text-property (posn-point pos) 'column-name))))
-    (setq package-menu-sort-key col))
-  (package-list-packages-internal))
-
-(defun package--list-packages ()
-  "Display a list of packages.
-Helper function that does all the work for the user-facing functions."
-  (with-current-buffer (package-list-packages-internal)
+               (get-text-property (posn-point pos) 'column-name)))
+        (buf (window-buffer (posn-window (event-start e)))))
+    (with-current-buffer buf
+      (when (eq major-mode 'package-menu-mode)
+       (setq package-menu-sort-key col)
+       (package--generate-package-list)))))
+
+(defun package--list-packages (&optional packages)
+  "Generate and pop to the *Packages* buffer.
+Optional PACKAGES is a list of names of packages (symbols) to
+list; the default is to display everything in `package-alist'."
+  (with-current-buffer (get-buffer-create "*Packages*")
     (package-menu-mode)
-    ;; Set up the header line.
-    (setq header-line-format
-         (mapconcat
-          (lambda (pair)
-            (let ((column (car pair))
-                  (name (cdr pair)))
-              (concat
-               ;; Insert a space that aligns the button properly.
-               (propertize " " 'display (list 'space :align-to column)
-                           'face 'fixed-pitch)
-               ;; Set up the column button.
-               (if (string= name "Version")
-                   name
-                 (propertize name
-                             'column-name name
-                             'help-echo "mouse-1: sort by column"
-                             'mouse-face 'highlight
-                             'keymap package-menu-sort-button-map)))))
-          ;; We take a trick from buff-menu and have a dummy leading
-          ;; space to align the header line with the beginning of the
-          ;; text.  This doesn't really work properly on Emacs 21,
-          ;; but it is close enough.
-          '((0 . "")
-            (2 . "Package")
-            (20 . "Version")
-            (30 . "Status")
-            (41 . "Description"))
-          ""))
-
+    (set (make-local-variable 'package-menu-package-list) packages)
+    (set (make-local-variable 'package-menu-sort-key) nil)
+    (package--generate-package-list)
     ;; It's okay to use pop-to-buffer here.  The package menu buffer
-    ;; has keybindings, and the user just typed 'M-x
-    ;; package-list-packages', suggesting that they might want to use
-    ;; them.
+    ;; has keybindings, and the user just typed `M-x list-packages',
+    ;; suggesting that they might want to use them.
     (pop-to-buffer (current-buffer))))
 
 ;;;###autoload
-(defun package-list-packages ()
+(defun list-packages ()
   "Display a list of packages.
 Fetches the updated list of packages before displaying.
 The list is displayed in a buffer named `*Packages*'."
@@ -1551,6 +1623,9 @@ The list is displayed in a buffer named `*Packages*'."
   (package-refresh-contents)
   (package--list-packages))
 
+;;;###autoload
+(defalias 'package-list-packages 'list-packages)
+
 (defun package-list-packages-no-fetch ()
   "Display a list of packages.
 Does not fetch the updated list of packages before displaying.