Silence compilation of nndiary.el.
[bpt/emacs.git] / lisp / emacs-lisp / package.el
CommitLineData
44198b6e
CY
1;;; package.el --- Simple package system for Emacs
2
3;; Copyright (C) 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
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;;
80;; M-x package-list-packages
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))
218(declare-function dired-delete-file "dired" (file &optional recursive trash))
cb6c4991 219(defvar url-http-end-of-headers)
44198b6e 220
bc44bef7
PH
221(defcustom package-archives '(("gnu" . "http://elpa.gnu.org/packages/"))
222 "An alist of archives from which to fetch.
223The default value points to the GNU Emacs package repository.
224Each element has the form (ID . URL), where ID is an identifier
225string for an archive and URL is a http: URL (a string)."
226 :type '(alist :key-type (string :tag "Archive name")
227 :value-type (string :tag "Archive URL"))
228 :risky t
229 :group 'package
230 :version "24.1")
44198b6e
CY
231
232(defconst package-archive-version 1
233 "Version number of the package archive understood by this file.
234Lower version numbers than this will probably be understood as well.")
235
236(defconst package-el-version "1.0"
237 "Version of package.el.")
238
239;; We don't prime the cache since it tends to get out of date.
240(defvar package-archive-contents nil
241 "Cache of the contents of the Emacs Lisp Package Archive.
242This is an alist mapping package names (symbols) to package
243descriptor vectors. These are like the vectors for `package-alist'
bc44bef7
PH
244but have extra entries: one which is 'tar for tar packages and
245'single for single-file packages, and one which is the name of
246the archive from which it came.")
247(put 'package-archive-contents 'risky-local-variable t)
44198b6e
CY
248
249(defcustom package-user-dir (locate-user-emacs-file "elpa")
250 "Directory containing the user's Emacs Lisp packages.
251The directory name should be absolute.
252Apart from this directory, Emacs also looks for system-wide
253packages in `package-directory-list'."
254 :type 'directory
bc44bef7 255 :risky t
44198b6e
CY
256 :group 'package
257 :version "24.1")
258
259(defcustom package-directory-list
260 ;; Defaults are subdirs named "elpa" in the site-lisp dirs.
261 (let (result)
262 (dolist (f load-path)
0be01d2c
CY
263 (and (stringp f)
264 (equal (file-name-nondirectory f) "site-lisp")
265 (push (expand-file-name "elpa" f) result)))
44198b6e
CY
266 (nreverse result))
267 "List of additional directories containing Emacs Lisp packages.
268Each directory name should be absolute.
269
270These directories contain packages intended for system-wide; in
271contrast, `package-user-dir' contains packages for personal use."
272 :type '(repeat directory)
bc44bef7 273 :risky t
44198b6e
CY
274 :group 'package
275 :version "24.1")
276
96ae4c8f
CY
277;; The value is precomputed in finder-inf.el, but don't load that
278;; until it's needed (i.e. when `package-intialize' is called).
279(defvar package--builtins nil
280 "Alist of built-in packages.
281Each element has the form (PKG . DESC), where PKG is a package
282name (a symbol) and DESC is a vector that describes the package.
283
284The vector DESC has the form [VERSION REQS DOCSTRING].
285 VERSION is a version list.
286 REQS is a list of packages (symbols) required by the package.
287 DOCSTRING is a brief description of the package.")
bc44bef7 288(put 'package--builtins 'risky-local-variable t)
44198b6e 289
96ae4c8f 290(defvar package-alist nil
44198b6e 291 "Alist of all packages available for activation.
96ae4c8f
CY
292Each element has the form (PKG . DESC), where PKG is a package
293name (a symbol) and DESC is a vector that describes the package.
44198b6e 294
96ae4c8f
CY
295The vector DESC has the form [VERSION REQS DOCSTRING].
296 VERSION is a version list.
297 REQS is a list of packages (symbols) required by the package.
298 DOCSTRING is a brief description of the package.
299
300This variable is set automatically by `package-load-descriptor',
301called via `package-initialize'. To change which packages are
302loaded and/or activated, customize `package-load-list'.")
bc44bef7 303(put 'package-archive-contents 'risky-local-variable t)
44198b6e 304
96ae4c8f 305(defvar package-activated-list nil
44198b6e 306 "List of the names of currently activated packages.")
bc44bef7 307(put 'package-activated-list 'risky-local-variable t)
44198b6e
CY
308
309(defvar package-obsolete-alist nil
310 "Representation of obsolete packages.
311Like `package-alist', but maps package name to a second alist.
312The inner alist is keyed by version.")
bc44bef7 313(put 'package-obsolete-alist 'risky-local-variable t)
44198b6e
CY
314
315(defconst package-subdirectory-regexp
316 "^\\([^.].*\\)-\\([0-9]+\\(?:[.][0-9]+\\)*\\)$"
317 "Regular expression matching the name of a package subdirectory.
318The first subexpression is the package name.
319The second subexpression is the version string.")
320
321(defun package-version-join (l)
322 "Turn a list of version numbers into a version string."
323 (mapconcat 'int-to-string l "."))
324
44198b6e
CY
325(defun package-strip-version (dirname)
326 "Strip the version from a combined package name and version.
327E.g., if given \"quux-23.0\", will return \"quux\""
328 (if (string-match package-subdirectory-regexp dirname)
329 (match-string 1 dirname)))
330
331(defun package-load-descriptor (dir package)
bc44bef7
PH
332 "Load the description file in directory DIR for package PACKAGE."
333 (let* ((pkg-dir (expand-file-name package dir))
334 (pkg-file (expand-file-name
335 (concat (package-strip-version package) "-pkg")
336 pkg-dir)))
337 (when (and (file-directory-p pkg-dir)
338 (file-exists-p (concat pkg-file ".el")))
339 (load pkg-file nil t))))
44198b6e
CY
340
341(defun package-load-all-descriptors ()
342 "Load descriptors for installed Emacs Lisp packages.
343This looks for package subdirectories in `package-user-dir' and
344`package-directory-list'. The variable `package-load-list'
345controls which package subdirectories may be loaded.
346
347In each valid package subdirectory, this function loads the
348description file containing a call to `define-package', which
349updates `package-alist' and `package-obsolete-alist'."
350 (let ((all (memq 'all package-load-list))
351 name version force)
352 (dolist (dir (cons package-user-dir package-directory-list))
353 (when (file-directory-p dir)
354 (dolist (subdir (directory-files dir))
355 (when (and (file-directory-p (expand-file-name subdir dir))
356 (string-match package-subdirectory-regexp subdir))
357 (setq name (intern (match-string 1 subdir))
358 version (match-string 2 subdir)
359 force (assq name package-load-list))
360 (when (cond
361 ((null force)
362 all) ; not in package-load-list
363 ((null (setq force (cadr force)))
364 nil) ; disabled
365 ((eq force t)
366 t)
367 ((stringp force) ; held
148cef8e
CY
368 (version-list-= (version-to-list version)
369 (version-to-list force)))
44198b6e
CY
370 (t
371 (error "Invalid element in `package-load-list'")))
372 (package-load-descriptor dir subdir))))))))
373
374(defsubst package-desc-vers (desc)
375 "Extract version from a package description vector."
376 (aref desc 0))
377
378(defsubst package-desc-reqs (desc)
379 "Extract requirements from a package description vector."
380 (aref desc 1))
381
382(defsubst package-desc-doc (desc)
383 "Extract doc string from a package description vector."
384 (aref desc 2))
385
386(defsubst package-desc-kind (desc)
387 "Extract the kind of download from an archive package description vector."
388 (aref desc 3))
389
cced7584
CY
390(defun package--dir (name version-string)
391 (let* ((subdir (concat name "-" version-string))
44198b6e 392 (dir-list (cons package-user-dir package-directory-list))
cced7584 393 pkg-dir)
44198b6e 394 (while dir-list
cced7584
CY
395 (let ((subdir-full (expand-file-name subdir (car dir-list))))
396 (if (file-directory-p subdir-full)
397 (setq pkg-dir subdir-full
398 dir-list nil)
44198b6e 399 (setq dir-list (cdr dir-list)))))
cced7584
CY
400 pkg-dir))
401
402(defun package-activate-1 (package pkg-vec)
403 (let* ((name (symbol-name package))
404 (version-str (package-version-join (package-desc-vers pkg-vec)))
405 (pkg-dir (package--dir name version-str)))
44198b6e
CY
406 (unless pkg-dir
407 (error "Internal error: could not find directory for %s-%s"
cced7584
CY
408 name version-str))
409 ;; Add info node.
ebf662f4
CY
410 (when (file-exists-p (expand-file-name "dir" pkg-dir))
411 ;; FIXME: not the friendliest, but simple.
412 (require 'info)
413 (info-initialize)
414 (push pkg-dir Info-directory-list))
cced7584 415 ;; Add to load path, add autoloads, and activate the package.
ebf662f4 416 (push pkg-dir load-path)
cced7584 417 (load (expand-file-name (concat name "-autoloads") pkg-dir) nil t)
ebf662f4 418 (push package package-activated-list)
44198b6e
CY
419 ;; Don't return nil.
420 t))
421
422(defun package--built-in (package version)
423 "Return true if the package is built-in to Emacs."
424 (let ((elt (assq package package--builtins)))
148cef8e 425 (and elt (version-list-= (package-desc-vers (cdr elt)) version))))
44198b6e
CY
426
427;; FIXME: return a reason instead?
428(defun package-activate (package version)
429 "Activate a package, and recursively activate its dependencies.
430Return nil if the package could not be activated."
431 ;; Assume the user knows what he is doing -- go ahead and activate a
432 ;; newer version of a package if an older one has already been
433 ;; activated. This is not ideal; we'd at least need to check to see
434 ;; if the package has actually been loaded, and not merely
435 ;; activated. However, don't try to activate 'emacs', as that makes
436 ;; no sense.
437 (unless (eq package 'emacs)
438 (let* ((pkg-desc (assq package package-alist))
439 (this-version (package-desc-vers (cdr pkg-desc)))
440 (req-list (package-desc-reqs (cdr pkg-desc)))
cced7584 441 ;; If the package was never activated, do it now.
44198b6e 442 (keep-going (or (not (memq package package-activated-list))
148cef8e 443 (version-list-< version this-version))))
44198b6e
CY
444 (while (and req-list keep-going)
445 (let* ((req (car req-list))
446 (req-name (car req))
447 (req-version (cadr req)))
448 (or (package-activate req-name req-version)
449 (setq keep-going nil)))
450 (setq req-list (cdr req-list)))
451 (if keep-going
452 (package-activate-1 package (cdr pkg-desc))
453 ;; We get here if a dependency failed to activate -- but we
454 ;; can also get here if the requested package was already
455 ;; activated. Return non-nil in the latter case.
456 (and (memq package package-activated-list)
148cef8e 457 (version-list-<= version this-version))))))
44198b6e
CY
458
459(defun package-mark-obsolete (package pkg-vec)
460 "Put package on the obsolete list, if not already there."
461 (let ((elt (assq package package-obsolete-alist)))
462 (if elt
463 ;; If this obsolete version does not exist in the list, update
464 ;; it the list.
465 (unless (assoc (package-desc-vers pkg-vec) (cdr elt))
466 (setcdr elt (cons (cons (package-desc-vers pkg-vec) pkg-vec)
467 (cdr elt))))
468 ;; Make a new association.
ebf662f4
CY
469 (push (cons package (list (cons (package-desc-vers pkg-vec)
470 pkg-vec)))
471 package-obsolete-alist))))
44198b6e 472
44198b6e 473(defun define-package (name-str version-string
187d3296
CY
474 &optional docstring requirements
475 &rest extra-properties)
44198b6e
CY
476 "Define a new package.
477NAME is the name of the package, a string.
478VERSION-STRING is the version of the package, a dotted sequence
479of integers.
480DOCSTRING is the optional description.
481REQUIREMENTS is a list of requirements on other packages.
187d3296
CY
482Each requirement is of the form (OTHER-PACKAGE \"VERSION\").
483
484EXTRA-PROPERTIES is currently unused."
44198b6e
CY
485 (let* ((name (intern name-str))
486 (pkg-desc (assq name package-alist))
148cef8e 487 (new-version (version-to-list version-string))
44198b6e
CY
488 (new-pkg-desc
489 (cons name
490 (vector new-version
491 (mapcar
492 (lambda (elt)
493 (list (car elt)
148cef8e 494 (version-to-list (car (cdr elt)))))
44198b6e
CY
495 requirements)
496 docstring))))
497 ;; Only redefine a package if the redefinition is newer.
498 (if (or (not pkg-desc)
148cef8e
CY
499 (version-list-< (package-desc-vers (cdr pkg-desc))
500 new-version))
44198b6e
CY
501 (progn
502 (when pkg-desc
503 ;; Remove old package and declare it obsolete.
504 (setq package-alist (delq pkg-desc package-alist))
505 (package-mark-obsolete (car pkg-desc) (cdr pkg-desc)))
506 ;; Add package to the alist.
ebf662f4 507 (push new-pkg-desc package-alist))
44198b6e
CY
508 ;; You can have two packages with the same version, for instance
509 ;; one in the system package directory and one in your private
510 ;; directory. We just let the first one win.
148cef8e
CY
511 (unless (version-list-= new-version
512 (package-desc-vers (cdr pkg-desc)))
44198b6e
CY
513 ;; The package is born obsolete.
514 (package-mark-obsolete (car new-pkg-desc) (cdr new-pkg-desc))))))
515
516;; From Emacs 22.
517(defun package-autoload-ensure-default-file (file)
518 "Make sure that the autoload file FILE exists and if not create it."
519 (unless (file-exists-p file)
520 (write-region
521 (concat ";;; " (file-name-nondirectory file)
522 " --- automatically extracted autoloads\n"
523 ";;\n"
524 ";;; Code:\n\n"
525 "\f\n;; Local Variables:\n"
526 ";; version-control: never\n"
527 ";; no-byte-compile: t\n"
528 ";; no-update-autoloads: t\n"
529 ";; End:\n"
530 ";;; " (file-name-nondirectory file)
531 " ends here\n")
532 nil file))
533 file)
534
535(defun package-generate-autoloads (name pkg-dir)
536 (let* ((auto-name (concat name "-autoloads.el"))
537 (ignore-name (concat name "-pkg.el"))
538 (generated-autoload-file (expand-file-name auto-name pkg-dir))
539 (version-control 'never))
540 (require 'autoload)
541 (unless (fboundp 'autoload-ensure-default-file)
542 (package-autoload-ensure-default-file generated-autoload-file))
543 (update-directory-autoloads pkg-dir)))
544
545(defun package-untar-buffer ()
546 "Untar the current buffer.
547This uses `tar-untar-buffer' if it is available.
548Otherwise it uses an external `tar' program.
549`default-directory' should be set by the caller."
550 (require 'tar-mode)
551 (if (fboundp 'tar-untar-buffer)
552 (progn
553 ;; tar-mode messes with narrowing, so we just let it have the
554 ;; whole buffer to play with.
555 (delete-region (point-min) (point))
556 (tar-mode)
557 (tar-untar-buffer))
558 ;; FIXME: check the result.
559 (call-process-region (point) (point-max) "tar" nil '(nil nil) nil
560 "xf" "-")))
561
562(defun package-unpack (name version)
563 (let ((pkg-dir (expand-file-name (concat (symbol-name name) "-" version)
564 package-user-dir)))
565 ;; Be careful!!
566 (make-directory package-user-dir t)
567 (if (file-directory-p pkg-dir)
568 (mapc (lambda (file) nil) ; 'delete-file -- FIXME: when we're
569 ; more confident
570 (directory-files pkg-dir t "^[^.]")))
571 (let* ((default-directory (file-name-as-directory package-user-dir)))
572 (package-untar-buffer)
573 (package-generate-autoloads (symbol-name name) pkg-dir)
574 (let ((load-path (cons pkg-dir load-path)))
575 (byte-recompile-directory pkg-dir 0 t)))))
576
bc44bef7
PH
577(defun package--write-file-no-coding (file-name excl)
578 (let ((buffer-file-coding-system 'no-conversion))
579 (write-region (point-min) (point-max) file-name nil nil nil excl)))
580
44198b6e
CY
581(defun package-unpack-single (file-name version desc requires)
582 "Install the contents of the current buffer as a package."
583 ;; Special case "package".
584 (if (string= file-name "package")
bc44bef7
PH
585 (package--write-file-no-coding
586 (expand-file-name (concat file-name ".el") package-user-dir)
587 nil)
44198b6e
CY
588 (let* ((pkg-dir (expand-file-name (concat file-name "-" version)
589 package-user-dir))
590 (el-file (expand-file-name (concat file-name ".el") pkg-dir))
591 (pkg-file (expand-file-name (concat file-name "-pkg.el") pkg-dir)))
592 (make-directory pkg-dir t)
bc44bef7 593 (package--write-file-no-coding el-file 'excl)
44198b6e
CY
594 (let ((print-level nil)
595 (print-length nil))
596 (write-region
597 (concat
598 (prin1-to-string
599 (list 'define-package
600 file-name
601 version
602 desc
603 (list 'quote
604 ;; Turn version lists into string form.
605 (mapcar
606 (lambda (elt)
607 (list (car elt)
608 (package-version-join (car (cdr elt)))))
609 requires))))
610 "\n")
611 nil
612 pkg-file
613 nil nil nil 'excl))
614 (package-generate-autoloads file-name pkg-dir)
615 (let ((load-path (cons pkg-dir load-path)))
616 (byte-recompile-directory pkg-dir 0 t)))))
617
618(defun package-handle-response ()
619 "Handle the response from the server.
620Parse the HTTP response and throw if an error occurred.
621The url package seems to require extra processing for this.
622This should be called in a `save-excursion', in the download buffer.
623It will move point to somewhere in the headers."
624 ;; We assume HTTP here.
625 (require 'url-http)
626 (let ((response (url-http-parse-response)))
627 (when (or (< response 200) (>= response 300))
628 (display-buffer (current-buffer))
629 (error "Error during download request:%s"
630 (buffer-substring-no-properties (point) (progn
631 (end-of-line)
632 (point)))))))
633
634(defun package-download-single (name version desc requires)
635 "Download and install a single-file package."
636 (let ((buffer (url-retrieve-synchronously
063e5294 637 (concat (package-archive-url name)
44198b6e
CY
638 (symbol-name name) "-" version ".el"))))
639 (with-current-buffer buffer
640 (package-handle-response)
641 (re-search-forward "^$" nil 'move)
642 (forward-char)
643 (delete-region (point-min) (point))
644 (package-unpack-single (symbol-name name) version desc requires)
645 (kill-buffer buffer))))
646
647(defun package-download-tar (name version)
648 "Download and install a tar package."
649 (let ((tar-buffer (url-retrieve-synchronously
063e5294 650 (concat (package-archive-url name)
44198b6e
CY
651 (symbol-name name) "-" version ".tar"))))
652 (with-current-buffer tar-buffer
653 (package-handle-response)
654 (re-search-forward "^$" nil 'move)
655 (forward-char)
656 (package-unpack name version)
657 (kill-buffer tar-buffer))))
658
bc44bef7 659(defun package-installed-p (package &optional min-version)
44198b6e
CY
660 (let ((pkg-desc (assq package package-alist)))
661 (and pkg-desc
148cef8e
CY
662 (version-list-<= min-version
663 (package-desc-vers (cdr pkg-desc))))))
44198b6e 664
96ae4c8f
CY
665(defun package-compute-transaction (package-list requirements)
666 "Return a list of packages to be installed, including PACKAGE-LIST.
667PACKAGE-LIST should be a list of package names (symbols).
668
669REQUIREMENTS should be a list of additional requirements; each
670element in this list should have the form (PACKAGE VERSION),
671where PACKAGE is a package name and VERSION is the required
672version of that package (as a list).
673
674This function recursively computes the requirements of the
675packages in REQUIREMENTS, and returns a list of all the packages
676that must be installed. Packages that are already installed are
677not included in this list."
44198b6e
CY
678 (dolist (elt requirements)
679 (let* ((next-pkg (car elt))
680 (next-version (cadr elt)))
681 (unless (package-installed-p next-pkg next-version)
682 ;; A package is required, but not installed. It might also be
683 ;; blocked via `package-load-list'.
684 (let ((pkg-desc (assq next-pkg package-archive-contents))
685 hold)
686 (when (setq hold (assq next-pkg package-load-list))
687 (setq hold (cadr hold))
688 (cond ((eq hold nil)
689 (error "Required package '%s' is disabled"
690 (symbol-name next-pkg)))
691 ((null (stringp hold))
692 (error "Invalid element in `package-load-list'"))
148cef8e 693 ((version-list-< (version-to-list hold) next-version)
44198b6e
CY
694 (error "Package '%s' held at version %s, \
695but version %s required"
696 (symbol-name next-pkg) hold
697 (package-version-join next-version)))))
698 (unless pkg-desc
699 (error "Package '%s' is not available for installation"
700 (symbol-name next-pkg)))
148cef8e
CY
701 (unless (version-list-<= next-version
702 (package-desc-vers (cdr pkg-desc)))
44198b6e
CY
703 (error
704 "Need package '%s' with version %s, but only %s is available"
705 (symbol-name next-pkg) (package-version-join next-version)
706 (package-version-join (package-desc-vers (cdr pkg-desc)))))
707 ;; Only add to the transaction if we don't already have it.
96ae4c8f 708 (unless (memq next-pkg package-list)
ebf662f4 709 (push next-pkg package-list))
96ae4c8f
CY
710 (setq package-list
711 (package-compute-transaction package-list
44198b6e
CY
712 (package-desc-reqs
713 (cdr pkg-desc))))))))
96ae4c8f 714 package-list)
44198b6e
CY
715
716(defun package-read-from-string (str)
717 "Read a Lisp expression from STR.
718Signal an error if the entire string was not used."
719 (let* ((read-data (read-from-string str))
187d3296
CY
720 (more-left
721 (condition-case nil
722 ;; The call to `ignore' suppresses a compiler warning.
723 (progn (ignore (read-from-string
724 (substring str (cdr read-data))))
725 t)
726 (end-of-file nil))))
44198b6e
CY
727 (if more-left
728 (error "Can't read whole string")
729 (car read-data))))
730
731(defun package--read-archive-file (file)
732 "Re-read archive file FILE, if it exists.
733Will return the data from the file, or nil if the file does not exist.
734Will throw an error if the archive version is too new."
735 (let ((filename (expand-file-name file package-user-dir)))
187d3296
CY
736 (when (file-exists-p filename)
737 (with-temp-buffer
738 (insert-file-contents-literally filename)
739 (let ((contents (read (current-buffer))))
740 (if (> (car contents) package-archive-version)
741 (error "Package archive version %d is higher than %d"
742 (car contents) package-archive-version))
743 (cdr contents))))))
44198b6e 744
bc44bef7 745(defun package-read-all-archive-contents ()
96ae4c8f
CY
746 "Re-read `archive-contents', if it exists.
747If successful, set `package-archive-contents'."
bc44bef7 748 (dolist (archive package-archives)
96ae4c8f 749 (package-read-archive-contents (car archive))))
44198b6e 750
bc44bef7 751(defun package-read-archive-contents (archive)
187d3296
CY
752 "Re-read archive contents for ARCHIVE.
753If successful, set the variable `package-archive-contents'.
bc44bef7 754If the archive version is too new, signal an error."
187d3296
CY
755 ;; Version 1 of 'archive-contents' is identical to our internal
756 ;; representation.
757 (let* ((dir (concat "archives/" archive))
758 (contents-file (concat dir "/archive-contents"))
759 contents)
760 (when (setq contents (package--read-archive-file contents-file))
761 (dolist (package contents)
762 (package--add-to-archive-contents package archive)))))
bc44bef7
PH
763
764(defun package--add-to-archive-contents (package archive)
765 "Add the PACKAGE from the given ARCHIVE if necessary.
766Also, add the originating archive to the end of the package vector."
767 (let* ((name (car package))
768 (version (aref (cdr package) 0))
769 (entry (cons (car package)
770 (vconcat (cdr package) (vector archive))))
771 (existing-package (cdr (assq name package-archive-contents))))
772 (when (or (not existing-package)
148cef8e 773 (version-list-< (aref existing-package 0) version))
bc44bef7
PH
774 (add-to-list 'package-archive-contents entry))))
775
96ae4c8f
CY
776(defun package-download-transaction (package-list)
777 "Download and install all the packages in PACKAGE-LIST.
778PACKAGE-LIST should be a list of package names (symbols).
779This function assumes that all package requirements in
780PACKAGE-LIST are satisfied, i.e. that PACKAGE-LIST is computed
781using `package-compute-transaction'."
782 (dolist (elt package-list)
44198b6e
CY
783 (let* ((desc (cdr (assq elt package-archive-contents)))
784 ;; As an exception, if package is "held" in
785 ;; `package-load-list', download the held version.
786 (hold (cadr (assq elt package-load-list)))
787 (v-string (or (and (stringp hold) hold)
788 (package-version-join (package-desc-vers desc))))
789 (kind (package-desc-kind desc)))
790 (cond
791 ((eq kind 'tar)
792 (package-download-tar elt v-string))
793 ((eq kind 'single)
794 (package-download-single elt v-string
795 (package-desc-doc desc)
796 (package-desc-reqs desc)))
797 (t
798 (error "Unknown package kind: %s" (symbol-name kind)))))))
799
800;;;###autoload
801(defun package-install (name)
802 "Install the package named NAME.
803Interactively, prompt for the package name.
063e5294 804The package is found on one of the archives in `package-archives'."
44198b6e 805 (interactive
bc44bef7
PH
806 (list (intern (completing-read "Install package: "
807 (mapcar (lambda (elt)
808 (cons (symbol-name (car elt))
809 nil))
810 package-archive-contents)
811 nil t))))
44198b6e
CY
812 (let ((pkg-desc (assq name package-archive-contents)))
813 (unless pkg-desc
bc44bef7 814 (error "Package '%s' is not available for installation"
44198b6e 815 (symbol-name name)))
bc44bef7
PH
816 (package-download-transaction
817 (package-compute-transaction (list name)
818 (package-desc-reqs (cdr pkg-desc)))))
44198b6e
CY
819 ;; Try to activate it.
820 (package-initialize))
821
822(defun package-strip-rcs-id (v-str)
823 "Strip RCS version ID from the version string.
824If the result looks like a dotted numeric version, return it.
825Otherwise return nil."
826 (if v-str
827 (if (string-match "^[ \t]*[$]Revision:[ \t]\([0-9.]+\)[ \t]*[$]$" v-str)
828 (match-string 1 v-str)
829 (if (string-match "^[0-9.]*$" v-str)
830 v-str))))
831
832(defun package-buffer-info ()
187d3296
CY
833 "Return a vector describing the package in the current buffer.
834The vector has the form
835
836 [FILENAME REQUIRES DESCRIPTION VERSION COMMENTARY]
837
838FILENAME is the file name, a string, sans the \".el\" extension.
44198b6e 839REQUIRES is a requires list, or nil.
187d3296 840DESCRIPTION is the package description, a string.
44198b6e
CY
841VERSION is the version, a string.
842COMMENTARY is the commentary section, a string, or nil if none.
187d3296
CY
843
844If the buffer does not contain a conforming package, signal an
845error. If there is a package, narrow the buffer to the file's
846boundaries."
44198b6e 847 (goto-char (point-min))
187d3296
CY
848 (unless (re-search-forward "^;;; \\([^ ]*\\)\\.el --- \\(.*\\)$" nil t)
849 (error "Packages lacks a file header"))
850 (let ((file-name (match-string-no-properties 1))
851 (desc (match-string-no-properties 2))
852 (start (line-beginning-position)))
853 (unless (search-forward (concat ";;; " file-name ".el ends here"))
854 (error "Package lacks a terminating comment"))
855 ;; Try to include a trailing newline.
856 (forward-line)
857 (narrow-to-region start (point))
858 (require 'lisp-mnt)
859 ;; Use some headers we've invented to drive the process.
860 (let* ((requires-str (lm-header "package-requires"))
861 (requires (if requires-str
862 (package-read-from-string requires-str)))
863 ;; Prefer Package-Version; if defined, the package author
864 ;; probably wants us to use it. Otherwise try Version.
865 (pkg-version
866 (or (package-strip-rcs-id (lm-header "package-version"))
867 (package-strip-rcs-id (lm-header "version"))))
868 (commentary (lm-commentary)))
869 (unless pkg-version
870 (error
871 "Package lacks a \"Version\" or \"Package-Version\" header"))
872 ;; Turn string version numbers into list form.
873 (setq requires
874 (mapcar
875 (lambda (elt)
876 (list (car elt)
877 (version-to-list (car (cdr elt)))))
878 requires))
879 (vector file-name requires desc pkg-version commentary))))
44198b6e
CY
880
881(defun package-tar-file-info (file)
882 "Find package information for a tar file.
883FILE is the name of the tar file to examine.
884The return result is a vector like `package-buffer-info'."
885 (unless (string-match "^\\(.+\\)-\\([0-9.]+\\)\\.tar$" file)
187d3296 886 (error "Invalid package name `%s'" file))
44198b6e
CY
887 (let* ((pkg-name (file-name-nondirectory (match-string-no-properties 1 file)))
888 (pkg-version (match-string-no-properties 2 file))
889 ;; Extract the package descriptor.
890 (pkg-def-contents (shell-command-to-string
891 ;; Requires GNU tar.
892 (concat "tar -xOf " file " "
893 pkg-name "-" pkg-version "/"
894 pkg-name "-pkg.el")))
895 (pkg-def-parsed (package-read-from-string pkg-def-contents)))
896 (unless (eq (car pkg-def-parsed) 'define-package)
187d3296
CY
897 (error "No `define-package' sexp is present in `%s-pkg.el'" pkg-name))
898 (let ((name-str (nth 1 pkg-def-parsed))
44198b6e 899 (version-string (nth 2 pkg-def-parsed))
187d3296
CY
900 (docstring (nth 3 pkg-def-parsed))
901 (requires (nth 4 pkg-def-parsed))
44198b6e
CY
902 (readme (shell-command-to-string
903 ;; Requires GNU tar.
904 (concat "tar -xOf " file " "
905 pkg-name "-" pkg-version "/README"))))
906 (unless (equal pkg-version version-string)
187d3296 907 (error "Package has inconsistent versions"))
44198b6e 908 (unless (equal pkg-name name-str)
187d3296 909 (error "Package has inconsistent names"))
44198b6e
CY
910 ;; Kind of a hack.
911 (if (string-match ": Not found in archive" readme)
912 (setq readme nil))
913 ;; Turn string version numbers into list form.
914 (if (eq (car requires) 'quote)
915 (setq requires (car (cdr requires))))
916 (setq requires
187d3296
CY
917 (mapcar (lambda (elt)
918 (list (car elt)
919 (version-to-list (cadr elt))))
920 requires))
44198b6e
CY
921 (vector pkg-name requires docstring version-string readme))))
922
187d3296
CY
923;;;###autoload
924(defun package-install-from-buffer (pkg-info type)
925 "Install a package from the current buffer.
926When called interactively, the current buffer is assumed to be a
927single .el file that follows the packaging guidelines; see info
928node `(elisp)Packaging'.
929
930When called from Lisp, PKG-INFO is a vector describing the
931information, of the type returned by `package-buffer-info'; and
932TYPE is the package type (either `single' or `tar')."
933 (interactive (list (package-buffer-info) 'single))
44198b6e
CY
934 (save-excursion
935 (save-restriction
936 (let* ((file-name (aref pkg-info 0))
187d3296 937 (requires (aref pkg-info 1))
44198b6e
CY
938 (desc (if (string= (aref pkg-info 2) "")
939 "No description available."
940 (aref pkg-info 2)))
941 (pkg-version (aref pkg-info 3)))
942 ;; Download and install the dependencies.
943 (let ((transaction (package-compute-transaction nil requires)))
944 (package-download-transaction transaction))
945 ;; Install the package itself.
946 (cond
947 ((eq type 'single)
948 (package-unpack-single file-name pkg-version desc requires))
949 ((eq type 'tar)
950 (package-unpack (intern file-name) pkg-version))
951 (t
952 (error "Unknown type: %s" (symbol-name type))))
953 ;; Try to activate it.
954 (package-initialize)))))
955
44198b6e
CY
956;;;###autoload
957(defun package-install-file (file)
958 "Install a package from a file.
959The file can either be a tar file or an Emacs Lisp file."
960 (interactive "fPackage file name: ")
961 (with-temp-buffer
962 (insert-file-contents-literally file)
963 (cond
187d3296
CY
964 ((string-match "\\.el$" file)
965 (package-install-from-buffer (package-buffer-info) 'single))
44198b6e 966 ((string-match "\\.tar$" file)
187d3296 967 (package-install-from-buffer (package-tar-file-info file) 'tar))
44198b6e
CY
968 (t (error "Unrecognized extension `%s'" (file-name-extension file))))))
969
970(defun package-delete (name version)
971 (require 'dired) ; for dired-delete-file
972 (dired-delete-file (expand-file-name (concat name "-" version)
973 package-user-dir)
974 ;; FIXME: query user?
975 'always))
976
063e5294 977(defun package-archive-url (name)
bc44bef7
PH
978 "Return the archive containing the package NAME."
979 (let ((desc (cdr (assq (intern-soft name) package-archive-contents))))
980 (cdr (assoc (aref desc (- (length desc) 1)) package-archives))))
981
982(defun package--download-one-archive (archive file)
983 "Download an archive file FILE from ARCHIVE, and cache it locally."
984 (let* ((archive-name (car archive))
985 (archive-url (cdr archive))
986 (dir (expand-file-name "archives" package-user-dir))
987 (dir (expand-file-name archive-name dir))
988 (buffer (url-retrieve-synchronously (concat archive-url file))))
44198b6e
CY
989 (with-current-buffer buffer
990 (package-handle-response)
991 (re-search-forward "^$" nil 'move)
992 (forward-char)
993 (delete-region (point-min) (point))
ebf662f4
CY
994 ;; Read the retrieved buffer to make sure it is valid (e.g. it
995 ;; may fetch a URL redirect page).
996 (when (listp (read buffer))
997 (make-directory dir t)
998 (setq buffer-file-name (expand-file-name file dir))
999 (let ((version-control 'never))
1000 (save-buffer))))
bc44bef7 1001 (kill-buffer buffer)))
44198b6e
CY
1002
1003(defun package-refresh-contents ()
1004 "Download the ELPA archive description if needed.
ebf662f4
CY
1005This informs Emacs about the latest versions of all packages, and
1006makes them available for download."
44198b6e
CY
1007 (interactive)
1008 (unless (file-exists-p package-user-dir)
1009 (make-directory package-user-dir t))
bc44bef7 1010 (dolist (archive package-archives)
cb6c4991
CY
1011 (condition-case nil
1012 (package--download-one-archive archive "archive-contents")
187d3296 1013 (error (message "Failed to download `%s' archive."
cb6c4991 1014 (car archive)))))
bc44bef7 1015 (package-read-all-archive-contents))
44198b6e
CY
1016
1017;;;###autoload
1018(defun package-initialize ()
1019 "Load Emacs Lisp packages, and activate them.
1020The variable `package-load-list' controls which packages to load."
1021 (interactive)
96ae4c8f 1022 (require 'finder-inf nil t)
0f75c62a
CY
1023 (setq package-alist package--builtins
1024 package-activated-list (mapcar #'car package-alist)
1025 package-obsolete-alist nil)
44198b6e 1026 (package-load-all-descriptors)
bc44bef7 1027 (package-read-all-archive-contents)
0f75c62a
CY
1028 ;; "Deactivate" obsoleted built-in packages
1029 (dolist (elt package-obsolete-alist)
be577d03
CY
1030 (setq package-activated-list
1031 (delq (car elt) package-activated-list)))
44198b6e 1032 ;; Try to activate all our packages.
0f75c62a
CY
1033 (dolist (elt package-alist)
1034 (package-activate (car elt) (package-desc-vers (cdr elt)))))
44198b6e
CY
1035
1036\f
cced7584 1037;;;; Package description buffer.
44198b6e 1038
cced7584
CY
1039;;;###autoload
1040(defun describe-package (package)
1041 "Display the full documentation of PACKAGE (a symbol)."
1042 (interactive
8a500a91
CY
1043 (let* ((guess (function-called-at-point))
1044 packages val)
1045 ;; Initialize the package system if it's not.
1046 (unless package-alist
1047 (package-initialize))
1048 (setq packages (append (mapcar 'car package-alist)
cced7584 1049 (mapcar 'car package-archive-contents)))
cced7584
CY
1050 (unless (memq guess packages)
1051 (setq guess nil))
1052 (setq packages (mapcar 'symbol-name packages))
1053 (setq val
1054 (completing-read (if guess
1055 (format "Describe package (default %s): "
1056 guess)
1057 "Describe package: ")
1058 packages nil t nil nil guess))
cb6c4991 1059 (list (if (equal val "") guess (intern val)))))
cced7584
CY
1060 (if (or (null package) (null (symbolp package)))
1061 (message "You did not specify a package")
1062 (help-setup-xref (list #'describe-package package)
1063 (called-interactively-p 'interactive))
1064 (with-help-window (help-buffer)
1065 (with-current-buffer standard-output
1066 (describe-package-1 package)))))
1067
1068(defun describe-package-1 (package)
96ae4c8f 1069 (require 'lisp-mnt)
cb6c4991
CY
1070 (let ((package-name (symbol-name package))
1071 (built-in (assq package package--builtins))
1072 desc pkg-dir reqs version installable)
cced7584
CY
1073 (prin1 package)
1074 (princ " is ")
cb6c4991
CY
1075 (if (setq desc (cdr (assq package package-alist)))
1076 ;; This package is loaded (i.e. in `package-alist').
1077 (progn
1078 (setq version (package-version-join (package-desc-vers desc)))
0f75c62a 1079 (cond ((setq pkg-dir (package--dir package-name version))
cb6c4991 1080 (insert "an installed package.\n\n"))
0f75c62a
CY
1081 (built-in
1082 (princ "a built-in package.\n\n"))
cb6c4991
CY
1083 (t ;; This normally does not happen.
1084 (insert "a deleted package.\n\n")
1085 (setq version nil))))
1086 ;; This package is not installed.
1087 (setq desc (cdr (assq package package-archive-contents))
8adb4c33
CY
1088 version (package-version-join (package-desc-vers desc))
1089 installable t)
cb6c4991
CY
1090 (insert "an uninstalled package.\n\n"))
1091
96ae4c8f 1092 (insert " " (propertize "Status" 'font-lock-face 'bold) ": ")
cb6c4991 1093 (cond (pkg-dir
96ae4c8f
CY
1094 (insert (propertize "Installed"
1095 'font-lock-face 'font-lock-comment-face))
cb6c4991
CY
1096 (insert " in `")
1097 ;; Todo: Add button for uninstalling.
1098 (help-insert-xref-button (file-name-as-directory pkg-dir)
1099 'help-package-def pkg-dir)
1100 (insert "'."))
1101 (installable
1102 (insert "Available -- ")
1103 (let ((button-text (if (display-graphic-p)
1104 "Install"
1105 "[Install]"))
1106 (button-face (if (display-graphic-p)
1107 '(:box (:line-width 2 :color "dark grey")
1108 :background "light grey"
1109 :foreground "black")
1110 'link)))
1111 (insert-text-button button-text
1112 'face button-face
1113 'follow-link t
1114 'package-symbol package
1115 'action 'package-install-button-action)))
1116 (built-in
96ae4c8f
CY
1117 (insert (propertize "Built-in"
1118 'font-lock-face 'font-lock-builtin-face) "."))
cb6c4991
CY
1119 (t (insert "Deleted.")))
1120 (insert "\n")
96ae4c8f
CY
1121 (and version
1122 (> (length version) 0)
1123 (insert " "
1124 (propertize "Version" 'font-lock-face 'bold) ": " version "\n"))
8adb4c33
CY
1125 (setq reqs (package-desc-reqs desc))
1126 (when reqs
96ae4c8f 1127 (insert " " (propertize "Requires" 'font-lock-face 'bold) ": ")
8adb4c33
CY
1128 (let ((first t)
1129 name vers text)
1130 (dolist (req reqs)
1131 (setq name (car req)
1132 vers (cadr req)
1133 text (format "%s-%s" (symbol-name name)
1134 (package-version-join vers)))
1135 (cond (first (setq first nil))
1136 ((>= (+ 2 (current-column) (length text))
1137 (window-width))
1138 (insert ",\n "))
1139 (t (insert ", ")))
1140 (help-insert-xref-button text 'help-package name))
1141 (insert "\n")))
96ae4c8f 1142 (insert " " (propertize "Summary" 'font-lock-face 'bold)
cb6c4991
CY
1143 ": " (package-desc-doc desc) "\n\n")
1144
96ae4c8f
CY
1145 (if (assq package package--builtins)
1146 ;; For built-in packages, insert the commentary.
1147 (let ((fn (locate-file (concat package-name ".el") load-path
1148 load-file-rep-suffixes))
1149 (opoint (point)))
1150 (insert (or (lm-commentary fn) ""))
1151 (save-excursion
1152 (goto-char opoint)
1153 (when (re-search-forward "^;;; Commentary:\n" nil t)
1154 (replace-match ""))
1155 (while (re-search-forward "^\\(;+ ?\\)" nil t)
1156 (replace-match ""))))
1157 (let ((readme (expand-file-name (concat package-name "-readme.txt")
1158 package-user-dir)))
1159 ;; For elpa packages, try downloading the commentary. If that
1160 ;; fails, try an existing readme file in `package-user-dir'.
1161 (cond ((let ((buffer (ignore-errors
1162 (url-retrieve-synchronously
1163 (concat (package-archive-url package)
1164 package-name "-readme.txt"))))
1165 response)
1166 (when buffer
1167 (with-current-buffer buffer
1168 (setq response (url-http-parse-response))
1169 (if (or (< response 200) (>= response 300))
1170 (setq response nil)
1171 (setq buffer-file-name
1172 (expand-file-name readme package-user-dir))
1173 (delete-region (point-min) (1+ url-http-end-of-headers))
1174 (save-buffer)))
1175 (when response
1176 (insert-buffer-substring buffer)
1177 (kill-buffer buffer)
1178 t))))
1179 ((file-readable-p readme)
1180 (insert-file-contents readme)
1181 (goto-char (point-max))))))))
cb6c4991
CY
1182
1183(defun package-install-button-action (button)
1184 (let ((package (button-get button 'package-symbol)))
1185 (when (y-or-n-p (format "Install package `%s'? " package))
1186 (package-install package)
1187 (revert-buffer nil t)
1188 (goto-char (point-min)))))
cced7584
CY
1189
1190\f
44198b6e
CY
1191;;;; Package menu mode.
1192
54ea2a0d 1193(defvar package-menu-mode-map
64eba874
DN
1194 (let ((map (make-keymap))
1195 (menu-map (make-sparse-keymap "Package")))
43207249 1196 (set-keymap-parent map button-buffer-map)
8adb4c33 1197 (define-key map "\C-m" 'package-menu-describe-package)
54ea2a0d
JB
1198 (define-key map "q" 'quit-window)
1199 (define-key map "n" 'next-line)
1200 (define-key map "p" 'previous-line)
1201 (define-key map "u" 'package-menu-mark-unmark)
1202 (define-key map "\177" 'package-menu-backup-unmark)
1203 (define-key map "d" 'package-menu-mark-delete)
1204 (define-key map "i" 'package-menu-mark-install)
e687c2cd 1205 (define-key map "g" 'revert-buffer)
54ea2a0d
JB
1206 (define-key map "r" 'package-menu-refresh)
1207 (define-key map "~" 'package-menu-mark-obsolete-for-deletion)
1208 (define-key map "x" 'package-menu-execute)
1209 (define-key map "h" 'package-menu-quick-help)
cb6c4991 1210 (define-key map "?" 'package-menu-describe-package)
96ae4c8f
CY
1211 (define-key map [follow-link] 'mouse-face)
1212 (define-key map [mouse-2] 'mouse-select-window)
64eba874
DN
1213 (define-key map [menu-bar package-menu] (cons "Package" menu-map))
1214 (define-key menu-map [mq]
1215 '(menu-item "Quit" quit-window
1216 :help "Quit package selection"))
1217 (define-key menu-map [s1] '("--"))
1218 (define-key menu-map [mn]
1219 '(menu-item "Next" next-line
1220 :help "Next Line"))
1221 (define-key menu-map [mp]
1222 '(menu-item "Previous" previous-line
1223 :help "Previous Line"))
1224 (define-key menu-map [s2] '("--"))
1225 (define-key menu-map [mu]
1226 '(menu-item "Unmark" package-menu-mark-unmark
1227 :help "Clear any marks on a package and move to the next line"))
1228 (define-key menu-map [munm]
1229 '(menu-item "Unmark backwards" package-menu-backup-unmark
1230 :help "Back up one line and clear any marks on that package"))
1231 (define-key menu-map [md]
1232 '(menu-item "Mark for deletion" package-menu-mark-delete
1233 :help "Mark a package for deletion and move to the next line"))
1234 (define-key menu-map [mi]
1235 '(menu-item "Mark for install" package-menu-mark-install
1236 :help "Mark a package for installation and move to the next line"))
1237 (define-key menu-map [s3] '("--"))
1238 (define-key menu-map [mg]
e687c2cd 1239 '(menu-item "Update package list" revert-buffer
64eba874
DN
1240 :help "Update the list of packages"))
1241 (define-key menu-map [mr]
1242 '(menu-item "Refresh package list" package-menu-refresh
1243 :help "Download the ELPA archive"))
1244 (define-key menu-map [s4] '("--"))
1245 (define-key menu-map [mt]
1246 '(menu-item "Mark obsolete packages" package-menu-mark-obsolete-for-deletion
1247 :help "Mark all obsolete packages for deletion"))
1248 (define-key menu-map [mx]
1249 '(menu-item "Execute actions" package-menu-execute
1250 :help "Perform all the marked actions"))
1251 (define-key menu-map [s5] '("--"))
1252 (define-key menu-map [mh]
1253 '(menu-item "Help" package-menu-quick-help
1254 :help "Show short key binding help for package-menu-mode"))
1255 (define-key menu-map [mc]
1256 '(menu-item "View Commentary" package-menu-view-commentary
1257 :help "Display information about this package"))
54ea2a0d 1258 map)
44198b6e
CY
1259 "Local keymap for `package-menu-mode' buffers.")
1260
44198b6e
CY
1261(defvar package-menu-sort-button-map
1262 (let ((map (make-sparse-keymap)))
1263 (define-key map [header-line mouse-1] 'package-menu-sort-by-column)
96ae4c8f 1264 (define-key map [header-line mouse-2] 'package-menu-sort-by-column)
44198b6e
CY
1265 (define-key map [follow-link] 'mouse-face)
1266 map)
1267 "Local keymap for package menu sort buttons.")
1268
1269(put 'package-menu-mode 'mode-class 'special)
1270
1271(defun package-menu-mode ()
1272 "Major mode for browsing a list of packages.
1273Letters do not insert themselves; instead, they are commands.
1274\\<package-menu-mode-map>
1275\\{package-menu-mode-map}"
1276 (kill-all-local-variables)
1277 (use-local-map package-menu-mode-map)
1278 (setq major-mode 'package-menu-mode)
1279 (setq mode-name "Package Menu")
1280 (setq truncate-lines t)
1281 (setq buffer-read-only t)
cd205c76 1282 (set (make-local-variable 'revert-buffer-function) 'package-menu-revert)
187d3296
CY
1283 (setq header-line-format
1284 (mapconcat
1285 (lambda (pair)
1286 (let ((column (car pair))
1287 (name (cdr pair)))
1288 (concat
1289 ;; Insert a space that aligns the button properly.
1290 (propertize " " 'display (list 'space :align-to column)
1291 'face 'fixed-pitch)
1292 ;; Set up the column button.
1293 (propertize name
1294 'column-name name
1295 'help-echo "mouse-1: sort by column"
1296 'mouse-face 'highlight
1297 'keymap package-menu-sort-button-map))))
1298 ;; We take a trick from buff-menu and have a dummy leading
1299 ;; space to align the header line with the beginning of the
1300 ;; text. This doesn't really work properly on Emacs 21, but
1301 ;; it is close enough.
1302 '((0 . "")
1303 (2 . "Package")
1304 (20 . "Version")
1305 (32 . "Status")
1306 (43 . "Description"))
1307 ""))
1308 (run-mode-hooks 'package-menu-mode-hook))
44198b6e
CY
1309
1310(defun package-menu-refresh ()
ebf662f4
CY
1311 "Download the Emacs Lisp package archive.
1312This fetches the contents of each archive specified in
1313`package-archives', and then refreshes the package menu."
44198b6e 1314 (interactive)
187d3296
CY
1315 (unless (eq major-mode 'package-menu-mode)
1316 (error "The current buffer is not a Package Menu"))
44198b6e 1317 (package-refresh-contents)
96ae4c8f 1318 (package--generate-package-list))
44198b6e 1319
e687c2cd
CY
1320(defun package-menu-revert (&optional arg noconfirm)
1321 "Update the list of packages.
1322This function is the `revert-buffer-function' for Package Menu
1323buffers. The arguments are ignored."
44198b6e 1324 (interactive)
187d3296
CY
1325 (unless (eq major-mode 'package-menu-mode)
1326 (error "The current buffer is not a Package Menu"))
96ae4c8f 1327 (package--generate-package-list))
44198b6e 1328
8adb4c33
CY
1329(defun package-menu-describe-package ()
1330 "Describe the package in the current line."
1331 (interactive)
1332 (let ((name (package-menu-get-package)))
1333 (if name
1334 (describe-package (intern name))
1335 (message "No package on this line"))))
1336
44198b6e
CY
1337(defun package-menu-mark-internal (what)
1338 (unless (eobp)
1339 (let ((buffer-read-only nil))
1340 (beginning-of-line)
1341 (delete-char 1)
1342 (insert what)
1343 (forward-line))))
1344
1345;; fixme numeric argument
1346(defun package-menu-mark-delete (num)
1347 "Mark a package for deletion and move to the next line."
1348 (interactive "p")
1349 (package-menu-mark-internal "D"))
1350
1351(defun package-menu-mark-install (num)
1352 "Mark a package for installation and move to the next line."
1353 (interactive "p")
1354 (package-menu-mark-internal "I"))
1355
1356(defun package-menu-mark-unmark (num)
1357 "Clear any marks on a package and move to the next line."
1358 (interactive "p")
1359 (package-menu-mark-internal " "))
1360
1361(defun package-menu-backup-unmark ()
1362 "Back up one line and clear any marks on that package."
1363 (interactive)
1364 (forward-line -1)
1365 (package-menu-mark-internal " ")
1366 (forward-line -1))
1367
1368(defun package-menu-mark-obsolete-for-deletion ()
1369 "Mark all obsolete packages for deletion."
1370 (interactive)
1371 (save-excursion
1372 (goto-char (point-min))
1373 (forward-line 2)
1374 (while (not (eobp))
1375 (if (looking-at ".*\\s obsolete\\s ")
1376 (package-menu-mark-internal "D")
1377 (forward-line 1)))))
1378
1379(defun package-menu-quick-help ()
1380 "Show short key binding help for package-menu-mode."
1381 (interactive)
1382 (message "n-ext, i-nstall, d-elete, u-nmark, x-ecute, r-efresh, h-elp"))
1383
cb6c4991
CY
1384(define-obsolete-function-alias
1385 'package-menu-view-commentary 'package-menu-describe-package "24.1")
44198b6e
CY
1386
1387;; Return the name of the package on the current line.
1388(defun package-menu-get-package ()
1389 (save-excursion
1390 (beginning-of-line)
1391 (if (looking-at ". \\([^ \t]*\\)")
8adb4c33 1392 (match-string-no-properties 1))))
44198b6e
CY
1393
1394;; Return the version of the package on the current line.
1395(defun package-menu-get-version ()
1396 (save-excursion
1397 (beginning-of-line)
1398 (if (looking-at ". [^ \t]*[ \t]*\\([0-9.]*\\)")
1399 (match-string 1))))
1400
1401(defun package-menu-get-status ()
1402 (save-excursion
1403 (if (looking-at ". [^ \t]*[ \t]*[^ \t]*[ \t]*\\([^ \t]*\\)")
1404 (match-string 1)
1405 "")))
1406
1407(defun package-menu-execute ()
1408 "Perform all the marked actions.
1409Packages marked for installation will be downloaded and
1410installed. Packages marked for deletion will be removed.
1411Note that after installing packages you will want to restart
1412Emacs."
1413 (interactive)
1414 (goto-char (point-min))
44198b6e
CY
1415 (while (not (eobp))
1416 (let ((cmd (char-after))
1417 (pkg-name (package-menu-get-package))
1418 (pkg-vers (package-menu-get-version))
1419 (pkg-status (package-menu-get-status)))
1420 (cond
1421 ((eq cmd ?D)
1422 (when (and (string= pkg-status "installed")
1423 (string= pkg-name "package"))
1424 ;; FIXME: actually, we could be tricky and remove all info.
1425 ;; But that is drastic and the user can do that instead.
1426 (error "Can't delete most recent version of `package'"))
1427 ;; Ask for confirmation here? Maybe if package status is ""?
1428 ;; Or if any lisp from package is actually loaded?
1429 (message "Deleting %s-%s..." pkg-name pkg-vers)
1430 (package-delete pkg-name pkg-vers)
1431 (message "Deleting %s-%s... done" pkg-name pkg-vers))
1432 ((eq cmd ?I)
1433 (package-install (intern pkg-name)))))
1434 (forward-line))
1435 (package-menu-revert))
1436
1437(defun package-print-package (package version key desc)
1438 (let ((face
376c2b6b 1439 (cond ((string= key "built-in") 'font-lock-builtin-face)
44198b6e
CY
1440 ((string= key "available") 'default)
1441 ((string= key "held") 'font-lock-constant-face)
1442 ((string= key "disabled") 'font-lock-warning-face)
1443 ((string= key "installed") 'font-lock-comment-face)
1444 (t ; obsolete, but also the default.
1445 'font-lock-warning-face))))
1446 (insert (propertize " " 'font-lock-face face))
8adb4c33
CY
1447 (insert-text-button (symbol-name package)
1448 'face 'link
1449 'follow-link t
1450 'package-symbol package
1451 'action (lambda (button)
1452 (describe-package
1453 (button-get button 'package-symbol))))
44198b6e
CY
1454 (indent-to 20 1)
1455 (insert (propertize (package-version-join version) 'font-lock-face face))
8adb4c33 1456 (indent-to 32 1)
44198b6e
CY
1457 (insert (propertize key 'font-lock-face face))
1458 ;; FIXME: this 'when' is bogus...
1459 (when desc
8adb4c33 1460 (indent-to 43 1)
376c2b6b
CY
1461 (let ((opoint (point)))
1462 (insert (propertize desc 'font-lock-face face))
1463 (upcase-region opoint (min (point) (1+ opoint)))))
44198b6e
CY
1464 (insert "\n")))
1465
1466(defun package-list-maybe-add (package version status description result)
1467 (unless (assoc (cons package version) result)
ebf662f4 1468 (push (list (cons package version) status description) result))
44198b6e
CY
1469 result)
1470
187d3296
CY
1471(defvar package-menu-package-list nil
1472 "List of packages to display in the Package Menu buffer.
1473A value of nil means to display all packages.")
44198b6e 1474
187d3296
CY
1475(defvar package-menu-sort-key nil
1476 "Sort key for the current Package Menu buffer.")
1477
1478(defun package--generate-package-list ()
1479 "Populate the current Package Menu buffer."
1480 (package-initialize)
1481 (let ((inhibit-read-only t)
1482 info-list name desc hold builtin)
44198b6e 1483 (erase-buffer)
187d3296
CY
1484 ;; List installed packages
1485 (dolist (elt package-alist)
1486 (setq name (car elt))
1487 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
1488 (or (null package-menu-package-list)
1489 (memq name package-menu-package-list)))
1490 (setq desc (cdr elt)
1491 hold (cadr (assq name package-load-list))
1492 builtin (cdr (assq name package--builtins)))
1493 (setq info-list
1494 (package-list-maybe-add
1495 name (package-desc-vers desc)
1496 ;; FIXME: it turns out to be tricky to see if this
1497 ;; package is presently activated.
1498 (cond ((stringp hold) "held")
1499 ((and builtin
1500 (version-list-=
1501 (package-desc-vers builtin)
1502 (package-desc-vers desc)))
1503 "built-in")
1504 (t "installed"))
1505 (package-desc-doc desc)
1506 info-list))))
1507
1508 ;; List available and disabled packages
1509 (dolist (elt package-archive-contents)
1510 (setq name (car elt)
1511 desc (cdr elt)
1512 hold (assq name package-load-list))
1513 (when (or (null package-menu-package-list)
1514 (memq name package-menu-package-list))
1515 (setq info-list
1516 (package-list-maybe-add name
1517 (package-desc-vers desc)
1518 (if (and hold (null (cadr hold)))
1519 "disabled"
1520 "available")
1521 (package-desc-doc (cdr elt))
1522 info-list))))
1523 ;; List obsolete packages
1524 (mapc (lambda (elt)
1525 (mapc (lambda (inner-elt)
1526 (setq info-list
1527 (package-list-maybe-add (car elt)
1528 (package-desc-vers
1529 (cdr inner-elt))
1530 "obsolete"
1531 (package-desc-doc
1532 (cdr inner-elt))
1533 info-list)))
1534 (cdr elt)))
1535 package-obsolete-alist)
1536
1537 (setq info-list
1538 (sort info-list
1539 (cond ((string= package-menu-sort-key "Package")
1540 'package-menu--name-predicate)
1541 ((string= package-menu-sort-key "Version")
1542 'package-menu--version-predicate)
1543 ((string= package-menu-sort-key "Description")
1544 'package-menu--description-predicate)
1545 (t ; By default, sort by package status
1546 'package-menu--status-predicate))))
1547
1548 (dolist (elt info-list)
1549 (package-print-package (car (car elt))
1550 (cdr (car elt))
1551 (car (cdr elt))
1552 (car (cdr (cdr elt)))))
44198b6e 1553 (goto-char (point-min))
96ae4c8f 1554 (set-buffer-modified-p nil)
44198b6e
CY
1555 (current-buffer)))
1556
96ae4c8f 1557(defun package-menu--version-predicate (left right)
187d3296
CY
1558 (let ((vleft (or (cdr (car left)) '(0)))
1559 (vright (or (cdr (car right)) '(0))))
1560 (if (version-list-= vleft vright)
96ae4c8f 1561 (package-menu--name-predicate left right)
187d3296 1562 (version-list-< vleft vright))))
96ae4c8f
CY
1563
1564(defun package-menu--status-predicate (left right)
1565 (let ((sleft (cadr left))
1566 (sright (cadr right)))
1567 (cond ((string= sleft sright)
1568 (package-menu--name-predicate left right))
1569 ((string= sleft "available") t)
1570 ((string= sright "available") nil)
1571 ((string= sleft "installed") t)
1572 ((string= sright "installed") nil)
1573 ((string= sleft "held") t)
1574 ((string= sright "held") nil)
1575 ((string= sleft "built-in") t)
1576 ((string= sright "built-in") nil)
1577 ((string= sleft "obsolete") t)
1578 ((string= sright "obsolete") nil)
1579 (t (string< sleft sright)))))
1580
1581(defun package-menu--description-predicate (left right)
1582 (let ((sleft (car (cddr left)))
1583 (sright (car (cddr right))))
1584 (if (string= sleft sright)
1585 (package-menu--name-predicate left right)
1586 (string< sleft sright))))
1587
1588(defun package-menu--name-predicate (left right)
1589 (string< (symbol-name (caar left))
1590 (symbol-name (caar right))))
1591
44198b6e 1592(defun package-menu-sort-by-column (&optional e)
187d3296 1593 "Sort the package menu by the column of the mouse click E."
96ae4c8f 1594 (interactive "e")
44198b6e 1595 (let* ((pos (event-start e))
187d3296
CY
1596 (obj (posn-object pos))
1597 (col (if obj
1598 (get-text-property (cdr obj) 'column-name (car obj))
1599 (get-text-property (posn-point pos) 'column-name)))
1600 (buf (window-buffer (posn-window (event-start e)))))
1601 (with-current-buffer buf
1602 (when (eq major-mode 'package-menu-mode)
1603 (setq package-menu-sort-key col)
1604 (package--generate-package-list)))))
96ae4c8f
CY
1605
1606(defun package--list-packages (&optional packages)
187d3296
CY
1607 "Generate and pop to the *Packages* buffer.
1608Optional PACKAGES is a list of names of packages (symbols) to
1609list; the default is to display everything in `package-alist'."
1610 (with-current-buffer (get-buffer-create "*Packages*")
44198b6e 1611 (package-menu-mode)
187d3296
CY
1612 (set (make-local-variable 'package-menu-package-list) packages)
1613 (set (make-local-variable 'package-menu-sort-key) nil)
1614 (package--generate-package-list)
44198b6e 1615 ;; It's okay to use pop-to-buffer here. The package menu buffer
96ae4c8f
CY
1616 ;; has keybindings, and the user just typed `M-x list-packages',
1617 ;; suggesting that they might want to use them.
44198b6e
CY
1618 (pop-to-buffer (current-buffer))))
1619
1620;;;###autoload
96ae4c8f 1621(defun list-packages ()
44198b6e
CY
1622 "Display a list of packages.
1623Fetches the updated list of packages before displaying.
1624The list is displayed in a buffer named `*Packages*'."
1625 (interactive)
8a500a91
CY
1626 ;; Initialize the package system if necessary.
1627 (unless package-alist
1628 (package-initialize))
44198b6e
CY
1629 (package-refresh-contents)
1630 (package--list-packages))
1631
cb8759ca 1632;;;###autoload
96ae4c8f 1633(defalias 'package-list-packages 'list-packages)
cb8759ca 1634
44198b6e
CY
1635(defun package-list-packages-no-fetch ()
1636 "Display a list of packages.
1637Does not fetch the updated list of packages before displaying.
1638The list is displayed in a buffer named `*Packages*'."
1639 (interactive)
1640 (package--list-packages))
1641
44198b6e
CY
1642(provide 'package)
1643
1644;;; package.el ends here