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