Merge changes from emacs-23 branch
[bpt/emacs.git] / lisp / emacs-lisp / package.el
CommitLineData
44198b6e
CY
1;;; package.el --- Simple package system for Emacs
2
73b0cd50 3;; Copyright (C) 2007-2011 Free Software Foundation, Inc.
44198b6e
CY
4
5;; Author: Tom Tromey <tromey@redhat.com>
6;; Created: 10 Mar 2007
7;; Version: 0.9
8;; Keywords: tools
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation; either version 3, or (at your option)
15;; any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
23;; along with GNU Emacs; see the file COPYING. If not, write to the
24;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25;; Boston, MA 02110-1301, USA.
26
27;;; Change Log:
28
29;; 2 Apr 2007 - now using ChangeLog file
30;; 15 Mar 2007 - updated documentation
31;; 14 Mar 2007 - Changed how obsolete packages are handled
32;; 13 Mar 2007 - Wrote package-install-from-buffer
33;; 12 Mar 2007 - Wrote package-menu mode
34
35;;; Commentary:
36
37;; The idea behind package.el is to be able to download packages and
38;; install them. Packages are versioned and have versioned
39;; dependencies. Furthermore, this supports built-in packages which
40;; may or may not be newer than user-specified packages. This makes
41;; it possible to upgrade Emacs and automatically disable packages
42;; which have moved from external to core. (Note though that we don't
43;; currently register any of these, so this feature does not actually
44;; work.)
45
44198b6e
CY
46;; A package is described by its name and version. The distribution
47;; format is either a tar file or a single .el file.
48
49;; A tar file should be named "NAME-VERSION.tar". The tar file must
50;; unpack into a directory named after the package and version:
51;; "NAME-VERSION". It must contain a file named "PACKAGE-pkg.el"
52;; which consists of a call to define-package. It may also contain a
53;; "dir" file and the info files it references.
54
bc44bef7 55;; A .el file is named "NAME-VERSION.el" in the remote archive, but is
44198b6e
CY
56;; installed as simply "NAME.el" in a directory named "NAME-VERSION".
57
bc44bef7
PH
58;; The downloader downloads all dependent packages. By default,
59;; packages come from the official GNU sources, but others may be
60;; added by customizing the `package-archives' alist. Packages get
61;; byte-compiled at install time.
44198b6e
CY
62
63;; At activation time we will set up the load-path and the info path,
64;; and we will load the package's autoloads. If a package's
65;; dependencies are not available, we will not activate that package.
66
67;; Conceptually a package has multiple state transitions:
68;;
69;; * Download. Fetching the package from ELPA.
70;; * Install. Untar the package, or write the .el file, into
71;; ~/.emacs.d/elpa/ directory.
72;; * Byte compile. Currently this phase is done during install,
73;; but we may change this.
74;; * Activate. Evaluate the autoloads for the package to make it
75;; available to the user.
76;; * Load. Actually load the package and run some code from it.
77
78;; Other external functions you may want to use:
79;;
015eea59 80;; M-x list-packages
44198b6e
CY
81;; Enters a mode similar to buffer-menu which lets you manage
82;; packages. You can choose packages for install (mark with "i",
83;; then "x" to execute) or deletion (not implemented yet), and you
84;; can see what packages are available. This will automatically
85;; fetch the latest list of packages from ELPA.
86;;
87;; M-x package-list-packages-no-fetch
88;; Like package-list-packages, but does not automatically fetch the
89;; new list of packages.
90;;
91;; M-x package-install-from-buffer
92;; Install a package consisting of a single .el file that appears
93;; in the current buffer. This only works for packages which
94;; define a Version header properly; package.el also supports the
95;; extension headers Package-Version (in case Version is an RCS id
96;; or similar), and Package-Requires (if the package requires other
97;; packages).
98;;
99;; M-x package-install-file
100;; Install a package from the indicated file. The package can be
101;; either a tar file or a .el file. A tar file must contain an
102;; appropriately-named "-pkg.el" file; a .el file must be properly
103;; formatted as with package-install-from-buffer.
104
105;;; Thanks:
106;;; (sorted by sort-lines):
107
108;; Jim Blandy <jimb@red-bean.com>
109;; Karl Fogel <kfogel@red-bean.com>
110;; Kevin Ryde <user42@zip.com.au>
111;; Lawrence Mitchell
112;; Michael Olson <mwolson@member.fsf.org>
113;; Sebastian Tennant <sebyte@smolny.plus.com>
114;; Stefan Monnier <monnier@iro.umontreal.ca>
115;; Vinicius Jose Latorre <viniciusjl@ig.com.br>
116;; Phil Hagelberg <phil@hagelb.org>
117
118;;; ToDo:
119
120;; - putting info dirs at the start of the info path means
121;; users see a weird ordering of categories. OTOH we want to
122;; override later entries. maybe emacs needs to enforce
123;; the standard layout?
124;; - put bytecode in a separate directory tree
125;; - perhaps give users a way to recompile their bytecode
126;; or do it automatically when emacs changes
127;; - give users a way to know whether a package is installed ok
128;; - give users a way to view a package's documentation when it
129;; only appears in the .el
130;; - use/extend checkdoc so people can tell if their package will work
131;; - "installed" instead of a blank in the status column
132;; - tramp needs its files to be compiled in a certain order.
133;; how to handle this? fix tramp?
134;; - on emacs 21 we don't kill the -autoloads.el buffer. what about 22?
135;; - maybe we need separate .elc directories for various emacs versions
136;; and also emacs-vs-xemacs. That way conditional compilation can
137;; work. But would this break anything?
138;; - should store the package's keywords in archive-contents, then
139;; let the users filter the package-menu by keyword. See
140;; finder-by-keyword. (We could also let people view the
141;; Commentary, but it isn't clear how useful this is.)
142;; - William Xu suggests being able to open a package file without
143;; installing it
144;; - Interface with desktop.el so that restarting after an install
145;; works properly
146;; - Implement M-x package-upgrade, to upgrade any/all existing packages
147;; - Use hierarchical layout. PKG/etc PKG/lisp PKG/info
148;; ... except maybe lisp?
149;; - It may be nice to have a macro that expands to the package's
150;; private data dir, aka ".../etc". Or, maybe data-directory
151;; needs to be a list (though this would be less nice)
152;; a few packages want this, eg sokoban
153;; - package menu needs:
154;; ability to know which packages are built-in & thus not deletable
155;; it can sometimes print odd results, like 0.3 available but 0.4 active
156;; why is that?
157;; - Allow multiple versions on the server...?
158;; [ why bother? ]
159;; - Don't install a package which will invalidate dependencies overall
160;; - Allow something like (or (>= emacs 21.0) (>= xemacs 21.5))
161;; [ currently thinking, why bother.. KISS ]
162;; - Allow optional package dependencies
163;; then if we require 'bbdb', bbdb-specific lisp in lisp/bbdb
164;; and just don't compile to add to load path ...?
165;; - Have a list of archive URLs? [ maybe there's no point ]
166;; - David Kastrup pointed out on the xemacs list that for GPL it
167;; is friendlier to ship the source tree. We could "support" that
168;; by just having a "src" subdir in the package. This isn't ideal
169;; but it probably is not worth trying to support random source
170;; tree layouts, build schemes, etc.
171;; - Our treatment of the info path is somewhat bogus
172;; - perhaps have an "unstable" tree in ELPA as well as a stable one
173
174;;; Code:
175
176(defgroup package nil
177 "Manager for Emacs Lisp packages."
178 :group 'applications
179 :version "24.1")
180
181;;;###autoload
182(defcustom package-enable-at-startup t
183 "Whether to activate installed packages when Emacs starts.
184If non-nil, packages are activated after reading the init file
185and before `after-init-hook'. Activation is not done if
186`user-init-file' is nil (e.g. Emacs was started with \"-q\").
187
188Even if the value is nil, you can type \\[package-initialize] to
189activate the package system at any time."
190 :type 'boolean
191 :group 'package
192 :version "24.1")
193
194(defcustom package-load-list '(all)
195 "List of packages for `package-initialize' to load.
196Each element in this list should be a list (NAME VERSION), or the
197symbol `all'. The symbol `all' says to load the latest installed
198versions of all packages not specified by other elements.
199
200For an element (NAME VERSION), NAME is a package name (a symbol).
201VERSION should be t, a string, or nil.
202If VERSION is t, all versions are loaded, though obsolete ones
203 will be put in `package-obsolete-alist' and not activated.
204If VERSION is a string, only that version is ever loaded.
205 Any other version, even if newer, is silently ignored.
206 Hence, the package is \"held\" at that version.
207If VERSION is nil, the package is not loaded (it is \"disabled\")."
208 :type '(repeat symbol)
bc44bef7 209 :risky t
44198b6e
CY
210 :group 'package
211 :version "24.1")
212
213(defvar Info-directory-list)
44198b6e
CY
214(declare-function info-initialize "info" ())
215(declare-function url-http-parse-response "url-http" ())
216(declare-function lm-header "lisp-mnt" (header))
217(declare-function lm-commentary "lisp-mnt" (&optional file))
cb6c4991 218(defvar url-http-end-of-headers)
44198b6e 219
bc44bef7
PH
220(defcustom package-archives '(("gnu" . "http://elpa.gnu.org/packages/"))
221 "An alist of archives from which to fetch.
222The default value points to the GNU Emacs package repository.
223Each element has the form (ID . URL), where ID is an identifier
224string for an archive and URL is a http: URL (a string)."
225 :type '(alist :key-type (string :tag "Archive name")
226 :value-type (string :tag "Archive URL"))
227 :risky t
228 :group 'package
229 :version "24.1")
44198b6e
CY
230
231(defconst package-archive-version 1
232 "Version number of the package archive understood by this file.
233Lower version numbers than this will probably be understood as well.")
234
235(defconst package-el-version "1.0"
236 "Version of package.el.")
237
238;; We don't prime the cache since it tends to get out of date.
239(defvar package-archive-contents nil
240 "Cache of the contents of the Emacs Lisp Package Archive.
241This is an alist mapping package names (symbols) to package
242descriptor vectors. These are like the vectors for `package-alist'
bc44bef7
PH
243but have extra entries: one which is 'tar for tar packages and
244'single for single-file packages, and one which is the name of
245the archive from which it came.")
246(put 'package-archive-contents 'risky-local-variable t)
44198b6e
CY
247
248(defcustom package-user-dir (locate-user-emacs-file "elpa")
249 "Directory containing the user's Emacs Lisp packages.
250The directory name should be absolute.
251Apart from this directory, Emacs also looks for system-wide
252packages in `package-directory-list'."
253 :type 'directory
bc44bef7 254 :risky t
44198b6e
CY
255 :group 'package
256 :version "24.1")
257
258(defcustom package-directory-list
259 ;; Defaults are subdirs named "elpa" in the site-lisp dirs.
260 (let (result)
261 (dolist (f load-path)
0be01d2c
CY
262 (and (stringp f)
263 (equal (file-name-nondirectory f) "site-lisp")
264 (push (expand-file-name "elpa" f) result)))
44198b6e
CY
265 (nreverse result))
266 "List of additional directories containing Emacs Lisp packages.
267Each directory name should be absolute.
268
269These directories contain packages intended for system-wide; in
270contrast, `package-user-dir' contains packages for personal use."
271 :type '(repeat directory)
bc44bef7 272 :risky t
44198b6e
CY
273 :group 'package
274 :version "24.1")
275
96ae4c8f
CY
276;; The value is precomputed in finder-inf.el, but don't load that
277;; until it's needed (i.e. when `package-intialize' is called).
278(defvar package--builtins nil
279 "Alist of built-in packages.
015eea59
CY
280The actual value is initialized by loading the library
281`finder-inf'; this is not done until it is needed, e.g. by the
282function `package-built-in-p'.
283
96ae4c8f
CY
284Each element has the form (PKG . DESC), where PKG is a package
285name (a symbol) and DESC is a vector that describes the package.
96ae4c8f
CY
286The vector DESC has the form [VERSION REQS DOCSTRING].
287 VERSION is a version list.
288 REQS is a list of packages (symbols) required by the package.
289 DOCSTRING is a brief description of the package.")
bc44bef7 290(put 'package--builtins 'risky-local-variable t)
44198b6e 291
96ae4c8f 292(defvar package-alist nil
44198b6e 293 "Alist of all packages available for activation.
96ae4c8f
CY
294Each element has the form (PKG . DESC), where PKG is a package
295name (a symbol) and DESC is a vector that describes the package.
44198b6e 296
96ae4c8f
CY
297The vector DESC has the form [VERSION REQS DOCSTRING].
298 VERSION is a version list.
299 REQS is a list of packages (symbols) required by the package.
300 DOCSTRING is a brief description of the package.
301
302This variable is set automatically by `package-load-descriptor',
303called via `package-initialize'. To change which packages are
304loaded and/or activated, customize `package-load-list'.")
bc44bef7 305(put 'package-archive-contents 'risky-local-variable t)
44198b6e 306
96ae4c8f 307(defvar package-activated-list nil
44198b6e 308 "List of the names of currently activated packages.")
bc44bef7 309(put 'package-activated-list 'risky-local-variable t)
44198b6e
CY
310
311(defvar package-obsolete-alist nil
312 "Representation of obsolete packages.
313Like `package-alist', but maps package name to a second alist.
314The inner alist is keyed by version.")
bc44bef7 315(put 'package-obsolete-alist 'risky-local-variable t)
44198b6e
CY
316
317(defconst package-subdirectory-regexp
318 "^\\([^.].*\\)-\\([0-9]+\\(?:[.][0-9]+\\)*\\)$"
319 "Regular expression matching the name of a package subdirectory.
320The first subexpression is the package name.
321The second subexpression is the version string.")
322
323(defun package-version-join (l)
324 "Turn a list of version numbers into a version string."
325 (mapconcat 'int-to-string l "."))
326
44198b6e
CY
327(defun package-strip-version (dirname)
328 "Strip the version from a combined package name and version.
329E.g., if given \"quux-23.0\", will return \"quux\""
330 (if (string-match package-subdirectory-regexp dirname)
331 (match-string 1 dirname)))
332
333(defun package-load-descriptor (dir package)
4b99edf2
CY
334 "Load the description file in directory DIR for package PACKAGE.
335Here, PACKAGE is a string of the form NAME-VER, where NAME is the
336package name and VER is its version."
bc44bef7
PH
337 (let* ((pkg-dir (expand-file-name package dir))
338 (pkg-file (expand-file-name
339 (concat (package-strip-version package) "-pkg")
340 pkg-dir)))
341 (when (and (file-directory-p pkg-dir)
342 (file-exists-p (concat pkg-file ".el")))
343 (load pkg-file nil t))))
44198b6e
CY
344
345(defun package-load-all-descriptors ()
346 "Load descriptors for installed Emacs Lisp packages.
347This looks for package subdirectories in `package-user-dir' and
348`package-directory-list'. The variable `package-load-list'
349controls which package subdirectories may be loaded.
350
351In each valid package subdirectory, this function loads the
352description file containing a call to `define-package', which
353updates `package-alist' and `package-obsolete-alist'."
354 (let ((all (memq 'all package-load-list))
355 name version force)
356 (dolist (dir (cons package-user-dir package-directory-list))
357 (when (file-directory-p dir)
358 (dolist (subdir (directory-files dir))
359 (when (and (file-directory-p (expand-file-name subdir dir))
360 (string-match package-subdirectory-regexp subdir))
361 (setq name (intern (match-string 1 subdir))
362 version (match-string 2 subdir)
363 force (assq name package-load-list))
364 (when (cond
365 ((null force)
366 all) ; not in package-load-list
367 ((null (setq force (cadr force)))
368 nil) ; disabled
369 ((eq force t)
370 t)
371 ((stringp force) ; held
148cef8e
CY
372 (version-list-= (version-to-list version)
373 (version-to-list force)))
44198b6e
CY
374 (t
375 (error "Invalid element in `package-load-list'")))
376 (package-load-descriptor dir subdir))))))))
377
378(defsubst package-desc-vers (desc)
379 "Extract version from a package description vector."
380 (aref desc 0))
381
382(defsubst package-desc-reqs (desc)
383 "Extract requirements from a package description vector."
384 (aref desc 1))
385
386(defsubst package-desc-doc (desc)
387 "Extract doc string from a package description vector."
388 (aref desc 2))
389
390(defsubst package-desc-kind (desc)
391 "Extract the kind of download from an archive package description vector."
392 (aref desc 3))
393
015eea59
CY
394(defun package--dir (name version)
395 "Return the directory where a package is installed, or nil if none.
396NAME and VERSION are both strings."
397 (let* ((subdir (concat name "-" version))
44198b6e 398 (dir-list (cons package-user-dir package-directory-list))
cced7584 399 pkg-dir)
44198b6e 400 (while dir-list
cced7584
CY
401 (let ((subdir-full (expand-file-name subdir (car dir-list))))
402 (if (file-directory-p subdir-full)
403 (setq pkg-dir subdir-full
404 dir-list nil)
44198b6e 405 (setq dir-list (cdr dir-list)))))
cced7584
CY
406 pkg-dir))
407
408(defun package-activate-1 (package pkg-vec)
409 (let* ((name (symbol-name package))
410 (version-str (package-version-join (package-desc-vers pkg-vec)))
411 (pkg-dir (package--dir name version-str)))
44198b6e 412 (unless pkg-dir
015eea59 413 (error "Internal error: unable to find directory for `%s-%s'"
cced7584
CY
414 name version-str))
415 ;; Add info node.
ebf662f4
CY
416 (when (file-exists-p (expand-file-name "dir" pkg-dir))
417 ;; FIXME: not the friendliest, but simple.
418 (require 'info)
419 (info-initialize)
420 (push pkg-dir Info-directory-list))
cced7584 421 ;; Add to load path, add autoloads, and activate the package.
ebf662f4 422 (push pkg-dir load-path)
cced7584 423 (load (expand-file-name (concat name "-autoloads") pkg-dir) nil t)
ebf662f4 424 (push package package-activated-list)
44198b6e
CY
425 ;; Don't return nil.
426 t))
427
4b99edf2
CY
428(defun package-built-in-p (package &optional version)
429 "Return true if PACKAGE, of VERSION or newer, is built-in to Emacs."
430 (require 'finder-inf nil t) ; For `package--builtins'.
44198b6e 431 (let ((elt (assq package package--builtins)))
4b99edf2 432 (and elt (version-list-<= version (package-desc-vers (cdr elt))))))
44198b6e 433
4b99edf2
CY
434;; This function goes ahead and activates a newer version of a package
435;; if an older one was already activated. This is not ideal; we'd at
436;; least need to check to see if the package has actually been loaded,
437;; and not merely activated.
44198b6e 438(defun package-activate (package version)
4b99edf2
CY
439 "Activate package PACKAGE, of version VERSION or newer.
440If PACKAGE has any dependencies, recursively activate them.
44198b6e 441Return nil if the package could not be activated."
4b99edf2
CY
442 (let ((pkg-vec (cdr (assq package package-alist)))
443 available-version found)
444 ;; Check if PACKAGE is available in `package-alist'.
445 (when pkg-vec
446 (setq available-version (package-desc-vers pkg-vec)
447 found (version-list-<= version available-version)))
448 (cond
449 ;; If no such package is found, maybe it's built-in.
450 ((null found)
451 (package-built-in-p package version))
452 ;; If the package is already activated, just return t.
453 ((memq package package-activated-list)
454 t)
455 ;; Otherwise, proceed with activation.
456 (t
457 (let ((fail (catch 'dep-failure
458 ;; Activate its dependencies recursively.
459 (dolist (req (package-desc-reqs pkg-vec))
460 (unless (package-activate (car req) (cadr req))
461 (throw 'dep-failure req))))))
462 (if fail
463 (warn "Unable to activate package `%s'.
015eea59 464Required package `%s-%s' is unavailable"
4b99edf2
CY
465 package (car fail) (package-version-join (cadr fail)))
466 ;; If all goes well, activate the package itself.
467 (package-activate-1 package pkg-vec)))))))
44198b6e
CY
468
469(defun package-mark-obsolete (package pkg-vec)
470 "Put package on the obsolete list, if not already there."
471 (let ((elt (assq package package-obsolete-alist)))
472 (if elt
473 ;; If this obsolete version does not exist in the list, update
474 ;; it the list.
475 (unless (assoc (package-desc-vers pkg-vec) (cdr elt))
476 (setcdr elt (cons (cons (package-desc-vers pkg-vec) pkg-vec)
477 (cdr elt))))
478 ;; Make a new association.
ebf662f4
CY
479 (push (cons package (list (cons (package-desc-vers pkg-vec)
480 pkg-vec)))
481 package-obsolete-alist))))
44198b6e 482
4b99edf2 483(defun define-package (name-string version-string
187d3296
CY
484 &optional docstring requirements
485 &rest extra-properties)
44198b6e 486 "Define a new package.
4b99edf2
CY
487NAME-STRING is the name of the package, as a string.
488VERSION-STRING is the version of the package, as a list of
489integers of the form produced by `version-to-list'.
490DOCSTRING is a short description of the package, a string.
491REQUIREMENTS is a list of dependencies on other packages.
187d3296
CY
492Each requirement is of the form (OTHER-PACKAGE \"VERSION\").
493
494EXTRA-PROPERTIES is currently unused."
4b99edf2
CY
495 (let* ((name (intern name-string))
496 (version (version-to-list version-string))
44198b6e
CY
497 (new-pkg-desc
498 (cons name
4b99edf2 499 (vector version
44198b6e
CY
500 (mapcar
501 (lambda (elt)
502 (list (car elt)
148cef8e 503 (version-to-list (car (cdr elt)))))
44198b6e 504 requirements)
4b99edf2
CY
505 docstring)))
506 (old-pkg (assq name package-alist)))
507 (cond
508 ;; If there's no old package, just add this to `package-alist'.
509 ((null old-pkg)
510 (push new-pkg-desc package-alist))
511 ((version-list-< (package-desc-vers (cdr old-pkg)) version)
512 ;; Remove the old package and declare it obsolete.
513 (package-mark-obsolete name (cdr old-pkg))
514 (setq package-alist (cons new-pkg-desc
515 (delq old-pkg package-alist))))
516 ;; You can have two packages with the same version, e.g. one in
517 ;; the system package directory and one in your private
518 ;; directory. We just let the first one win.
519 ((not (version-list-= (package-desc-vers (cdr old-pkg)) version))
520 ;; The package is born obsolete.
521 (package-mark-obsolete name (cdr new-pkg-desc))))))
44198b6e
CY
522
523;; From Emacs 22.
524(defun package-autoload-ensure-default-file (file)
525 "Make sure that the autoload file FILE exists and if not create it."
526 (unless (file-exists-p file)
527 (write-region
528 (concat ";;; " (file-name-nondirectory file)
529 " --- automatically extracted autoloads\n"
530 ";;\n"
531 ";;; Code:\n\n"
532 "\f\n;; Local Variables:\n"
533 ";; version-control: never\n"
534 ";; no-byte-compile: t\n"
535 ";; no-update-autoloads: t\n"
536 ";; End:\n"
537 ";;; " (file-name-nondirectory file)
538 " ends here\n")
539 nil file))
540 file)
541
542(defun package-generate-autoloads (name pkg-dir)
543 (let* ((auto-name (concat name "-autoloads.el"))
544 (ignore-name (concat name "-pkg.el"))
545 (generated-autoload-file (expand-file-name auto-name pkg-dir))
546 (version-control 'never))
547 (require 'autoload)
548 (unless (fboundp 'autoload-ensure-default-file)
549 (package-autoload-ensure-default-file generated-autoload-file))
550 (update-directory-autoloads pkg-dir)))
551
552(defun package-untar-buffer ()
553 "Untar the current buffer.
554This uses `tar-untar-buffer' if it is available.
555Otherwise it uses an external `tar' program.
556`default-directory' should be set by the caller."
557 (require 'tar-mode)
558 (if (fboundp 'tar-untar-buffer)
559 (progn
560 ;; tar-mode messes with narrowing, so we just let it have the
561 ;; whole buffer to play with.
562 (delete-region (point-min) (point))
563 (tar-mode)
564 (tar-untar-buffer))
565 ;; FIXME: check the result.
566 (call-process-region (point) (point-max) "tar" nil '(nil nil) nil
567 "xf" "-")))
568
569(defun package-unpack (name version)
570 (let ((pkg-dir (expand-file-name (concat (symbol-name name) "-" version)
571 package-user-dir)))
44198b6e 572 (make-directory package-user-dir t)
015eea59 573 ;; FIXME: should we delete PKG-DIR if it exists?
44198b6e
CY
574 (let* ((default-directory (file-name-as-directory package-user-dir)))
575 (package-untar-buffer)
576 (package-generate-autoloads (symbol-name name) pkg-dir)
577 (let ((load-path (cons pkg-dir load-path)))
578 (byte-recompile-directory pkg-dir 0 t)))))
579
c6affbde 580(defun package--write-file-no-coding (file-name)
bc44bef7 581 (let ((buffer-file-coding-system 'no-conversion))
c6affbde 582 (write-region (point-min) (point-max) file-name)))
bc44bef7 583
44198b6e
CY
584(defun package-unpack-single (file-name version desc requires)
585 "Install the contents of the current buffer as a package."
586 ;; Special case "package".
587 (if (string= file-name "package")
bc44bef7 588 (package--write-file-no-coding
c6affbde 589 (expand-file-name (concat file-name ".el") package-user-dir))
44198b6e
CY
590 (let* ((pkg-dir (expand-file-name (concat file-name "-" version)
591 package-user-dir))
592 (el-file (expand-file-name (concat file-name ".el") pkg-dir))
593 (pkg-file (expand-file-name (concat file-name "-pkg.el") pkg-dir)))
594 (make-directory pkg-dir t)
c6affbde 595 (package--write-file-no-coding el-file)
44198b6e
CY
596 (let ((print-level nil)
597 (print-length nil))
598 (write-region
599 (concat
600 (prin1-to-string
601 (list 'define-package
602 file-name
603 version
604 desc
605 (list 'quote
606 ;; Turn version lists into string form.
607 (mapcar
608 (lambda (elt)
609 (list (car elt)
015eea59 610 (package-version-join (cadr elt))))
44198b6e
CY
611 requires))))
612 "\n")
613 nil
614 pkg-file
615 nil nil nil 'excl))
616 (package-generate-autoloads file-name pkg-dir)
617 (let ((load-path (cons pkg-dir load-path)))
618 (byte-recompile-directory pkg-dir 0 t)))))
619
620(defun package-handle-response ()
621 "Handle the response from the server.
622Parse the HTTP response and throw if an error occurred.
623The url package seems to require extra processing for this.
624This should be called in a `save-excursion', in the download buffer.
625It will move point to somewhere in the headers."
626 ;; We assume HTTP here.
627 (require 'url-http)
628 (let ((response (url-http-parse-response)))
629 (when (or (< response 200) (>= response 300))
630 (display-buffer (current-buffer))
631 (error "Error during download request:%s"
632 (buffer-substring-no-properties (point) (progn
633 (end-of-line)
634 (point)))))))
635
636(defun package-download-single (name version desc requires)
637 "Download and install a single-file package."
638 (let ((buffer (url-retrieve-synchronously
063e5294 639 (concat (package-archive-url name)
44198b6e
CY
640 (symbol-name name) "-" version ".el"))))
641 (with-current-buffer buffer
642 (package-handle-response)
643 (re-search-forward "^$" nil 'move)
644 (forward-char)
645 (delete-region (point-min) (point))
646 (package-unpack-single (symbol-name name) version desc requires)
647 (kill-buffer buffer))))
648
649(defun package-download-tar (name version)
650 "Download and install a tar package."
651 (let ((tar-buffer (url-retrieve-synchronously
063e5294 652 (concat (package-archive-url name)
44198b6e
CY
653 (symbol-name name) "-" version ".tar"))))
654 (with-current-buffer tar-buffer
655 (package-handle-response)
656 (re-search-forward "^$" nil 'move)
657 (forward-char)
658 (package-unpack name version)
659 (kill-buffer tar-buffer))))
660
bc44bef7 661(defun package-installed-p (package &optional min-version)
4b99edf2
CY
662 "Return true if PACKAGE, of VERSION or newer, is installed.
663Built-in packages also qualify."
44198b6e 664 (let ((pkg-desc (assq package package-alist)))
4b99edf2
CY
665 (if pkg-desc
666 (version-list-<= min-version
667 (package-desc-vers (cdr pkg-desc)))
668 ;; Also check built-in packages.
669 (package-built-in-p package min-version))))
44198b6e 670
96ae4c8f
CY
671(defun package-compute-transaction (package-list requirements)
672 "Return a list of packages to be installed, including PACKAGE-LIST.
673PACKAGE-LIST should be a list of package names (symbols).
674
675REQUIREMENTS should be a list of additional requirements; each
676element in this list should have the form (PACKAGE VERSION),
677where PACKAGE is a package name and VERSION is the required
678version of that package (as a list).
679
680This function recursively computes the requirements of the
681packages in REQUIREMENTS, and returns a list of all the packages
682that must be installed. Packages that are already installed are
683not included in this list."
44198b6e
CY
684 (dolist (elt requirements)
685 (let* ((next-pkg (car elt))
686 (next-version (cadr elt)))
687 (unless (package-installed-p next-pkg next-version)
688 ;; A package is required, but not installed. It might also be
689 ;; blocked via `package-load-list'.
690 (let ((pkg-desc (assq next-pkg package-archive-contents))
691 hold)
692 (when (setq hold (assq next-pkg package-load-list))
693 (setq hold (cadr hold))
694 (cond ((eq hold nil)
695 (error "Required package '%s' is disabled"
696 (symbol-name next-pkg)))
697 ((null (stringp hold))
698 (error "Invalid element in `package-load-list'"))
148cef8e 699 ((version-list-< (version-to-list hold) next-version)
015eea59 700 (error "Package `%s' held at version %s, \
44198b6e
CY
701but version %s required"
702 (symbol-name next-pkg) hold
703 (package-version-join next-version)))))
704 (unless pkg-desc
015eea59 705 (error "Package `%s-%s' is unavailable"
4b99edf2
CY
706 (symbol-name next-pkg)
707 (package-version-join next-version)))
148cef8e
CY
708 (unless (version-list-<= next-version
709 (package-desc-vers (cdr pkg-desc)))
44198b6e 710 (error
015eea59 711 "Need package `%s-%s', but only %s is available"
44198b6e
CY
712 (symbol-name next-pkg) (package-version-join next-version)
713 (package-version-join (package-desc-vers (cdr pkg-desc)))))
714 ;; Only add to the transaction if we don't already have it.
96ae4c8f 715 (unless (memq next-pkg package-list)
ebf662f4 716 (push next-pkg package-list))
96ae4c8f
CY
717 (setq package-list
718 (package-compute-transaction package-list
44198b6e
CY
719 (package-desc-reqs
720 (cdr pkg-desc))))))))
96ae4c8f 721 package-list)
44198b6e
CY
722
723(defun package-read-from-string (str)
724 "Read a Lisp expression from STR.
725Signal an error if the entire string was not used."
726 (let* ((read-data (read-from-string str))
187d3296
CY
727 (more-left
728 (condition-case nil
729 ;; The call to `ignore' suppresses a compiler warning.
730 (progn (ignore (read-from-string
731 (substring str (cdr read-data))))
732 t)
733 (end-of-file nil))))
44198b6e
CY
734 (if more-left
735 (error "Can't read whole string")
736 (car read-data))))
737
738(defun package--read-archive-file (file)
739 "Re-read archive file FILE, if it exists.
740Will return the data from the file, or nil if the file does not exist.
741Will throw an error if the archive version is too new."
742 (let ((filename (expand-file-name file package-user-dir)))
187d3296
CY
743 (when (file-exists-p filename)
744 (with-temp-buffer
745 (insert-file-contents-literally filename)
746 (let ((contents (read (current-buffer))))
747 (if (> (car contents) package-archive-version)
748 (error "Package archive version %d is higher than %d"
749 (car contents) package-archive-version))
750 (cdr contents))))))
44198b6e 751
bc44bef7 752(defun package-read-all-archive-contents ()
96ae4c8f
CY
753 "Re-read `archive-contents', if it exists.
754If successful, set `package-archive-contents'."
fbe3be3f 755 (setq package-archive-contents nil)
bc44bef7 756 (dolist (archive package-archives)
96ae4c8f 757 (package-read-archive-contents (car archive))))
44198b6e 758
bc44bef7 759(defun package-read-archive-contents (archive)
187d3296
CY
760 "Re-read archive contents for ARCHIVE.
761If successful, set the variable `package-archive-contents'.
bc44bef7 762If the archive version is too new, signal an error."
187d3296
CY
763 ;; Version 1 of 'archive-contents' is identical to our internal
764 ;; representation.
765 (let* ((dir (concat "archives/" archive))
766 (contents-file (concat dir "/archive-contents"))
767 contents)
768 (when (setq contents (package--read-archive-file contents-file))
769 (dolist (package contents)
770 (package--add-to-archive-contents package archive)))))
bc44bef7
PH
771
772(defun package--add-to-archive-contents (package archive)
773 "Add the PACKAGE from the given ARCHIVE if necessary.
774Also, add the originating archive to the end of the package vector."
775 (let* ((name (car package))
776 (version (aref (cdr package) 0))
777 (entry (cons (car package)
778 (vconcat (cdr package) (vector archive))))
779 (existing-package (cdr (assq name package-archive-contents))))
780 (when (or (not existing-package)
148cef8e 781 (version-list-< (aref existing-package 0) version))
bc44bef7
PH
782 (add-to-list 'package-archive-contents entry))))
783
96ae4c8f
CY
784(defun package-download-transaction (package-list)
785 "Download and install all the packages in PACKAGE-LIST.
786PACKAGE-LIST should be a list of package names (symbols).
787This function assumes that all package requirements in
788PACKAGE-LIST are satisfied, i.e. that PACKAGE-LIST is computed
789using `package-compute-transaction'."
790 (dolist (elt package-list)
44198b6e
CY
791 (let* ((desc (cdr (assq elt package-archive-contents)))
792 ;; As an exception, if package is "held" in
793 ;; `package-load-list', download the held version.
794 (hold (cadr (assq elt package-load-list)))
795 (v-string (or (and (stringp hold) hold)
796 (package-version-join (package-desc-vers desc))))
797 (kind (package-desc-kind desc)))
798 (cond
799 ((eq kind 'tar)
800 (package-download-tar elt v-string))
801 ((eq kind 'single)
802 (package-download-single elt v-string
803 (package-desc-doc desc)
804 (package-desc-reqs desc)))
805 (t
806 (error "Unknown package kind: %s" (symbol-name kind)))))))
807
808;;;###autoload
809(defun package-install (name)
810 "Install the package named NAME.
811Interactively, prompt for the package name.
063e5294 812The package is found on one of the archives in `package-archives'."
44198b6e 813 (interactive
bc44bef7
PH
814 (list (intern (completing-read "Install package: "
815 (mapcar (lambda (elt)
816 (cons (symbol-name (car elt))
817 nil))
818 package-archive-contents)
819 nil t))))
44198b6e
CY
820 (let ((pkg-desc (assq name package-archive-contents)))
821 (unless pkg-desc
015eea59 822 (error "Package `%s' is not available for installation"
44198b6e 823 (symbol-name name)))
bc44bef7
PH
824 (package-download-transaction
825 (package-compute-transaction (list name)
826 (package-desc-reqs (cdr pkg-desc)))))
44198b6e
CY
827 ;; Try to activate it.
828 (package-initialize))
829
830(defun package-strip-rcs-id (v-str)
831 "Strip RCS version ID from the version string.
832If the result looks like a dotted numeric version, return it.
833Otherwise return nil."
834 (if v-str
835 (if (string-match "^[ \t]*[$]Revision:[ \t]\([0-9.]+\)[ \t]*[$]$" v-str)
836 (match-string 1 v-str)
837 (if (string-match "^[0-9.]*$" v-str)
838 v-str))))
839
840(defun package-buffer-info ()
187d3296
CY
841 "Return a vector describing the package in the current buffer.
842The vector has the form
843
844 [FILENAME REQUIRES DESCRIPTION VERSION COMMENTARY]
845
846FILENAME is the file name, a string, sans the \".el\" extension.
44198b6e 847REQUIRES is a requires list, or nil.
187d3296 848DESCRIPTION is the package description, a string.
44198b6e
CY
849VERSION is the version, a string.
850COMMENTARY is the commentary section, a string, or nil if none.
187d3296
CY
851
852If the buffer does not contain a conforming package, signal an
853error. If there is a package, narrow the buffer to the file's
854boundaries."
44198b6e 855 (goto-char (point-min))
187d3296
CY
856 (unless (re-search-forward "^;;; \\([^ ]*\\)\\.el --- \\(.*\\)$" nil t)
857 (error "Packages lacks a file header"))
858 (let ((file-name (match-string-no-properties 1))
859 (desc (match-string-no-properties 2))
860 (start (line-beginning-position)))
861 (unless (search-forward (concat ";;; " file-name ".el ends here"))
862 (error "Package lacks a terminating comment"))
863 ;; Try to include a trailing newline.
864 (forward-line)
865 (narrow-to-region start (point))
866 (require 'lisp-mnt)
867 ;; Use some headers we've invented to drive the process.
868 (let* ((requires-str (lm-header "package-requires"))
869 (requires (if requires-str
870 (package-read-from-string requires-str)))
871 ;; Prefer Package-Version; if defined, the package author
872 ;; probably wants us to use it. Otherwise try Version.
873 (pkg-version
874 (or (package-strip-rcs-id (lm-header "package-version"))
875 (package-strip-rcs-id (lm-header "version"))))
876 (commentary (lm-commentary)))
877 (unless pkg-version
878 (error
879 "Package lacks a \"Version\" or \"Package-Version\" header"))
880 ;; Turn string version numbers into list form.
881 (setq requires
882 (mapcar
883 (lambda (elt)
884 (list (car elt)
885 (version-to-list (car (cdr elt)))))
886 requires))
887 (vector file-name requires desc pkg-version commentary))))
44198b6e
CY
888
889(defun package-tar-file-info (file)
890 "Find package information for a tar file.
891FILE is the name of the tar file to examine.
892The return result is a vector like `package-buffer-info'."
893 (unless (string-match "^\\(.+\\)-\\([0-9.]+\\)\\.tar$" file)
187d3296 894 (error "Invalid package name `%s'" file))
44198b6e
CY
895 (let* ((pkg-name (file-name-nondirectory (match-string-no-properties 1 file)))
896 (pkg-version (match-string-no-properties 2 file))
897 ;; Extract the package descriptor.
898 (pkg-def-contents (shell-command-to-string
899 ;; Requires GNU tar.
900 (concat "tar -xOf " file " "
901 pkg-name "-" pkg-version "/"
902 pkg-name "-pkg.el")))
903 (pkg-def-parsed (package-read-from-string pkg-def-contents)))
904 (unless (eq (car pkg-def-parsed) 'define-package)
187d3296
CY
905 (error "No `define-package' sexp is present in `%s-pkg.el'" pkg-name))
906 (let ((name-str (nth 1 pkg-def-parsed))
44198b6e 907 (version-string (nth 2 pkg-def-parsed))
187d3296
CY
908 (docstring (nth 3 pkg-def-parsed))
909 (requires (nth 4 pkg-def-parsed))
44198b6e
CY
910 (readme (shell-command-to-string
911 ;; Requires GNU tar.
912 (concat "tar -xOf " file " "
913 pkg-name "-" pkg-version "/README"))))
914 (unless (equal pkg-version version-string)
187d3296 915 (error "Package has inconsistent versions"))
44198b6e 916 (unless (equal pkg-name name-str)
187d3296 917 (error "Package has inconsistent names"))
44198b6e
CY
918 ;; Kind of a hack.
919 (if (string-match ": Not found in archive" readme)
920 (setq readme nil))
921 ;; Turn string version numbers into list form.
922 (if (eq (car requires) 'quote)
923 (setq requires (car (cdr requires))))
924 (setq requires
187d3296
CY
925 (mapcar (lambda (elt)
926 (list (car elt)
927 (version-to-list (cadr elt))))
928 requires))
44198b6e
CY
929 (vector pkg-name requires docstring version-string readme))))
930
187d3296
CY
931;;;###autoload
932(defun package-install-from-buffer (pkg-info type)
933 "Install a package from the current buffer.
934When called interactively, the current buffer is assumed to be a
935single .el file that follows the packaging guidelines; see info
936node `(elisp)Packaging'.
937
938When called from Lisp, PKG-INFO is a vector describing the
939information, of the type returned by `package-buffer-info'; and
940TYPE is the package type (either `single' or `tar')."
941 (interactive (list (package-buffer-info) 'single))
44198b6e
CY
942 (save-excursion
943 (save-restriction
944 (let* ((file-name (aref pkg-info 0))
187d3296 945 (requires (aref pkg-info 1))
44198b6e
CY
946 (desc (if (string= (aref pkg-info 2) "")
947 "No description available."
948 (aref pkg-info 2)))
949 (pkg-version (aref pkg-info 3)))
950 ;; Download and install the dependencies.
951 (let ((transaction (package-compute-transaction nil requires)))
952 (package-download-transaction transaction))
953 ;; Install the package itself.
954 (cond
955 ((eq type 'single)
956 (package-unpack-single file-name pkg-version desc requires))
957 ((eq type 'tar)
958 (package-unpack (intern file-name) pkg-version))
959 (t
960 (error "Unknown type: %s" (symbol-name type))))
961 ;; Try to activate it.
962 (package-initialize)))))
963
44198b6e
CY
964;;;###autoload
965(defun package-install-file (file)
966 "Install a package from a file.
967The file can either be a tar file or an Emacs Lisp file."
968 (interactive "fPackage file name: ")
969 (with-temp-buffer
970 (insert-file-contents-literally file)
971 (cond
187d3296
CY
972 ((string-match "\\.el$" file)
973 (package-install-from-buffer (package-buffer-info) 'single))
44198b6e 974 ((string-match "\\.tar$" file)
187d3296 975 (package-install-from-buffer (package-tar-file-info file) 'tar))
44198b6e
CY
976 (t (error "Unrecognized extension `%s'" (file-name-extension file))))))
977
978(defun package-delete (name version)
015eea59
CY
979 (let ((dir (package--dir name version)))
980 (if (string-equal (file-name-directory dir)
981 (file-name-as-directory
982 (expand-file-name package-user-dir)))
983 (progn
984 (delete-directory dir t t)
985 (message "Package `%s-%s' deleted." name version))
986 ;; Don't delete "system" packages
987 (error "Package `%s-%s' is a system package, not deleting"
988 name version))))
44198b6e 989
063e5294 990(defun package-archive-url (name)
bc44bef7
PH
991 "Return the archive containing the package NAME."
992 (let ((desc (cdr (assq (intern-soft name) package-archive-contents))))
993 (cdr (assoc (aref desc (- (length desc) 1)) package-archives))))
994
995(defun package--download-one-archive (archive file)
996 "Download an archive file FILE from ARCHIVE, and cache it locally."
997 (let* ((archive-name (car archive))
998 (archive-url (cdr archive))
999 (dir (expand-file-name "archives" package-user-dir))
1000 (dir (expand-file-name archive-name dir))
1001 (buffer (url-retrieve-synchronously (concat archive-url file))))
44198b6e
CY
1002 (with-current-buffer buffer
1003 (package-handle-response)
1004 (re-search-forward "^$" nil 'move)
1005 (forward-char)
1006 (delete-region (point-min) (point))
ebf662f4
CY
1007 ;; Read the retrieved buffer to make sure it is valid (e.g. it
1008 ;; may fetch a URL redirect page).
1009 (when (listp (read buffer))
1010 (make-directory dir t)
1011 (setq buffer-file-name (expand-file-name file dir))
1012 (let ((version-control 'never))
1013 (save-buffer))))
bc44bef7 1014 (kill-buffer buffer)))
44198b6e
CY
1015
1016(defun package-refresh-contents ()
1017 "Download the ELPA archive description if needed.
ebf662f4
CY
1018This informs Emacs about the latest versions of all packages, and
1019makes them available for download."
44198b6e
CY
1020 (interactive)
1021 (unless (file-exists-p package-user-dir)
1022 (make-directory package-user-dir t))
bc44bef7 1023 (dolist (archive package-archives)
cb6c4991
CY
1024 (condition-case nil
1025 (package--download-one-archive archive "archive-contents")
187d3296 1026 (error (message "Failed to download `%s' archive."
cb6c4991 1027 (car archive)))))
bc44bef7 1028 (package-read-all-archive-contents))
44198b6e 1029
4b99edf2
CY
1030(defvar package--initialized nil)
1031
44198b6e 1032;;;###autoload
4b99edf2 1033(defun package-initialize (&optional no-activate)
44198b6e 1034 "Load Emacs Lisp packages, and activate them.
4b99edf2
CY
1035The variable `package-load-list' controls which packages to load.
1036If optional arg NO-ACTIVATE is non-nil, don't activate packages."
44198b6e 1037 (interactive)
015eea59
CY
1038 (setq package-alist nil
1039 package-obsolete-alist nil)
44198b6e 1040 (package-load-all-descriptors)
bc44bef7 1041 (package-read-all-archive-contents)
4b99edf2
CY
1042 (unless no-activate
1043 (dolist (elt package-alist)
1044 (package-activate (car elt) (package-desc-vers (cdr elt)))))
1045 (setq package--initialized t))
44198b6e
CY
1046
1047\f
cced7584 1048;;;; Package description buffer.
44198b6e 1049
cced7584
CY
1050;;;###autoload
1051(defun describe-package (package)
1052 "Display the full documentation of PACKAGE (a symbol)."
1053 (interactive
8a500a91
CY
1054 (let* ((guess (function-called-at-point))
1055 packages val)
4b99edf2
CY
1056 (require 'finder-inf nil t)
1057 ;; Load the package list if necessary (but don't activate them).
1058 (unless package--initialized
1059 (package-initialize t))
8a500a91 1060 (setq packages (append (mapcar 'car package-alist)
4b99edf2
CY
1061 (mapcar 'car package-archive-contents)
1062 (mapcar 'car package--builtins)))
cced7584
CY
1063 (unless (memq guess packages)
1064 (setq guess nil))
1065 (setq packages (mapcar 'symbol-name packages))
1066 (setq val
1067 (completing-read (if guess
1068 (format "Describe package (default %s): "
1069 guess)
1070 "Describe package: ")
1071 packages nil t nil nil guess))
cb6c4991 1072 (list (if (equal val "") guess (intern val)))))
4b99edf2
CY
1073 (if (or (null package) (not (symbolp package)))
1074 (message "No package specified")
cced7584
CY
1075 (help-setup-xref (list #'describe-package package)
1076 (called-interactively-p 'interactive))
1077 (with-help-window (help-buffer)
1078 (with-current-buffer standard-output
1079 (describe-package-1 package)))))
1080
1081(defun describe-package-1 (package)
96ae4c8f 1082 (require 'lisp-mnt)
cb6c4991
CY
1083 (let ((package-name (symbol-name package))
1084 (built-in (assq package package--builtins))
1085 desc pkg-dir reqs version installable)
cced7584
CY
1086 (prin1 package)
1087 (princ " is ")
4b99edf2
CY
1088 (cond
1089 ;; Loaded packages are in `package-alist'.
1090 ((setq desc (cdr (assq package package-alist)))
1091 (setq version (package-version-join (package-desc-vers desc)))
1092 (if (setq pkg-dir (package--dir package-name version))
1093 (insert "an installed package.\n\n")
1094 ;; This normally does not happen.
1095 (insert "a deleted package.\n\n")))
1096 ;; Available packages are in `package-archive-contents'.
1097 ((setq desc (cdr (assq package package-archive-contents)))
1098 (setq version (package-version-join (package-desc-vers desc))
8adb4c33 1099 installable t)
4b99edf2
CY
1100 (if built-in
1101 (insert "a built-in package.\n\n")
1102 (insert "an uninstalled package.\n\n")))
1103 (built-in
1104 (setq desc (cdr built-in)
1105 version (package-version-join (package-desc-vers desc)))
1106 (insert "a built-in package.\n\n"))
1107 (t
1108 (insert "an orphan package.\n\n")))
cb6c4991 1109
96ae4c8f 1110 (insert " " (propertize "Status" 'font-lock-face 'bold) ": ")
cb6c4991 1111 (cond (pkg-dir
96ae4c8f
CY
1112 (insert (propertize "Installed"
1113 'font-lock-face 'font-lock-comment-face))
cb6c4991
CY
1114 (insert " in `")
1115 ;; Todo: Add button for uninstalling.
1116 (help-insert-xref-button (file-name-as-directory pkg-dir)
1117 'help-package-def pkg-dir)
4b99edf2
CY
1118 (if built-in
1119 (insert "',\n shadowing a "
1120 (propertize "built-in package"
1121 'font-lock-face 'font-lock-builtin-face)
1122 ".")
1123 (insert "'.")))
cb6c4991 1124 (installable
4b99edf2
CY
1125 (if built-in
1126 (insert (propertize "Built-in." 'font-lock-face 'font-lock-builtin-face)
1127 " Alternate version available -- ")
1128 (insert "Available -- "))
1129 (let ((button-text (if (display-graphic-p) "Install" "[Install]"))
cb6c4991
CY
1130 (button-face (if (display-graphic-p)
1131 '(:box (:line-width 2 :color "dark grey")
1132 :background "light grey"
1133 :foreground "black")
1134 'link)))
4b99edf2 1135 (insert-text-button button-text 'face button-face 'follow-link t
cb6c4991
CY
1136 'package-symbol package
1137 'action 'package-install-button-action)))
1138 (built-in
4b99edf2 1139 (insert (propertize "Built-in." 'font-lock-face 'font-lock-builtin-face)))
cb6c4991
CY
1140 (t (insert "Deleted.")))
1141 (insert "\n")
4b99edf2 1142 (and version (> (length version) 0)
96ae4c8f
CY
1143 (insert " "
1144 (propertize "Version" 'font-lock-face 'bold) ": " version "\n"))
4b99edf2
CY
1145
1146 (setq reqs (if desc (package-desc-reqs desc)))
8adb4c33 1147 (when reqs
96ae4c8f 1148 (insert " " (propertize "Requires" 'font-lock-face 'bold) ": ")
8adb4c33
CY
1149 (let ((first t)
1150 name vers text)
1151 (dolist (req reqs)
1152 (setq name (car req)
1153 vers (cadr req)
1154 text (format "%s-%s" (symbol-name name)
1155 (package-version-join vers)))
1156 (cond (first (setq first nil))
1157 ((>= (+ 2 (current-column) (length text))
1158 (window-width))
1159 (insert ",\n "))
1160 (t (insert ", ")))
1161 (help-insert-xref-button text 'help-package name))
1162 (insert "\n")))
96ae4c8f 1163 (insert " " (propertize "Summary" 'font-lock-face 'bold)
4b99edf2 1164 ": " (if desc (package-desc-doc desc)) "\n\n")
cb6c4991 1165
4b99edf2 1166 (if built-in
96ae4c8f
CY
1167 ;; For built-in packages, insert the commentary.
1168 (let ((fn (locate-file (concat package-name ".el") load-path
1169 load-file-rep-suffixes))
1170 (opoint (point)))
1171 (insert (or (lm-commentary fn) ""))
1172 (save-excursion
1173 (goto-char opoint)
1174 (when (re-search-forward "^;;; Commentary:\n" nil t)
1175 (replace-match ""))
1176 (while (re-search-forward "^\\(;+ ?\\)" nil t)
1177 (replace-match ""))))
1178 (let ((readme (expand-file-name (concat package-name "-readme.txt")
1179 package-user-dir)))
1180 ;; For elpa packages, try downloading the commentary. If that
1181 ;; fails, try an existing readme file in `package-user-dir'.
1182 (cond ((let ((buffer (ignore-errors
1183 (url-retrieve-synchronously
1184 (concat (package-archive-url package)
1185 package-name "-readme.txt"))))
1186 response)
1187 (when buffer
1188 (with-current-buffer buffer
1189 (setq response (url-http-parse-response))
1190 (if (or (< response 200) (>= response 300))
1191 (setq response nil)
1192 (setq buffer-file-name
1193 (expand-file-name readme package-user-dir))
1194 (delete-region (point-min) (1+ url-http-end-of-headers))
1195 (save-buffer)))
1196 (when response
1197 (insert-buffer-substring buffer)
1198 (kill-buffer buffer)
1199 t))))
1200 ((file-readable-p readme)
1201 (insert-file-contents readme)
1202 (goto-char (point-max))))))))
cb6c4991
CY
1203
1204(defun package-install-button-action (button)
1205 (let ((package (button-get button 'package-symbol)))
1206 (when (y-or-n-p (format "Install package `%s'? " package))
1207 (package-install package)
1208 (revert-buffer nil t)
1209 (goto-char (point-min)))))
cced7584
CY
1210
1211\f
44198b6e
CY
1212;;;; Package menu mode.
1213
54ea2a0d 1214(defvar package-menu-mode-map
abef340a 1215 (let ((map (copy-keymap special-mode-map))
64eba874 1216 (menu-map (make-sparse-keymap "Package")))
43207249 1217 (set-keymap-parent map button-buffer-map)
8adb4c33 1218 (define-key map "\C-m" 'package-menu-describe-package)
54ea2a0d
JB
1219 (define-key map "n" 'next-line)
1220 (define-key map "p" 'previous-line)
1221 (define-key map "u" 'package-menu-mark-unmark)
1222 (define-key map "\177" 'package-menu-backup-unmark)
1223 (define-key map "d" 'package-menu-mark-delete)
1224 (define-key map "i" 'package-menu-mark-install)
54ea2a0d
JB
1225 (define-key map "r" 'package-menu-refresh)
1226 (define-key map "~" 'package-menu-mark-obsolete-for-deletion)
1227 (define-key map "x" 'package-menu-execute)
1228 (define-key map "h" 'package-menu-quick-help)
cb6c4991 1229 (define-key map "?" 'package-menu-describe-package)
96ae4c8f
CY
1230 (define-key map [follow-link] 'mouse-face)
1231 (define-key map [mouse-2] 'mouse-select-window)
64eba874
DN
1232 (define-key map [menu-bar package-menu] (cons "Package" menu-map))
1233 (define-key menu-map [mq]
1234 '(menu-item "Quit" quit-window
1235 :help "Quit package selection"))
1236 (define-key menu-map [s1] '("--"))
1237 (define-key menu-map [mn]
1238 '(menu-item "Next" next-line
1239 :help "Next Line"))
1240 (define-key menu-map [mp]
1241 '(menu-item "Previous" previous-line
1242 :help "Previous Line"))
1243 (define-key menu-map [s2] '("--"))
1244 (define-key menu-map [mu]
1245 '(menu-item "Unmark" package-menu-mark-unmark
1246 :help "Clear any marks on a package and move to the next line"))
1247 (define-key menu-map [munm]
1248 '(menu-item "Unmark backwards" package-menu-backup-unmark
1249 :help "Back up one line and clear any marks on that package"))
1250 (define-key menu-map [md]
1251 '(menu-item "Mark for deletion" package-menu-mark-delete
1252 :help "Mark a package for deletion and move to the next line"))
1253 (define-key menu-map [mi]
1254 '(menu-item "Mark for install" package-menu-mark-install
1255 :help "Mark a package for installation and move to the next line"))
1256 (define-key menu-map [s3] '("--"))
1257 (define-key menu-map [mg]
e687c2cd 1258 '(menu-item "Update package list" revert-buffer
64eba874
DN
1259 :help "Update the list of packages"))
1260 (define-key menu-map [mr]
1261 '(menu-item "Refresh package list" package-menu-refresh
1262 :help "Download the ELPA archive"))
1263 (define-key menu-map [s4] '("--"))
1264 (define-key menu-map [mt]
1265 '(menu-item "Mark obsolete packages" package-menu-mark-obsolete-for-deletion
1266 :help "Mark all obsolete packages for deletion"))
1267 (define-key menu-map [mx]
1268 '(menu-item "Execute actions" package-menu-execute
1269 :help "Perform all the marked actions"))
1270 (define-key menu-map [s5] '("--"))
1271 (define-key menu-map [mh]
1272 '(menu-item "Help" package-menu-quick-help
1273 :help "Show short key binding help for package-menu-mode"))
1274 (define-key menu-map [mc]
1275 '(menu-item "View Commentary" package-menu-view-commentary
1276 :help "Display information about this package"))
54ea2a0d 1277 map)
44198b6e
CY
1278 "Local keymap for `package-menu-mode' buffers.")
1279
44198b6e
CY
1280(defvar package-menu-sort-button-map
1281 (let ((map (make-sparse-keymap)))
1282 (define-key map [header-line mouse-1] 'package-menu-sort-by-column)
96ae4c8f 1283 (define-key map [header-line mouse-2] 'package-menu-sort-by-column)
44198b6e
CY
1284 (define-key map [follow-link] 'mouse-face)
1285 map)
1286 "Local keymap for package menu sort buttons.")
1287
1288(put 'package-menu-mode 'mode-class 'special)
1289
abef340a 1290(define-derived-mode package-menu-mode special-mode "Package Menu"
44198b6e
CY
1291 "Major mode for browsing a list of packages.
1292Letters do not insert themselves; instead, they are commands.
1293\\<package-menu-mode-map>
1294\\{package-menu-mode-map}"
44198b6e
CY
1295 (setq truncate-lines t)
1296 (setq buffer-read-only t)
cd205c76 1297 (set (make-local-variable 'revert-buffer-function) 'package-menu-revert)
187d3296
CY
1298 (setq header-line-format
1299 (mapconcat
1300 (lambda (pair)
1301 (let ((column (car pair))
1302 (name (cdr pair)))
1303 (concat
1304 ;; Insert a space that aligns the button properly.
1305 (propertize " " 'display (list 'space :align-to column)
1306 'face 'fixed-pitch)
1307 ;; Set up the column button.
1308 (propertize name
1309 'column-name name
1310 'help-echo "mouse-1: sort by column"
1311 'mouse-face 'highlight
1312 'keymap package-menu-sort-button-map))))
1313 ;; We take a trick from buff-menu and have a dummy leading
1314 ;; space to align the header line with the beginning of the
1315 ;; text. This doesn't really work properly on Emacs 21, but
1316 ;; it is close enough.
1317 '((0 . "")
1318 (2 . "Package")
1319 (20 . "Version")
1320 (32 . "Status")
1321 (43 . "Description"))
abef340a 1322 "")))
44198b6e
CY
1323
1324(defun package-menu-refresh ()
ebf662f4
CY
1325 "Download the Emacs Lisp package archive.
1326This fetches the contents of each archive specified in
1327`package-archives', and then refreshes the package menu."
44198b6e 1328 (interactive)
187d3296
CY
1329 (unless (eq major-mode 'package-menu-mode)
1330 (error "The current buffer is not a Package Menu"))
44198b6e 1331 (package-refresh-contents)
96ae4c8f 1332 (package--generate-package-list))
44198b6e 1333
e687c2cd
CY
1334(defun package-menu-revert (&optional arg noconfirm)
1335 "Update the list of packages.
1336This function is the `revert-buffer-function' for Package Menu
1337buffers. The arguments are ignored."
44198b6e 1338 (interactive)
187d3296
CY
1339 (unless (eq major-mode 'package-menu-mode)
1340 (error "The current buffer is not a Package Menu"))
96ae4c8f 1341 (package--generate-package-list))
44198b6e 1342
8adb4c33
CY
1343(defun package-menu-describe-package ()
1344 "Describe the package in the current line."
1345 (interactive)
1346 (let ((name (package-menu-get-package)))
1347 (if name
1348 (describe-package (intern name))
1349 (message "No package on this line"))))
1350
44198b6e
CY
1351(defun package-menu-mark-internal (what)
1352 (unless (eobp)
1353 (let ((buffer-read-only nil))
1354 (beginning-of-line)
1355 (delete-char 1)
1356 (insert what)
1357 (forward-line))))
1358
1359;; fixme numeric argument
1360(defun package-menu-mark-delete (num)
1361 "Mark a package for deletion and move to the next line."
1362 (interactive "p")
015eea59
CY
1363 (if (string-equal (package-menu-get-status) "installed")
1364 (package-menu-mark-internal "D")
1365 (forward-line)))
44198b6e
CY
1366
1367(defun package-menu-mark-install (num)
1368 "Mark a package for installation and move to the next line."
1369 (interactive "p")
015eea59
CY
1370 (if (string-equal (package-menu-get-status) "available")
1371 (package-menu-mark-internal "I")
1372 (forward-line)))
44198b6e
CY
1373
1374(defun package-menu-mark-unmark (num)
1375 "Clear any marks on a package and move to the next line."
1376 (interactive "p")
1377 (package-menu-mark-internal " "))
1378
1379(defun package-menu-backup-unmark ()
1380 "Back up one line and clear any marks on that package."
1381 (interactive)
1382 (forward-line -1)
1383 (package-menu-mark-internal " ")
1384 (forward-line -1))
1385
1386(defun package-menu-mark-obsolete-for-deletion ()
1387 "Mark all obsolete packages for deletion."
1388 (interactive)
1389 (save-excursion
1390 (goto-char (point-min))
1391 (forward-line 2)
1392 (while (not (eobp))
1393 (if (looking-at ".*\\s obsolete\\s ")
1394 (package-menu-mark-internal "D")
1395 (forward-line 1)))))
1396
1397(defun package-menu-quick-help ()
1398 "Show short key binding help for package-menu-mode."
1399 (interactive)
1400 (message "n-ext, i-nstall, d-elete, u-nmark, x-ecute, r-efresh, h-elp"))
1401
cb6c4991
CY
1402(define-obsolete-function-alias
1403 'package-menu-view-commentary 'package-menu-describe-package "24.1")
44198b6e
CY
1404
1405;; Return the name of the package on the current line.
1406(defun package-menu-get-package ()
1407 (save-excursion
1408 (beginning-of-line)
1409 (if (looking-at ". \\([^ \t]*\\)")
8adb4c33 1410 (match-string-no-properties 1))))
44198b6e
CY
1411
1412;; Return the version of the package on the current line.
1413(defun package-menu-get-version ()
1414 (save-excursion
1415 (beginning-of-line)
1416 (if (looking-at ". [^ \t]*[ \t]*\\([0-9.]*\\)")
1417 (match-string 1))))
1418
1419(defun package-menu-get-status ()
1420 (save-excursion
1421 (if (looking-at ". [^ \t]*[ \t]*[^ \t]*[ \t]*\\([^ \t]*\\)")
1422 (match-string 1)
1423 "")))
1424
1425(defun package-menu-execute ()
015eea59
CY
1426 "Perform marked Package Menu actions.
1427Packages marked for installation are downloaded and installed;
1428packages marked for deletion are removed."
44198b6e 1429 (interactive)
015eea59
CY
1430 (let (install-list delete-list cmd)
1431 (save-excursion
1432 (goto-char (point-min))
1433 (while (not (eobp))
1434 (setq cmd (char-after))
1435 (cond
1436 ((eq cmd ?\s) t)
1437 ((eq cmd ?D)
1438 (push (cons (package-menu-get-package)
1439 (package-menu-get-version))
1440 delete-list))
1441 ((eq cmd ?I)
1442 (push (package-menu-get-package) install-list)))
1443 (forward-line)))
1444 ;; Delete packages, prompting if necessary.
1445 (when delete-list
1446 (if (yes-or-no-p
1447 (if (= (length delete-list) 1)
1448 (format "Delete package `%s-%s'? "
1449 (caar delete-list)
1450 (cdr (car delete-list)))
1451 (format "Delete these %d packages (%s)? "
1452 (length delete-list)
1453 (mapconcat (lambda (elt)
1454 (concat (car elt) "-" (cdr elt)))
1455 delete-list
1456 ", "))))
1457 (dolist (elt delete-list)
1458 (condition-case err
1459 (package-delete (car elt) (cdr elt))
1460 (error (message (cadr err)))))
1461 (error "Aborted")))
1462 (when install-list
1463 (if (yes-or-no-p
1464 (if (= (length install-list) 1)
1465 (format "Install package `%s'? " (car install-list))
1466 (format "Install these %d packages (%s)? "
1467 (length install-list)
1468 (mapconcat 'identity install-list ", "))))
1469 (dolist (elt install-list)
1470 (package-install (intern elt)))))
1471 ;; If we deleted anything, regenerate `package-alist'. This is done
1472 ;; automatically if we installed a package.
1473 (and delete-list (null install-list)
1474 (package-initialize))
1475 (if (or delete-list install-list)
1476 (package-menu-revert)
1477 (message "No operations specified."))))
44198b6e
CY
1478
1479(defun package-print-package (package version key desc)
1480 (let ((face
376c2b6b 1481 (cond ((string= key "built-in") 'font-lock-builtin-face)
44198b6e
CY
1482 ((string= key "available") 'default)
1483 ((string= key "held") 'font-lock-constant-face)
1484 ((string= key "disabled") 'font-lock-warning-face)
1485 ((string= key "installed") 'font-lock-comment-face)
1486 (t ; obsolete, but also the default.
1487 'font-lock-warning-face))))
1488 (insert (propertize " " 'font-lock-face face))
8adb4c33
CY
1489 (insert-text-button (symbol-name package)
1490 'face 'link
1491 'follow-link t
1492 'package-symbol package
1493 'action (lambda (button)
1494 (describe-package
1495 (button-get button 'package-symbol))))
44198b6e
CY
1496 (indent-to 20 1)
1497 (insert (propertize (package-version-join version) 'font-lock-face face))
8adb4c33 1498 (indent-to 32 1)
44198b6e
CY
1499 (insert (propertize key 'font-lock-face face))
1500 ;; FIXME: this 'when' is bogus...
1501 (when desc
8adb4c33 1502 (indent-to 43 1)
376c2b6b
CY
1503 (let ((opoint (point)))
1504 (insert (propertize desc 'font-lock-face face))
1505 (upcase-region opoint (min (point) (1+ opoint)))))
44198b6e
CY
1506 (insert "\n")))
1507
1508(defun package-list-maybe-add (package version status description result)
1509 (unless (assoc (cons package version) result)
ebf662f4 1510 (push (list (cons package version) status description) result))
44198b6e
CY
1511 result)
1512
187d3296
CY
1513(defvar package-menu-package-list nil
1514 "List of packages to display in the Package Menu buffer.
1515A value of nil means to display all packages.")
44198b6e 1516
187d3296
CY
1517(defvar package-menu-sort-key nil
1518 "Sort key for the current Package Menu buffer.")
1519
1520(defun package--generate-package-list ()
1521 "Populate the current Package Menu buffer."
187d3296
CY
1522 (let ((inhibit-read-only t)
1523 info-list name desc hold builtin)
44198b6e 1524 (erase-buffer)
187d3296
CY
1525 ;; List installed packages
1526 (dolist (elt package-alist)
1527 (setq name (car elt))
4b99edf2
CY
1528 (when (or (null package-menu-package-list)
1529 (memq name package-menu-package-list))
187d3296 1530 (setq desc (cdr elt)
4b99edf2 1531 hold (cadr (assq name package-load-list)))
187d3296
CY
1532 (setq info-list
1533 (package-list-maybe-add
1534 name (package-desc-vers desc)
1535 ;; FIXME: it turns out to be tricky to see if this
1536 ;; package is presently activated.
4b99edf2
CY
1537 (if (stringp hold) "held" "installed")
1538 (package-desc-doc desc)
1539 info-list))))
1540
1541 ;; List built-in packages
1542 (dolist (elt package--builtins)
1543 (setq name (car elt))
1544 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
1545 (or (null package-menu-package-list)
1546 (memq name package-menu-package-list)))
1547 (setq desc (cdr elt))
1548 (setq info-list
1549 (package-list-maybe-add
1550 name (package-desc-vers desc)
1551 "built-in"
187d3296
CY
1552 (package-desc-doc desc)
1553 info-list))))
1554
1555 ;; List available and disabled packages
1556 (dolist (elt package-archive-contents)
1557 (setq name (car elt)
1558 desc (cdr elt)
1559 hold (assq name package-load-list))
1560 (when (or (null package-menu-package-list)
1561 (memq name package-menu-package-list))
1562 (setq info-list
1563 (package-list-maybe-add name
1564 (package-desc-vers desc)
1565 (if (and hold (null (cadr hold)))
1566 "disabled"
1567 "available")
1568 (package-desc-doc (cdr elt))
1569 info-list))))
1570 ;; List obsolete packages
1571 (mapc (lambda (elt)
1572 (mapc (lambda (inner-elt)
1573 (setq info-list
1574 (package-list-maybe-add (car elt)
1575 (package-desc-vers
1576 (cdr inner-elt))
1577 "obsolete"
1578 (package-desc-doc
1579 (cdr inner-elt))
1580 info-list)))
1581 (cdr elt)))
1582 package-obsolete-alist)
1583
1584 (setq info-list
1585 (sort info-list
1586 (cond ((string= package-menu-sort-key "Package")
1587 'package-menu--name-predicate)
1588 ((string= package-menu-sort-key "Version")
1589 'package-menu--version-predicate)
1590 ((string= package-menu-sort-key "Description")
1591 'package-menu--description-predicate)
1592 (t ; By default, sort by package status
1593 'package-menu--status-predicate))))
1594
1595 (dolist (elt info-list)
1596 (package-print-package (car (car elt))
1597 (cdr (car elt))
1598 (car (cdr elt))
1599 (car (cdr (cdr elt)))))
44198b6e 1600 (goto-char (point-min))
96ae4c8f 1601 (set-buffer-modified-p nil)
44198b6e
CY
1602 (current-buffer)))
1603
96ae4c8f 1604(defun package-menu--version-predicate (left right)
187d3296
CY
1605 (let ((vleft (or (cdr (car left)) '(0)))
1606 (vright (or (cdr (car right)) '(0))))
1607 (if (version-list-= vleft vright)
96ae4c8f 1608 (package-menu--name-predicate left right)
187d3296 1609 (version-list-< vleft vright))))
96ae4c8f
CY
1610
1611(defun package-menu--status-predicate (left right)
1612 (let ((sleft (cadr left))
1613 (sright (cadr right)))
1614 (cond ((string= sleft sright)
1615 (package-menu--name-predicate left right))
1616 ((string= sleft "available") t)
1617 ((string= sright "available") nil)
1618 ((string= sleft "installed") t)
1619 ((string= sright "installed") nil)
1620 ((string= sleft "held") t)
1621 ((string= sright "held") nil)
1622 ((string= sleft "built-in") t)
1623 ((string= sright "built-in") nil)
1624 ((string= sleft "obsolete") t)
1625 ((string= sright "obsolete") nil)
1626 (t (string< sleft sright)))))
1627
1628(defun package-menu--description-predicate (left right)
1629 (let ((sleft (car (cddr left)))
1630 (sright (car (cddr right))))
1631 (if (string= sleft sright)
1632 (package-menu--name-predicate left right)
1633 (string< sleft sright))))
1634
1635(defun package-menu--name-predicate (left right)
1636 (string< (symbol-name (caar left))
1637 (symbol-name (caar right))))
1638
44198b6e 1639(defun package-menu-sort-by-column (&optional e)
187d3296 1640 "Sort the package menu by the column of the mouse click E."
96ae4c8f 1641 (interactive "e")
44198b6e 1642 (let* ((pos (event-start e))
187d3296
CY
1643 (obj (posn-object pos))
1644 (col (if obj
1645 (get-text-property (cdr obj) 'column-name (car obj))
1646 (get-text-property (posn-point pos) 'column-name)))
1647 (buf (window-buffer (posn-window (event-start e)))))
1648 (with-current-buffer buf
1649 (when (eq major-mode 'package-menu-mode)
1650 (setq package-menu-sort-key col)
1651 (package--generate-package-list)))))
96ae4c8f
CY
1652
1653(defun package--list-packages (&optional packages)
187d3296
CY
1654 "Generate and pop to the *Packages* buffer.
1655Optional PACKAGES is a list of names of packages (symbols) to
1656list; the default is to display everything in `package-alist'."
4b99edf2 1657 (require 'finder-inf nil t)
2a8b13af
CY
1658 (let ((buf (get-buffer-create "*Packages*")))
1659 (with-current-buffer buf
2a8b13af
CY
1660 (set (make-local-variable 'package-menu-package-list) packages)
1661 (set (make-local-variable 'package-menu-sort-key) nil)
e90f8545
SS
1662 (package--generate-package-list)
1663 (package-menu-mode))
2a8b13af
CY
1664 ;; The package menu buffer has keybindings. If the user types
1665 ;; `M-x list-packages', that suggests it should become current.
1666 (switch-to-buffer buf)))
44198b6e
CY
1667
1668;;;###autoload
96ae4c8f 1669(defun list-packages ()
44198b6e
CY
1670 "Display a list of packages.
1671Fetches the updated list of packages before displaying.
1672The list is displayed in a buffer named `*Packages*'."
1673 (interactive)
8a500a91 1674 ;; Initialize the package system if necessary.
4b99edf2
CY
1675 (unless package--initialized
1676 (package-initialize t))
44198b6e
CY
1677 (package-refresh-contents)
1678 (package--list-packages))
1679
cb8759ca 1680;;;###autoload
96ae4c8f 1681(defalias 'package-list-packages 'list-packages)
cb8759ca 1682
44198b6e
CY
1683(defun package-list-packages-no-fetch ()
1684 "Display a list of packages.
1685Does not fetch the updated list of packages before displaying.
1686The list is displayed in a buffer named `*Packages*'."
1687 (interactive)
1688 (package--list-packages))
1689
44198b6e
CY
1690(provide 'package)
1691
1692;;; package.el ends here