]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/package.el
* lisp/emacs-lisp/package.el (package--prepare-dependencies):
[gnu-emacs] / lisp / emacs-lisp / package.el
1 ;;; package.el --- Simple package system for Emacs -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2007-2014 Free Software Foundation, Inc.
4
5 ;; Author: Tom Tromey <tromey@redhat.com>
6 ;; Daniel Hackney <dan@haxney.org>
7 ;; Created: 10 Mar 2007
8 ;; Version: 1.0.1
9 ;; Keywords: tools
10 ;; Package-Requires: ((tabulated-list "1.0"))
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
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 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-install-from-buffer
88 ;; Install a package consisting of a single .el file that appears
89 ;; in the current buffer. This only works for packages which
90 ;; define a Version header properly; package.el also supports the
91 ;; extension headers Package-Version (in case Version is an RCS id
92 ;; or similar), and Package-Requires (if the package requires other
93 ;; packages).
94 ;;
95 ;; M-x package-install-file
96 ;; Install a package from the indicated file. The package can be
97 ;; either a tar file or a .el file. A tar file must contain an
98 ;; appropriately-named "-pkg.el" file; a .el file must be properly
99 ;; formatted as with package-install-from-buffer.
100
101 ;;; Thanks:
102 ;;; (sorted by sort-lines):
103
104 ;; Jim Blandy <jimb@red-bean.com>
105 ;; Karl Fogel <kfogel@red-bean.com>
106 ;; Kevin Ryde <user42@zip.com.au>
107 ;; Lawrence Mitchell
108 ;; Michael Olson <mwolson@member.fsf.org>
109 ;; Sebastian Tennant <sebyte@smolny.plus.com>
110 ;; Stefan Monnier <monnier@iro.umontreal.ca>
111 ;; Vinicius Jose Latorre <viniciusjl@ig.com.br>
112 ;; Phil Hagelberg <phil@hagelb.org>
113
114 ;;; ToDo:
115
116 ;; - a trust mechanism, since compiling a package can run arbitrary code.
117 ;; For example, download package signatures and check that they match.
118 ;; - putting info dirs at the start of the info path means
119 ;; users see a weird ordering of categories. OTOH we want to
120 ;; override later entries. maybe emacs needs to enforce
121 ;; the standard layout?
122 ;; - put bytecode in a separate directory tree
123 ;; - perhaps give users a way to recompile their bytecode
124 ;; or do it automatically when emacs changes
125 ;; - give users a way to know whether a package is installed ok
126 ;; - give users a way to view a package's documentation when it
127 ;; only appears in the .el
128 ;; - use/extend checkdoc so people can tell if their package will work
129 ;; - "installed" instead of a blank in the status column
130 ;; - tramp needs its files to be compiled in a certain order.
131 ;; how to handle this? fix tramp?
132 ;; - on emacs 21 we don't kill the -autoloads.el buffer. what about 22?
133 ;; - maybe we need separate .elc directories for various emacs versions
134 ;; and also emacs-vs-xemacs. That way conditional compilation can
135 ;; work. But would this break anything?
136 ;; - should store the package's keywords in archive-contents, then
137 ;; let the users filter the package-menu by keyword. See
138 ;; finder-by-keyword. (We could also let people view the
139 ;; Commentary, but it isn't clear how useful this is.)
140 ;; - William Xu suggests being able to open a package file without
141 ;; installing it
142 ;; - Interface with desktop.el so that restarting after an install
143 ;; works properly
144 ;; - Use hierarchical layout. PKG/etc PKG/lisp PKG/info
145 ;; ... except maybe lisp?
146 ;; - It may be nice to have a macro that expands to the package's
147 ;; private data dir, aka ".../etc". Or, maybe data-directory
148 ;; needs to be a list (though this would be less nice)
149 ;; a few packages want this, eg sokoban
150 ;; - package menu needs:
151 ;; ability to know which packages are built-in & thus not deletable
152 ;; it can sometimes print odd results, like 0.3 available but 0.4 active
153 ;; why is that?
154 ;; - Allow multiple versions on the server...?
155 ;; [ why bother? ]
156 ;; - Don't install a package which will invalidate dependencies overall
157 ;; - Allow something like (or (>= emacs 21.0) (>= xemacs 21.5))
158 ;; [ currently thinking, why bother.. KISS ]
159 ;; - Allow optional package dependencies
160 ;; then if we require 'bbdb', bbdb-specific lisp in lisp/bbdb
161 ;; and just don't compile to add to load path ...?
162 ;; - Our treatment of the info path is somewhat bogus
163
164 ;;; Code:
165
166 (eval-when-compile (require 'cl-lib))
167
168 (require 'tabulated-list)
169
170 (defgroup package nil
171 "Manager for Emacs Lisp packages."
172 :group 'applications
173 :version "24.1")
174
175 ;;;###autoload
176 (defcustom package-enable-at-startup t
177 "Whether to activate installed packages when Emacs starts.
178 If non-nil, packages are activated after reading the init file
179 and before `after-init-hook'. Activation is not done if
180 `user-init-file' is nil (e.g. Emacs was started with \"-q\").
181
182 Even if the value is nil, you can type \\[package-initialize] to
183 activate the package system at any time."
184 :type 'boolean
185 :group 'package
186 :version "24.1")
187
188 (defcustom package-load-list '(all)
189 "List of packages for `package-initialize' to load.
190 Each element in this list should be a list (NAME VERSION), or the
191 symbol `all'. The symbol `all' says to load the latest installed
192 versions of all packages not specified by other elements.
193
194 For an element (NAME VERSION), NAME is a package name (a symbol).
195 VERSION should be t, a string, or nil.
196 If VERSION is t, the most recent version is activated.
197 If VERSION is a string, only that version is ever loaded.
198 Any other version, even if newer, is silently ignored.
199 Hence, the package is \"held\" at that version.
200 If VERSION is nil, the package is not loaded (it is \"disabled\")."
201 :type '(repeat symbol)
202 :risky t
203 :group 'package
204 :version "24.1")
205
206 (defvar Info-directory-list)
207 (declare-function info-initialize "info" ())
208 (declare-function url-http-parse-response "url-http" ())
209 (declare-function url-http-file-exists-p "url-http" (url))
210 (declare-function lm-header "lisp-mnt" (header))
211 (declare-function lm-commentary "lisp-mnt" (&optional file))
212 (defvar url-http-end-of-headers)
213 (declare-function url-recreate-url "url-parse" (urlobj))
214 (defvar url-http-target-url)
215
216 (defcustom package-archives '(("gnu" . "http://elpa.gnu.org/packages/"))
217 "An alist of archives from which to fetch.
218 The default value points to the GNU Emacs package repository.
219
220 Each element has the form (ID . LOCATION).
221 ID is an archive name, as a string.
222 LOCATION specifies the base location for the archive.
223 If it starts with \"http:\", it is treated as a HTTP URL;
224 otherwise it should be an absolute directory name.
225 (Other types of URL are currently not supported.)
226
227 Only add locations that you trust, since fetching and installing
228 a package can run arbitrary code."
229 :type '(alist :key-type (string :tag "Archive name")
230 :value-type (string :tag "URL or directory name"))
231 :risky t
232 :group 'package
233 :version "24.1")
234
235 (defcustom package-pinned-packages nil
236 "An alist of packages that are pinned to a specific archive
237
238 Each element has the form (SYM . ID).
239 SYM is a package, as a symbol.
240 ID is an archive name. This should correspond to an
241 entry in `package-archives'.
242
243 If the archive of name ID does not contain the package SYM, no
244 other location will be considered, which will make the
245 package unavailable."
246 :type '(alist :key-type (symbol :tag "Package")
247 :value-type (string :tag "Archive name"))
248 :risky t
249 :group 'package
250 :version "24.4")
251
252 (defconst package-archive-version 1
253 "Version number of the package archive understood by this file.
254 Lower version numbers than this will probably be understood as well.")
255
256 ;; We don't prime the cache since it tends to get out of date.
257 (defvar package-archive-contents nil
258 "Cache of the contents of the Emacs Lisp Package Archive.
259 This is an alist mapping package names (symbols) to
260 non-empty lists of `package-desc' structures.")
261 (put 'package-archive-contents 'risky-local-variable t)
262
263 (defcustom package-user-dir (locate-user-emacs-file "elpa")
264 "Directory containing the user's Emacs Lisp packages.
265 The directory name should be absolute.
266 Apart from this directory, Emacs also looks for system-wide
267 packages in `package-directory-list'."
268 :type 'directory
269 :risky t
270 :group 'package
271 :version "24.1")
272
273 (defcustom package-directory-list
274 ;; Defaults are subdirs named "elpa" in the site-lisp dirs.
275 (let (result)
276 (dolist (f load-path)
277 (and (stringp f)
278 (equal (file-name-nondirectory f) "site-lisp")
279 (push (expand-file-name "elpa" f) result)))
280 (nreverse result))
281 "List of additional directories containing Emacs Lisp packages.
282 Each directory name should be absolute.
283
284 These directories contain packages intended for system-wide; in
285 contrast, `package-user-dir' contains packages for personal use."
286 :type '(repeat directory)
287 :risky t
288 :group 'package
289 :version "24.1")
290
291 (defcustom package-check-signature 'allow-unsigned
292 "Whether to check package signatures when installing."
293 :type '(choice (const nil :tag "Never")
294 (const allow-unsigned :tag "Allow unsigned")
295 (const t :tag "Check always"))
296 :risky t
297 :group 'package
298 :version "24.1")
299
300 (defcustom package-unsigned-archives nil
301 "A list of archives which do not use package signature."
302 :type '(repeat (string :tag "Archive name"))
303 :risky t
304 :group 'package
305 :version "24.1")
306
307 (defvar package--default-summary "No description available.")
308
309 (cl-defstruct (package-desc
310 ;; Rename the default constructor from `make-package-desc'.
311 (:constructor package-desc-create)
312 ;; Has the same interface as the old `define-package',
313 ;; which is still used in the "foo-pkg.el" files. Extra
314 ;; options can be supported by adding additional keys.
315 (:constructor
316 package-desc-from-define
317 (name-string version-string &optional summary requirements
318 &rest rest-plist
319 &aux
320 (name (intern name-string))
321 (version (version-to-list version-string))
322 (reqs (mapcar #'(lambda (elt)
323 (list (car elt)
324 (version-to-list (cadr elt))))
325 (if (eq 'quote (car requirements))
326 (nth 1 requirements)
327 requirements)))
328 (kind (plist-get rest-plist :kind))
329 (archive (plist-get rest-plist :archive))
330 (extras (let (alist)
331 (while rest-plist
332 (unless (memq (car rest-plist) '(:kind :archive))
333 (let ((value (cadr rest-plist)))
334 (when value
335 (push (cons (car rest-plist)
336 (if (eq (car-safe value) 'quote)
337 (cdr value)
338 value))
339 alist))))
340 (setq rest-plist (cddr rest-plist)))
341 alist)))))
342 "Structure containing information about an individual package.
343 Slots:
344
345 `name' Name of the package, as a symbol.
346
347 `version' Version of the package, as a version list.
348
349 `summary' Short description of the package, typically taken from
350 the first line of the file.
351
352 `reqs' Requirements of the package. A list of (PACKAGE
353 VERSION-LIST) naming the dependent package and the minimum
354 required version.
355
356 `kind' The distribution format of the package. Currently, it is
357 either `single' or `tar'.
358
359 `archive' The name of the archive (as a string) whence this
360 package came.
361
362 `dir' The directory where the package is installed (if installed),
363 `builtin' if it is built-in, or nil otherwise.
364
365 `extras' Optional alist of additional keyword-value pairs.
366
367 `signed' Flag to indicate that the package is signed by provider."
368 name
369 version
370 (summary package--default-summary)
371 reqs
372 kind
373 archive
374 dir
375 extras
376 signed)
377
378 ;; Pseudo fields.
379 (defun package-desc-full-name (pkg-desc)
380 (format "%s-%s"
381 (package-desc-name pkg-desc)
382 (package-version-join (package-desc-version pkg-desc))))
383
384 (defun package-desc-suffix (pkg-desc)
385 (pcase (package-desc-kind pkg-desc)
386 (`single ".el")
387 (`tar ".tar")
388 (kind (error "Unknown package kind: %s" kind))))
389
390 (defun package-desc--keywords (pkg-desc)
391 (let ((keywords (cdr (assoc :keywords (package-desc-extras pkg-desc)))))
392 (if (eq (car-safe keywords) 'quote)
393 (nth 1 keywords)
394 keywords)))
395
396 ;; Package descriptor format used in finder-inf.el and package--builtins.
397 (cl-defstruct (package--bi-desc
398 (:constructor package-make-builtin (version summary))
399 (:type vector))
400 version
401 reqs
402 summary)
403
404 (defvar package--builtins nil
405 "Alist of built-in packages.
406 The actual value is initialized by loading the library
407 `finder-inf'; this is not done until it is needed, e.g. by the
408 function `package-built-in-p'.
409
410 Each element has the form (PKG . PACKAGE-BI-DESC), where PKG is a package
411 name (a symbol) and DESC is a `package--bi-desc' structure.")
412 (put 'package--builtins 'risky-local-variable t)
413
414 (defvar package-alist nil
415 "Alist of all packages available for activation.
416 Each element has the form (PKG . DESCS), where PKG is a package
417 name (a symbol) and DESCS is a non-empty list of `package-desc' structure,
418 sorted by decreasing versions.
419
420 This variable is set automatically by `package-load-descriptor',
421 called via `package-initialize'. To change which packages are
422 loaded and/or activated, customize `package-load-list'.")
423 (put 'package-alist 'risky-local-variable t)
424
425 (defvar package-activated-list nil
426 ;; FIXME: This should implicitly include all builtin packages.
427 "List of the names of currently activated packages.")
428 (put 'package-activated-list 'risky-local-variable t)
429
430 (defun package-version-join (vlist)
431 "Return the version string corresponding to the list VLIST.
432 This is, approximately, the inverse of `version-to-list'.
433 \(Actually, it returns only one of the possible inverses, since
434 `version-to-list' is a many-to-one operation.)"
435 (if (null vlist)
436 ""
437 (let ((str-list (list "." (int-to-string (car vlist)))))
438 (dolist (num (cdr vlist))
439 (cond
440 ((>= num 0)
441 (push (int-to-string num) str-list)
442 (push "." str-list))
443 ((< num -4)
444 (error "Invalid version list `%s'" vlist))
445 (t
446 ;; pre, or beta, or alpha
447 (cond ((equal "." (car str-list))
448 (pop str-list))
449 ((not (string-match "[0-9]+" (car str-list)))
450 (error "Invalid version list `%s'" vlist)))
451 (push (cond ((= num -1) "pre")
452 ((= num -2) "beta")
453 ((= num -3) "alpha")
454 ((= num -4) "snapshot"))
455 str-list))))
456 (if (equal "." (car str-list))
457 (pop str-list))
458 (apply 'concat (nreverse str-list)))))
459
460 (defun package-load-descriptor (pkg-dir)
461 "Load the description file in directory PKG-DIR."
462 (let ((pkg-file (expand-file-name (package--description-file pkg-dir)
463 pkg-dir))
464 (signed-file (concat pkg-dir ".signed")))
465 (when (file-exists-p pkg-file)
466 (with-temp-buffer
467 (insert-file-contents pkg-file)
468 (goto-char (point-min))
469 (let ((pkg-desc (package-process-define-package
470 (read (current-buffer)) pkg-file)))
471 (setf (package-desc-dir pkg-desc) pkg-dir)
472 (if (file-exists-p signed-file)
473 (setf (package-desc-signed pkg-desc) t))
474 pkg-desc)))))
475
476 (defun package-load-all-descriptors ()
477 "Load descriptors for installed Emacs Lisp packages.
478 This looks for package subdirectories in `package-user-dir' and
479 `package-directory-list'. The variable `package-load-list'
480 controls which package subdirectories may be loaded.
481
482 In each valid package subdirectory, this function loads the
483 description file containing a call to `define-package', which
484 updates `package-alist'."
485 (dolist (dir (cons package-user-dir package-directory-list))
486 (when (file-directory-p dir)
487 (dolist (subdir (directory-files dir))
488 (let ((pkg-dir (expand-file-name subdir dir)))
489 (when (file-directory-p pkg-dir)
490 (package-load-descriptor pkg-dir)))))))
491
492 (defun package-disabled-p (pkg-name version)
493 "Return whether PKG-NAME at VERSION can be activated.
494 The decision is made according to `package-load-list'.
495 Return nil if the package can be activated.
496 Return t if the package is completely disabled.
497 Return the max version (as a string) if the package is held at a lower version."
498 (let ((force (assq pkg-name package-load-list)))
499 (cond ((null force) (not (memq 'all package-load-list)))
500 ((null (setq force (cadr force))) t) ; disabled
501 ((eq force t) nil)
502 ((stringp force) ; held
503 (unless (version-list-= version (version-to-list force))
504 force))
505 (t (error "Invalid element in `package-load-list'")))))
506
507 (defun package-activate-1 (pkg-desc)
508 (let* ((name (package-desc-name pkg-desc))
509 (pkg-dir (package-desc-dir pkg-desc))
510 (pkg-dir-dir (file-name-as-directory pkg-dir)))
511 (unless pkg-dir
512 (error "Internal error: unable to find directory for `%s'"
513 (package-desc-full-name pkg-desc)))
514 ;; Add to load path, add autoloads, and activate the package.
515 (let ((old-lp load-path))
516 (with-demoted-errors
517 (load (expand-file-name (format "%s-autoloads" name) pkg-dir) nil t))
518 (when (and (eq old-lp load-path)
519 (not (or (member pkg-dir load-path)
520 (member pkg-dir-dir load-path))))
521 ;; Old packages don't add themselves to the `load-path', so we have to
522 ;; do it ourselves.
523 (push pkg-dir load-path)))
524 ;; Add info node.
525 (when (file-exists-p (expand-file-name "dir" pkg-dir))
526 ;; FIXME: not the friendliest, but simple.
527 (require 'info)
528 (info-initialize)
529 (push pkg-dir Info-directory-list))
530 (push name package-activated-list)
531 ;; Don't return nil.
532 t))
533
534 (defun package-built-in-p (package &optional min-version)
535 "Return true if PACKAGE is built-in to Emacs.
536 Optional arg MIN-VERSION, if non-nil, should be a version list
537 specifying the minimum acceptable version."
538 (if (package-desc-p package) ;; was built-in and then was converted
539 (eq 'builtin (package-desc-dir package))
540 (let ((bi (assq package package--builtin-versions)))
541 (cond
542 (bi (version-list-<= min-version (cdr bi)))
543 (min-version nil)
544 (t
545 (require 'finder-inf nil t) ; For `package--builtins'.
546 (assq package package--builtins))))))
547
548 (defun package--from-builtin (bi-desc)
549 (package-desc-create :name (pop bi-desc)
550 :version (package--bi-desc-version bi-desc)
551 :summary (package--bi-desc-summary bi-desc)
552 :dir 'builtin))
553
554 ;; This function goes ahead and activates a newer version of a package
555 ;; if an older one was already activated. This is not ideal; we'd at
556 ;; least need to check to see if the package has actually been loaded,
557 ;; and not merely activated.
558 (defun package-activate (package &optional force)
559 "Activate package PACKAGE.
560 If FORCE is true, (re-)activate it if it's already activated."
561 (let ((pkg-descs (cdr (assq package package-alist))))
562 ;; Check if PACKAGE is available in `package-alist'.
563 (while
564 (when pkg-descs
565 (let ((available-version (package-desc-version (car pkg-descs))))
566 (or (package-disabled-p package available-version)
567 ;; Prefer a builtin package.
568 (package-built-in-p package available-version))))
569 (setq pkg-descs (cdr pkg-descs)))
570 (cond
571 ;; If no such package is found, maybe it's built-in.
572 ((null pkg-descs)
573 (package-built-in-p package))
574 ;; If the package is already activated, just return t.
575 ((and (memq package package-activated-list) (not force))
576 t)
577 ;; Otherwise, proceed with activation.
578 (t
579 (let* ((pkg-vec (car pkg-descs))
580 (fail (catch 'dep-failure
581 ;; Activate its dependencies recursively.
582 (dolist (req (package-desc-reqs pkg-vec))
583 (unless (package-activate (car req) (cadr req))
584 (throw 'dep-failure req))))))
585 (if fail
586 (warn "Unable to activate package `%s'.
587 Required package `%s-%s' is unavailable"
588 package (car fail) (package-version-join (cadr fail)))
589 ;; If all goes well, activate the package itself.
590 (package-activate-1 pkg-vec)))))))
591
592 (defun define-package (_name-string _version-string
593 &optional _docstring _requirements
594 &rest _extra-properties)
595 "Define a new package.
596 NAME-STRING is the name of the package, as a string.
597 VERSION-STRING is the version of the package, as a string.
598 DOCSTRING is a short description of the package, a string.
599 REQUIREMENTS is a list of dependencies on other packages.
600 Each requirement is of the form (OTHER-PACKAGE OTHER-VERSION),
601 where OTHER-VERSION is a string.
602
603 EXTRA-PROPERTIES is currently unused."
604 ;; FIXME: Placeholder! Should we keep it?
605 (error "Don't call me!"))
606
607 (defun package-process-define-package (exp origin)
608 (unless (eq (car-safe exp) 'define-package)
609 (error "Can't find define-package in %s" origin))
610 (let* ((new-pkg-desc (apply #'package-desc-from-define (cdr exp)))
611 (name (package-desc-name new-pkg-desc))
612 (version (package-desc-version new-pkg-desc))
613 (old-pkgs (assq name package-alist)))
614 (if (null old-pkgs)
615 ;; If there's no old package, just add this to `package-alist'.
616 (push (list name new-pkg-desc) package-alist)
617 ;; If there is, insert the new package at the right place in the list.
618 (while
619 (if (and (cdr old-pkgs)
620 (version-list-< version
621 (package-desc-version (cadr old-pkgs))))
622 (setq old-pkgs (cdr old-pkgs))
623 (push new-pkg-desc (cdr old-pkgs))
624 nil)))
625 new-pkg-desc))
626
627 ;; From Emacs 22, but changed so it adds to load-path.
628 (defun package-autoload-ensure-default-file (file)
629 "Make sure that the autoload file FILE exists and if not create it."
630 (unless (file-exists-p file)
631 (write-region
632 (concat ";;; " (file-name-nondirectory file)
633 " --- automatically extracted autoloads\n"
634 ";;\n"
635 ";;; Code:\n"
636 "(add-to-list 'load-path (or (file-name-directory #$) (car load-path)))\n"
637 "\f\n;; Local Variables:\n"
638 ";; version-control: never\n"
639 ";; no-byte-compile: t\n"
640 ";; no-update-autoloads: t\n"
641 ";; End:\n"
642 ";;; " (file-name-nondirectory file)
643 " ends here\n")
644 nil file nil 'silent))
645 file)
646
647 (defvar generated-autoload-file)
648 (defvar version-control)
649
650 (defun package-generate-autoloads (name pkg-dir)
651 (let* ((auto-name (format "%s-autoloads.el" name))
652 ;;(ignore-name (concat name "-pkg.el"))
653 (generated-autoload-file (expand-file-name auto-name pkg-dir))
654 (version-control 'never))
655 (package-autoload-ensure-default-file generated-autoload-file)
656 (update-directory-autoloads pkg-dir)
657 (let ((buf (find-buffer-visiting generated-autoload-file)))
658 (when buf (kill-buffer buf)))
659 auto-name))
660
661 (defvar tar-parse-info)
662 (declare-function tar-untar-buffer "tar-mode" ())
663 (declare-function tar-header-name "tar-mode" (tar-header) t)
664 (declare-function tar-header-link-type "tar-mode" (tar-header) t)
665
666 (defun package-untar-buffer (dir)
667 "Untar the current buffer.
668 This uses `tar-untar-buffer' from Tar mode. All files should
669 untar into a directory named DIR; otherwise, signal an error."
670 (require 'tar-mode)
671 (tar-mode)
672 ;; Make sure everything extracts into DIR.
673 (let ((regexp (concat "\\`" (regexp-quote (expand-file-name dir)) "/"))
674 (case-fold-search (memq system-type '(windows-nt ms-dos cygwin))))
675 (dolist (tar-data tar-parse-info)
676 (let ((name (expand-file-name (tar-header-name tar-data))))
677 (or (string-match regexp name)
678 ;; Tarballs created by some utilities don't list
679 ;; directories with a trailing slash (Bug#13136).
680 (and (string-equal dir name)
681 (eq (tar-header-link-type tar-data) 5))
682 (error "Package does not untar cleanly into directory %s/" dir)))))
683 (tar-untar-buffer))
684
685 (defun package-generate-description-file (pkg-desc pkg-dir)
686 "Create the foo-pkg.el file for single-file packages."
687 (let* ((name (package-desc-name pkg-desc))
688 (pkg-file (expand-file-name (package--description-file pkg-dir)
689 pkg-dir)))
690 (let ((print-level nil)
691 (print-quoted t)
692 (print-length nil))
693 (write-region
694 (concat
695 (prin1-to-string
696 (nconc
697 (list 'define-package
698 (symbol-name name)
699 (package-version-join (package-desc-version pkg-desc))
700 (package-desc-summary pkg-desc)
701 (let ((requires (package-desc-reqs pkg-desc)))
702 (list 'quote
703 ;; Turn version lists into string form.
704 (mapcar
705 (lambda (elt)
706 (list (car elt)
707 (package-version-join (cadr elt))))
708 requires))))
709 (package--alist-to-plist
710 (package-desc-extras pkg-desc))))
711 "\n")
712 nil pkg-file nil 'silent))))
713
714 (defun package--alist-to-plist (alist)
715 (apply #'nconc (mapcar (lambda (pair) (list (car pair) (cdr pair))) alist)))
716
717 (defun package-unpack (pkg-desc)
718 "Install the contents of the current buffer as a package."
719 (let* ((name (package-desc-name pkg-desc))
720 (dirname (package-desc-full-name pkg-desc))
721 (pkg-dir (expand-file-name dirname package-user-dir)))
722 (pcase (package-desc-kind pkg-desc)
723 (`tar
724 (make-directory package-user-dir t)
725 ;; FIXME: should we delete PKG-DIR if it exists?
726 (let* ((default-directory (file-name-as-directory package-user-dir)))
727 (package-untar-buffer dirname)))
728 (`single
729 (let ((el-file (expand-file-name (format "%s.el" name) pkg-dir)))
730 (make-directory pkg-dir t)
731 (package--write-file-no-coding el-file)))
732 (kind (error "Unknown package kind: %S" kind)))
733 (package--make-autoloads-and-stuff pkg-desc pkg-dir)
734 ;; Update package-alist.
735 (let ((new-desc (package-load-descriptor pkg-dir)))
736 ;; FIXME: Check that `new-desc' matches `desc'!
737 ;; FIXME: Compilation should be done as a separate, optional, step.
738 ;; E.g. for multi-package installs, we should first install all packages
739 ;; and then compile them.
740 (package--compile new-desc))
741 ;; Try to activate it.
742 (package-activate name 'force)
743 pkg-dir))
744
745 (defun package--make-autoloads-and-stuff (pkg-desc pkg-dir)
746 "Generate autoloads, description file, etc.. for PKG-DESC installed at PKG-DIR."
747 (package-generate-autoloads (package-desc-name pkg-desc) pkg-dir)
748 (let ((desc-file (package--description-file pkg-dir)))
749 (unless (file-exists-p desc-file)
750 (package-generate-description-file pkg-desc pkg-dir)))
751 ;; FIXME: Create foo.info and dir file from foo.texi?
752 )
753
754 (defun package--compile (pkg-desc)
755 "Byte-compile installed package PKG-DESC."
756 (package-activate-1 pkg-desc)
757 (byte-recompile-directory (package-desc-dir pkg-desc) 0 t))
758
759 (defun package--write-file-no-coding (file-name)
760 (let ((buffer-file-coding-system 'no-conversion))
761 (write-region (point-min) (point-max) file-name nil 'silent)))
762
763 (defmacro package--with-work-buffer (location file &rest body)
764 "Run BODY in a buffer containing the contents of FILE at LOCATION.
765 LOCATION is the base location of a package archive, and should be
766 one of the URLs (or file names) specified in `package-archives'.
767 FILE is the name of a file relative to that base location.
768
769 This macro retrieves FILE from LOCATION into a temporary buffer,
770 and evaluates BODY while that buffer is current. This work
771 buffer is killed afterwards. Return the last value in BODY."
772 (declare (indent 2) (debug t))
773 `(let* ((http (string-match "\\`https?:" ,location))
774 (buffer
775 (if http
776 (url-retrieve-synchronously (concat ,location ,file))
777 (generate-new-buffer "*package work buffer*"))))
778 (prog1
779 (with-current-buffer buffer
780 (if http
781 (progn (package-handle-response)
782 (re-search-forward "^$" nil 'move)
783 (forward-char)
784 (delete-region (point-min) (point)))
785 (unless (file-name-absolute-p ,location)
786 (error "Archive location %s is not an absolute file name"
787 ,location))
788 (insert-file-contents (expand-file-name ,file ,location)))
789 ,@body)
790 (kill-buffer buffer))))
791
792 (defun package-handle-response ()
793 "Handle the response from a `url-retrieve-synchronously' call.
794 Parse the HTTP response and throw if an error occurred.
795 The url package seems to require extra processing for this.
796 This should be called in a `save-excursion', in the download buffer.
797 It will move point to somewhere in the headers."
798 ;; We assume HTTP here.
799 (require 'url-http)
800 (let ((response (url-http-parse-response)))
801 (when (or (< response 200) (>= response 300))
802 (error "Error downloading %s:%s"
803 (url-recreate-url url-http-target-url)
804 (buffer-substring-no-properties (point) (line-end-position))))))
805
806 (defun package--archive-file-exists-p (location file)
807 (let ((http (string-match "\\`https?:" location)))
808 (if http
809 (progn
810 (require 'url-http)
811 (url-http-file-exists-p (concat location file)))
812 (file-exists-p (expand-file-name file location)))))
813
814 (declare-function epg-make-context "epg"
815 (&optional protocol armor textmode include-certs
816 cipher-algorithm
817 digest-algorithm
818 compress-algorithm))
819 (declare-function epg-context-set-home-directory "epg" (context directory))
820 (declare-function epg-verify-string "epg" (context signature
821 &optional signed-text))
822 (declare-function epg-context-result-for "epg" (context name))
823 (declare-function epg-signature-status "epg" (signature))
824 (declare-function epg-signature-to-string "epg" (signature))
825
826 (defun package--check-signature (location file)
827 "Check signature of the current buffer.
828 GnuPG keyring is located under \"gnupg\" in `package-user-dir'."
829 (let* ((context (epg-make-context 'OpenPGP))
830 (homedir (expand-file-name "gnupg" package-user-dir))
831 (sig-file (concat file ".sig"))
832 (sig-content (package--with-work-buffer location sig-file
833 (buffer-string))))
834 (epg-context-set-home-directory context homedir)
835 (epg-verify-string context sig-content (buffer-string))
836 ;; The .sig file may contain multiple signatures. Success if one
837 ;; of the signatures is good.
838 (let ((good-signatures
839 (delq nil (mapcar (lambda (sig)
840 (if (eq (epg-signature-status sig) 'good)
841 sig))
842 (epg-context-result-for context 'verify)))))
843 (if (null good-signatures)
844 (error "Failed to verify signature %s: %S"
845 sig-file
846 (mapcar #'epg-signature-to-string
847 (epg-context-result-for context 'verify)))
848 good-signatures))))
849
850 (defun package-install-from-archive (pkg-desc)
851 "Download and install a tar package."
852 (let* ((location (package-archive-base pkg-desc))
853 (file (concat (package-desc-full-name pkg-desc)
854 (package-desc-suffix pkg-desc)))
855 (sig-file (concat file ".sig"))
856 good-signatures pkg-descs)
857 (package--with-work-buffer location file
858 (if (and package-check-signature
859 (not (member (package-desc-archive pkg-desc)
860 package-unsigned-archives)))
861 (if (package--archive-file-exists-p location sig-file)
862 (setq good-signatures (package--check-signature location file))
863 (unless (eq package-check-signature 'allow-unsigned)
864 (error "Unsigned package: `%s'"
865 (package-desc-name pkg-desc)))))
866 (package-unpack pkg-desc))
867 ;; Here the package has been installed successfully, mark it as
868 ;; signed if appropriate.
869 (when good-signatures
870 ;; Write out good signatures into NAME-VERSION.signed file.
871 (write-region (mapconcat #'epg-signature-to-string good-signatures "\n")
872 nil
873 (expand-file-name
874 (concat (package-desc-full-name pkg-desc)
875 ".signed")
876 package-user-dir)
877 nil 'silent)
878 ;; Update the old pkg-desc which will be shown on the description buffer.
879 (setf (package-desc-signed pkg-desc) t)
880 ;; Update the new (activated) pkg-desc as well.
881 (setq pkg-descs (cdr (assq (package-desc-name pkg-desc) package-alist)))
882 (if pkg-descs
883 (setf (package-desc-signed (car pkg-descs)) t)))))
884
885 (defvar package--initialized nil)
886
887 (defun package-installed-p (package &optional min-version)
888 "Return true if PACKAGE, of MIN-VERSION or newer, is installed.
889 MIN-VERSION should be a version list."
890 (unless package--initialized (error "package.el is not yet initialized!"))
891 (or
892 (let ((pkg-descs (cdr (assq package package-alist))))
893 (and pkg-descs
894 (version-list-<= min-version
895 (package-desc-version (car pkg-descs)))))
896 ;; Also check built-in packages.
897 (package-built-in-p package min-version)))
898
899 (defun package-compute-transaction (packages requirements)
900 "Return a list of packages to be installed, including PACKAGES.
901 PACKAGES should be a list of `package-desc'.
902
903 REQUIREMENTS should be a list of additional requirements; each
904 element in this list should have the form (PACKAGE VERSION-LIST),
905 where PACKAGE is a package name and VERSION-LIST is the required
906 version of that package.
907
908 This function recursively computes the requirements of the
909 packages in REQUIREMENTS, and returns a list of all the packages
910 that must be installed. Packages that are already installed are
911 not included in this list."
912 ;; FIXME: We really should use backtracking to explore the whole
913 ;; search space (e.g. if foo require bar-1.3, and bar-1.4 requires toto-1.1
914 ;; whereas bar-1.3 requires toto-1.0 and the user has put a hold on toto-1.0:
915 ;; the current code might fail to see that it could install foo by using the
916 ;; older bar-1.3).
917 (dolist (elt requirements)
918 (let* ((next-pkg (car elt))
919 (next-version (cadr elt))
920 (already ()))
921 (dolist (pkg packages)
922 (if (eq next-pkg (package-desc-name pkg))
923 (setq already pkg)))
924 (cond
925 (already
926 (if (version-list-< next-version (package-desc-version already))
927 ;; Move to front, so it gets installed early enough (bug#14082).
928 (setq packages (cons already (delq already packages)))
929 (error "Need package `%s-%s', but only %s is available"
930 next-pkg (package-version-join next-version)
931 (package-version-join (package-desc-version already)))))
932
933 ((package-installed-p next-pkg next-version) nil)
934
935 (t
936 ;; A package is required, but not installed. It might also be
937 ;; blocked via `package-load-list'.
938 (let ((pkg-descs (cdr (assq next-pkg package-archive-contents)))
939 (found nil)
940 (problem nil))
941 (while (and pkg-descs (not found))
942 (let* ((pkg-desc (pop pkg-descs))
943 (version (package-desc-version pkg-desc))
944 (disabled (package-disabled-p next-pkg version)))
945 (cond
946 ((version-list-< version next-version)
947 (error
948 "Need package `%s-%s', but only %s is available"
949 next-pkg (package-version-join next-version)
950 (package-version-join version)))
951 (disabled
952 (unless problem
953 (setq problem
954 (if (stringp disabled)
955 (format "Package `%s' held at version %s, \
956 but version %s required"
957 next-pkg disabled
958 (package-version-join next-version))
959 (format "Required package '%s' is disabled"
960 next-pkg)))))
961 (t (setq found pkg-desc)))))
962 (unless found
963 (if problem
964 (error problem)
965 (error "Package `%s-%s' is unavailable"
966 next-pkg (package-version-join next-version))))
967 (setq packages
968 (package-compute-transaction (cons found packages)
969 (package-desc-reqs found))))))))
970 packages)
971
972 (defun package-read-from-string (str)
973 "Read a Lisp expression from STR.
974 Signal an error if the entire string was not used."
975 (let* ((read-data (read-from-string str))
976 (more-left
977 (condition-case nil
978 ;; The call to `ignore' suppresses a compiler warning.
979 (progn (ignore (read-from-string
980 (substring str (cdr read-data))))
981 t)
982 (end-of-file nil))))
983 (if more-left
984 (error "Can't read whole string")
985 (car read-data))))
986
987 (defun package--read-archive-file (file)
988 "Re-read archive file FILE, if it exists.
989 Will return the data from the file, or nil if the file does not exist.
990 Will throw an error if the archive version is too new."
991 (let ((filename (expand-file-name file package-user-dir)))
992 (when (file-exists-p filename)
993 (with-temp-buffer
994 (insert-file-contents-literally filename)
995 (let ((contents (read (current-buffer))))
996 (if (> (car contents) package-archive-version)
997 (error "Package archive version %d is higher than %d"
998 (car contents) package-archive-version))
999 (cdr contents))))))
1000
1001 (defun package-read-all-archive-contents ()
1002 "Re-read `archive-contents', if it exists.
1003 If successful, set `package-archive-contents'."
1004 (setq package-archive-contents nil)
1005 (dolist (archive package-archives)
1006 (package-read-archive-contents (car archive))))
1007
1008 (defun package-read-archive-contents (archive)
1009 "Re-read archive contents for ARCHIVE.
1010 If successful, set the variable `package-archive-contents'.
1011 If the archive version is too new, signal an error."
1012 ;; Version 1 of 'archive-contents' is identical to our internal
1013 ;; representation.
1014 (let* ((contents-file (format "archives/%s/archive-contents" archive))
1015 (contents (package--read-archive-file contents-file)))
1016 (when contents
1017 (dolist (package contents)
1018 (package--add-to-archive-contents package archive)))))
1019
1020 ;; Package descriptor objects used inside the "archive-contents" file.
1021 ;; Changing this defstruct implies changing the format of the
1022 ;; "archive-contents" files.
1023 (cl-defstruct (package--ac-desc
1024 (:constructor package-make-ac-desc (version reqs summary kind extras))
1025 (:copier nil)
1026 (:type vector))
1027 version reqs summary kind extras)
1028
1029 (defun package--add-to-archive-contents (package archive)
1030 "Add the PACKAGE from the given ARCHIVE if necessary.
1031 PACKAGE should have the form (NAME . PACKAGE--AC-DESC).
1032 Also, add the originating archive to the `package-desc' structure."
1033 (let* ((name (car package))
1034 (version (package--ac-desc-version (cdr package)))
1035 (pkg-desc
1036 (package-desc-create
1037 :name name
1038 :version version
1039 :reqs (package--ac-desc-reqs (cdr package))
1040 :summary (package--ac-desc-summary (cdr package))
1041 :kind (package--ac-desc-kind (cdr package))
1042 :archive archive
1043 :extras (and (> (length (cdr package)) 4)
1044 ;; Older archive-contents files have only 4
1045 ;; elements here.
1046 (package--ac-desc-extras (cdr package)))))
1047 (existing-packages (assq name package-archive-contents))
1048 (pinned-to-archive (assoc name package-pinned-packages)))
1049 (cond
1050 ;; Skip entirely if pinned to another archive or already installed.
1051 ((or (and pinned-to-archive
1052 (not (equal (cdr pinned-to-archive) archive)))
1053 (let ((bi (assq name package--builtin-versions)))
1054 (and bi (version-list-= version (cdr bi))))
1055 (let ((ins (cdr (assq name package-alist))))
1056 (and ins (version-list-= version
1057 (package-desc-version (car ins))))))
1058 nil)
1059 ((not existing-packages)
1060 (push (list name pkg-desc) package-archive-contents))
1061 (t
1062 (while
1063 (if (and (cdr existing-packages)
1064 (version-list-<
1065 version (package-desc-version (cadr existing-packages))))
1066 (setq existing-packages (cdr existing-packages))
1067 (push pkg-desc (cdr existing-packages))
1068 nil))))))
1069
1070 (defun package-download-transaction (packages)
1071 "Download and install all the packages in PACKAGES.
1072 PACKAGES should be a list of package-desc.
1073 This function assumes that all package requirements in
1074 PACKAGES are satisfied, i.e. that PACKAGES is computed
1075 using `package-compute-transaction'."
1076 (mapc #'package-install-from-archive packages))
1077
1078 ;;;###autoload
1079 (defun package-install (pkg)
1080 "Install the package PKG.
1081 PKG can be a package-desc or the package name of one the available packages
1082 in an archive in `package-archives'. Interactively, prompt for its name."
1083 (interactive
1084 (progn
1085 ;; Initialize the package system to get the list of package
1086 ;; symbols for completion.
1087 (unless package--initialized
1088 (package-initialize t))
1089 (unless package-archive-contents
1090 (package-refresh-contents))
1091 (list (intern (completing-read
1092 "Install package: "
1093 (mapcar (lambda (elt) (symbol-name (car elt)))
1094 package-archive-contents)
1095 nil t)))))
1096 (package-download-transaction
1097 (if (package-desc-p pkg)
1098 (package-compute-transaction (list pkg)
1099 (package-desc-reqs pkg))
1100 (package-compute-transaction ()
1101 (list (list pkg))))))
1102
1103 (defun package-strip-rcs-id (str)
1104 "Strip RCS version ID from the version string STR.
1105 If the result looks like a dotted numeric version, return it.
1106 Otherwise return nil."
1107 (when str
1108 (when (string-match "\\`[ \t]*[$]Revision:[ \t]+" str)
1109 (setq str (substring str (match-end 0))))
1110 (condition-case nil
1111 (if (version-to-list str)
1112 str)
1113 (error nil))))
1114
1115 (declare-function lm-homepage "lisp-mnt" (&optional file))
1116
1117 (defun package--prepare-dependencies (deps)
1118 "Turn DEPS into an acceptable list of dependencies.
1119
1120 Any parts missing a version string get a default version string
1121 of \"0\" (meaning any version) and an appropriate level of lists
1122 is wrapped around any parts requiring it."
1123 (cond
1124 ((not (listp deps))
1125 (error "Invalid requirement specifier: %S" deps))
1126 (t (mapcar (lambda (dep)
1127 (cond
1128 ((symbolp dep) `(,dep "0"))
1129 ((stringp dep)
1130 (error "Invalid requirement specifier: %S" dep))
1131 ((and (listp dep) (null (cdr dep)))
1132 (list (car dep) "0"))
1133 (t dep)))
1134 deps))))
1135
1136 (defun package-buffer-info ()
1137 "Return a `package-desc' describing the package in the current buffer.
1138
1139 If the buffer does not contain a conforming package, signal an
1140 error. If there is a package, narrow the buffer to the file's
1141 boundaries."
1142 (goto-char (point-min))
1143 (unless (re-search-forward "^;;; \\([^ ]*\\)\\.el ---[ \t]*\\(.*?\\)[ \t]*\\(-\\*-.*-\\*-[ \t]*\\)?$" nil t)
1144 (error "Package lacks a file header"))
1145 (let ((file-name (match-string-no-properties 1))
1146 (desc (match-string-no-properties 2))
1147 (start (line-beginning-position)))
1148 (unless (search-forward (concat ";;; " file-name ".el ends here"))
1149 (error "Package lacks a terminating comment"))
1150 ;; Try to include a trailing newline.
1151 (forward-line)
1152 (narrow-to-region start (point))
1153 (require 'lisp-mnt)
1154 ;; Use some headers we've invented to drive the process.
1155 (let* ((requires-str (lm-header "package-requires"))
1156 ;; Prefer Package-Version; if defined, the package author
1157 ;; probably wants us to use it. Otherwise try Version.
1158 (pkg-version
1159 (or (package-strip-rcs-id (lm-header "package-version"))
1160 (package-strip-rcs-id (lm-header "version"))))
1161 (homepage (lm-homepage)))
1162 (unless pkg-version
1163 (error
1164 "Package lacks a \"Version\" or \"Package-Version\" header"))
1165 (package-desc-from-define
1166 file-name pkg-version desc
1167 (if requires-str
1168 (package--prepare-dependencies
1169 (package-read-from-string requires-str)))
1170 :kind 'single
1171 :url homepage))))
1172
1173 (declare-function tar-get-file-descriptor "tar-mode" (file))
1174 (declare-function tar--extract "tar-mode" (descriptor))
1175
1176 (defun package-tar-file-info ()
1177 "Find package information for a tar file.
1178 The return result is a `package-desc'."
1179 (cl-assert (derived-mode-p 'tar-mode))
1180 (let* ((dir-name (file-name-directory
1181 (tar-header-name (car tar-parse-info))))
1182 (desc-file (package--description-file dir-name))
1183 (tar-desc (tar-get-file-descriptor (concat dir-name desc-file))))
1184 (unless tar-desc
1185 (error "No package descriptor file found"))
1186 (with-current-buffer (tar--extract tar-desc)
1187 (goto-char (point-min))
1188 (unwind-protect
1189 (let* ((pkg-def-parsed (read (current-buffer)))
1190 (pkg-desc
1191 (if (not (eq (car pkg-def-parsed) 'define-package))
1192 (error "Can't find define-package in %s"
1193 (tar-header-name tar-desc))
1194 (apply #'package-desc-from-define
1195 (append (cdr pkg-def-parsed))))))
1196 (setf (package-desc-kind pkg-desc) 'tar)
1197 pkg-desc)
1198 (kill-buffer (current-buffer))))))
1199
1200
1201 ;;;###autoload
1202 (defun package-install-from-buffer ()
1203 "Install a package from the current buffer.
1204 The current buffer is assumed to be a single .el or .tar file that follows the
1205 packaging guidelines; see info node `(elisp)Packaging'.
1206 Downloads and installs required packages as needed."
1207 (interactive)
1208 (let ((pkg-desc (if (derived-mode-p 'tar-mode)
1209 (package-tar-file-info)
1210 (package-buffer-info))))
1211 ;; Download and install the dependencies.
1212 (let* ((requires (package-desc-reqs pkg-desc))
1213 (transaction (package-compute-transaction nil requires)))
1214 (package-download-transaction transaction))
1215 ;; Install the package itself.
1216 (package-unpack pkg-desc)
1217 pkg-desc))
1218
1219 ;;;###autoload
1220 (defun package-install-file (file)
1221 "Install a package from a file.
1222 The file can either be a tar file or an Emacs Lisp file."
1223 (interactive "fPackage file name: ")
1224 (with-temp-buffer
1225 (insert-file-contents-literally file)
1226 (when (string-match "\\.tar\\'" file) (tar-mode))
1227 (package-install-from-buffer)))
1228
1229 (defun package-delete (pkg-desc)
1230 (let ((dir (package-desc-dir pkg-desc)))
1231 (if (not (string-prefix-p (file-name-as-directory
1232 (expand-file-name package-user-dir))
1233 (expand-file-name dir)))
1234 ;; Don't delete "system" packages.
1235 (error "Package `%s' is a system package, not deleting"
1236 (package-desc-full-name pkg-desc))
1237 (delete-directory dir t t)
1238 ;; Remove NAME-VERSION.signed file.
1239 (let ((signed-file (concat dir ".signed")))
1240 (if (file-exists-p signed-file)
1241 (delete-file signed-file)))
1242 ;; Update package-alist.
1243 (let* ((name (package-desc-name pkg-desc))
1244 (pkgs (assq name package-alist)))
1245 (delete pkg-desc pkgs)
1246 (unless (cdr pkgs)
1247 (setq package-alist (delq pkgs package-alist))))
1248 (message "Package `%s' deleted." (package-desc-full-name pkg-desc)))))
1249
1250 (defun package-archive-base (desc)
1251 "Return the archive containing the package NAME."
1252 (cdr (assoc (package-desc-archive desc) package-archives)))
1253
1254 (defun package--download-one-archive (archive file)
1255 "Retrieve an archive file FILE from ARCHIVE, and cache it.
1256 ARCHIVE should be a cons cell of the form (NAME . LOCATION),
1257 similar to an entry in `package-alist'. Save the cached copy to
1258 \"archives/NAME/archive-contents\" in `package-user-dir'."
1259 (let ((dir (expand-file-name (format "archives/%s" (car archive))
1260 package-user-dir))
1261 (sig-file (concat file ".sig"))
1262 good-signatures)
1263 (package--with-work-buffer (cdr archive) file
1264 ;; Check signature of archive-contents, if desired.
1265 (if (and package-check-signature
1266 (not (member archive package-unsigned-archives)))
1267 (if (package--archive-file-exists-p (cdr archive) sig-file)
1268 (setq good-signatures (package--check-signature (cdr archive)
1269 file))
1270 (unless (eq package-check-signature 'allow-unsigned)
1271 (error "Unsigned archive `%s'"
1272 (car archive)))))
1273 ;; Read the retrieved buffer to make sure it is valid (e.g. it
1274 ;; may fetch a URL redirect page).
1275 (when (listp (read buffer))
1276 (make-directory dir t)
1277 (setq buffer-file-name (expand-file-name file dir))
1278 (let ((version-control 'never)
1279 (require-final-newline nil))
1280 (save-buffer))))
1281 (when good-signatures
1282 ;; Write out good signatures into archive-contents.signed file.
1283 (write-region (mapconcat #'epg-signature-to-string good-signatures "\n")
1284 nil
1285 (expand-file-name (concat file ".signed") dir)
1286 nil 'silent))))
1287
1288 (declare-function epg-check-configuration "epg-config"
1289 (config &optional minimum-version))
1290 (declare-function epg-configuration "epg-config" ())
1291 (declare-function epg-import-keys-from-file "epg" (context keys))
1292
1293 ;;;###autoload
1294 (defun package-import-keyring (&optional file)
1295 "Import keys from FILE."
1296 (interactive "fFile: ")
1297 (setq file (expand-file-name file))
1298 (let ((context (epg-make-context 'OpenPGP))
1299 (homedir (expand-file-name "gnupg" package-user-dir)))
1300 (make-directory homedir t)
1301 (epg-context-set-home-directory context homedir)
1302 (message "Importing %s..." (file-name-nondirectory file))
1303 (epg-import-keys-from-file context file)
1304 (message "Importing %s...done" (file-name-nondirectory file))))
1305
1306 ;;;###autoload
1307 (defun package-refresh-contents ()
1308 "Download the ELPA archive description if needed.
1309 This informs Emacs about the latest versions of all packages, and
1310 makes them available for download."
1311 (interactive)
1312 ;; FIXME: Do it asynchronously.
1313 (unless (file-exists-p package-user-dir)
1314 (make-directory package-user-dir t))
1315 (let ((default-keyring (expand-file-name "package-keyring.gpg"
1316 data-directory)))
1317 (if (file-exists-p default-keyring)
1318 (condition-case-unless-debug error
1319 (progn
1320 (epg-check-configuration (epg-configuration))
1321 (package-import-keyring default-keyring))
1322 (error (message "Cannot import default keyring: %S" (cdr error))))))
1323 (dolist (archive package-archives)
1324 (condition-case-unless-debug nil
1325 (package--download-one-archive archive "archive-contents")
1326 (error (message "Failed to download `%s' archive."
1327 (car archive)))))
1328 (package-read-all-archive-contents))
1329
1330 ;;;###autoload
1331 (defun package-initialize (&optional no-activate)
1332 "Load Emacs Lisp packages, and activate them.
1333 The variable `package-load-list' controls which packages to load.
1334 If optional arg NO-ACTIVATE is non-nil, don't activate packages."
1335 (interactive)
1336 (setq package-alist nil)
1337 (package-load-all-descriptors)
1338 (package-read-all-archive-contents)
1339 (unless no-activate
1340 (dolist (elt package-alist)
1341 (package-activate (car elt))))
1342 (setq package--initialized t))
1343
1344 \f
1345 ;;;; Package description buffer.
1346
1347 ;;;###autoload
1348 (defun describe-package (package)
1349 "Display the full documentation of PACKAGE (a symbol)."
1350 (interactive
1351 (let* ((guess (function-called-at-point)))
1352 (require 'finder-inf nil t)
1353 ;; Load the package list if necessary (but don't activate them).
1354 (unless package--initialized
1355 (package-initialize t))
1356 (let ((packages (append (mapcar 'car package-alist)
1357 (mapcar 'car package-archive-contents)
1358 (mapcar 'car package--builtins))))
1359 (unless (memq guess packages)
1360 (setq guess nil))
1361 (setq packages (mapcar 'symbol-name packages))
1362 (let ((val
1363 (completing-read (if guess
1364 (format "Describe package (default %s): "
1365 guess)
1366 "Describe package: ")
1367 packages nil t nil nil guess)))
1368 (list (intern val))))))
1369 (if (not (or (package-desc-p package) (and package (symbolp package))))
1370 (message "No package specified")
1371 (help-setup-xref (list #'describe-package package)
1372 (called-interactively-p 'interactive))
1373 (with-help-window (help-buffer)
1374 (with-current-buffer standard-output
1375 (describe-package-1 package)))))
1376
1377 (defun describe-package-1 (pkg)
1378 (require 'lisp-mnt)
1379 (let* ((desc (or
1380 (if (package-desc-p pkg) pkg)
1381 (cadr (assq pkg package-alist))
1382 (let ((built-in (assq pkg package--builtins)))
1383 (if built-in
1384 (package--from-builtin built-in)
1385 (cadr (assq pkg package-archive-contents))))))
1386 (name (if desc (package-desc-name desc) pkg))
1387 (pkg-dir (if desc (package-desc-dir desc)))
1388 (reqs (if desc (package-desc-reqs desc)))
1389 (version (if desc (package-desc-version desc)))
1390 (archive (if desc (package-desc-archive desc)))
1391 (extras (and desc (package-desc-extras desc)))
1392 (homepage (cdr (assoc :url extras)))
1393 (keywords (if desc (package-desc--keywords desc)))
1394 (built-in (eq pkg-dir 'builtin))
1395 (installable (and archive (not built-in)))
1396 (status (if desc (package-desc-status desc) "orphan"))
1397 (signed (if desc (package-desc-signed desc))))
1398 (prin1 name)
1399 (princ " is ")
1400 (princ (if (memq (aref status 0) '(?a ?e ?i ?o ?u)) "an " "a "))
1401 (princ status)
1402 (princ " package.\n\n")
1403
1404 (insert " " (propertize "Status" 'font-lock-face 'bold) ": ")
1405 (cond (built-in
1406 (insert (propertize (capitalize status)
1407 'font-lock-face 'font-lock-builtin-face)
1408 "."))
1409 (pkg-dir
1410 (insert (propertize (if (equal status "unsigned")
1411 "Installed"
1412 (capitalize status)) ;FIXME: Why comment-face?
1413 'font-lock-face 'font-lock-comment-face))
1414 (insert " in `")
1415 ;; Todo: Add button for uninstalling.
1416 (help-insert-xref-button (abbreviate-file-name
1417 (file-name-as-directory pkg-dir))
1418 'help-package-def pkg-dir)
1419 (if (and (package-built-in-p name)
1420 (not (package-built-in-p name version)))
1421 (insert "',\n shadowing a "
1422 (propertize "built-in package"
1423 'font-lock-face 'font-lock-builtin-face))
1424 (insert "'"))
1425 (if signed
1426 (insert ".")
1427 (insert " (unsigned).")))
1428 (installable
1429 (insert (capitalize status))
1430 (insert " from " (format "%s" archive))
1431 (insert " -- ")
1432 (package-make-button
1433 "Install"
1434 'action 'package-install-button-action
1435 'package-desc desc))
1436 (t (insert (capitalize status) ".")))
1437 (insert "\n")
1438 (insert " " (propertize "Archive" 'font-lock-face 'bold)
1439 ": " (or archive "n/a") "\n")
1440 (and version
1441 (insert " "
1442 (propertize "Version" 'font-lock-face 'bold) ": "
1443 (package-version-join version) "\n"))
1444
1445 (setq reqs (if desc (package-desc-reqs desc)))
1446 (when reqs
1447 (insert " " (propertize "Requires" 'font-lock-face 'bold) ": ")
1448 (let ((first t)
1449 name vers text)
1450 (dolist (req reqs)
1451 (setq name (car req)
1452 vers (cadr req)
1453 text (format "%s-%s" (symbol-name name)
1454 (package-version-join vers)))
1455 (cond (first (setq first nil))
1456 ((>= (+ 2 (current-column) (length text))
1457 (window-width))
1458 (insert ",\n "))
1459 (t (insert ", ")))
1460 (help-insert-xref-button text 'help-package name))
1461 (insert "\n")))
1462 (insert " " (propertize "Summary" 'font-lock-face 'bold)
1463 ": " (if desc (package-desc-summary desc)) "\n")
1464 (when homepage
1465 (insert " " (propertize "Homepage" 'font-lock-face 'bold) ": ")
1466 (help-insert-xref-button homepage 'help-url homepage)
1467 (insert "\n"))
1468 (when keywords
1469 (insert " " (propertize "Keywords" 'font-lock-face 'bold) ": ")
1470 (dolist (k keywords)
1471 (package-make-button
1472 k
1473 'package-keyword k
1474 'action 'package-keyword-button-action)
1475 (insert " "))
1476 (insert "\n"))
1477 (let* ((all-pkgs (append (cdr (assq name package-alist))
1478 (cdr (assq name package-archive-contents))
1479 (let ((bi (assq name package--builtins)))
1480 (if bi (list (package--from-builtin bi))))))
1481 (other-pkgs (delete desc all-pkgs)))
1482 (when other-pkgs
1483 (insert " " (propertize "Other versions" 'font-lock-face 'bold) ": "
1484 (mapconcat
1485 (lambda (opkg)
1486 (let* ((ov (package-desc-version opkg))
1487 (dir (package-desc-dir opkg))
1488 (from (or (package-desc-archive opkg)
1489 (if (stringp dir) "installed" dir))))
1490 (if (not ov) (format "%s" from)
1491 (format "%s (%s)"
1492 (make-text-button (package-version-join ov) nil
1493 'face 'link
1494 'follow-link t
1495 'action
1496 (lambda (_button)
1497 (describe-package opkg)))
1498 from))))
1499 other-pkgs ", ")
1500 ".\n")))
1501
1502 (insert "\n")
1503
1504 (if built-in
1505 ;; For built-in packages, insert the commentary.
1506 (let ((fn (locate-file (format "%s.el" name) load-path
1507 load-file-rep-suffixes))
1508 (opoint (point)))
1509 (insert (or (lm-commentary fn) ""))
1510 (save-excursion
1511 (goto-char opoint)
1512 (when (re-search-forward "^;;; Commentary:\n" nil t)
1513 (replace-match ""))
1514 (while (re-search-forward "^\\(;+ ?\\)" nil t)
1515 (replace-match ""))))
1516 (let ((readme (expand-file-name (format "%s-readme.txt" name)
1517 package-user-dir))
1518 readme-string)
1519 ;; For elpa packages, try downloading the commentary. If that
1520 ;; fails, try an existing readme file in `package-user-dir'.
1521 (cond ((condition-case nil
1522 (save-excursion
1523 (package--with-work-buffer
1524 (package-archive-base desc)
1525 (format "%s-readme.txt" name)
1526 (setq buffer-file-name
1527 (expand-file-name readme package-user-dir))
1528 (let ((version-control 'never)
1529 (require-final-newline t))
1530 (save-buffer))
1531 (setq readme-string (buffer-string))
1532 t))
1533 (error nil))
1534 (insert readme-string))
1535 ((file-readable-p readme)
1536 (insert-file-contents readme)
1537 (goto-char (point-max))))))))
1538
1539 (defun package-install-button-action (button)
1540 (let ((pkg-desc (button-get button 'package-desc)))
1541 (when (y-or-n-p (format "Install package `%s'? "
1542 (package-desc-full-name pkg-desc)))
1543 (package-install pkg-desc)
1544 (revert-buffer nil t)
1545 (goto-char (point-min)))))
1546
1547 (defun package-keyword-button-action (button)
1548 (let ((pkg-keyword (button-get button 'package-keyword)))
1549 (package-show-package-list t (list pkg-keyword))))
1550
1551 (defun package-make-button (text &rest props)
1552 (let ((button-text (if (display-graphic-p) text (concat "[" text "]")))
1553 (button-face (if (display-graphic-p)
1554 '(:box (:line-width 2 :color "dark grey")
1555 :background "light grey"
1556 :foreground "black")
1557 'link)))
1558 (apply 'insert-text-button button-text 'face button-face 'follow-link t
1559 props)))
1560
1561 \f
1562 ;;;; Package menu mode.
1563
1564 (defvar package-menu-mode-map
1565 (let ((map (make-sparse-keymap))
1566 (menu-map (make-sparse-keymap "Package")))
1567 (set-keymap-parent map tabulated-list-mode-map)
1568 (define-key map "\C-m" 'package-menu-describe-package)
1569 (define-key map "u" 'package-menu-mark-unmark)
1570 (define-key map "\177" 'package-menu-backup-unmark)
1571 (define-key map "d" 'package-menu-mark-delete)
1572 (define-key map "i" 'package-menu-mark-install)
1573 (define-key map "U" 'package-menu-mark-upgrades)
1574 (define-key map "r" 'package-menu-refresh)
1575 (define-key map "f" 'package-menu-filter)
1576 (define-key map "~" 'package-menu-mark-obsolete-for-deletion)
1577 (define-key map "x" 'package-menu-execute)
1578 (define-key map "h" 'package-menu-quick-help)
1579 (define-key map "?" 'package-menu-describe-package)
1580 (define-key map [menu-bar package-menu] (cons "Package" menu-map))
1581 (define-key menu-map [mq]
1582 '(menu-item "Quit" quit-window
1583 :help "Quit package selection"))
1584 (define-key menu-map [s1] '("--"))
1585 (define-key menu-map [mn]
1586 '(menu-item "Next" next-line
1587 :help "Next Line"))
1588 (define-key menu-map [mp]
1589 '(menu-item "Previous" previous-line
1590 :help "Previous Line"))
1591 (define-key menu-map [s2] '("--"))
1592 (define-key menu-map [mu]
1593 '(menu-item "Unmark" package-menu-mark-unmark
1594 :help "Clear any marks on a package and move to the next line"))
1595 (define-key menu-map [munm]
1596 '(menu-item "Unmark Backwards" package-menu-backup-unmark
1597 :help "Back up one line and clear any marks on that package"))
1598 (define-key menu-map [md]
1599 '(menu-item "Mark for Deletion" package-menu-mark-delete
1600 :help "Mark a package for deletion and move to the next line"))
1601 (define-key menu-map [mi]
1602 '(menu-item "Mark for Install" package-menu-mark-install
1603 :help "Mark a package for installation and move to the next line"))
1604 (define-key menu-map [mupgrades]
1605 '(menu-item "Mark Upgradable Packages" package-menu-mark-upgrades
1606 :help "Mark packages that have a newer version for upgrading"))
1607 (define-key menu-map [s3] '("--"))
1608 (define-key menu-map [mf]
1609 '(menu-item "Filter Package List..." package-menu-filter
1610 :help "Filter package selection (q to go back)"))
1611 (define-key menu-map [mg]
1612 '(menu-item "Update Package List" revert-buffer
1613 :help "Update the list of packages"))
1614 (define-key menu-map [mr]
1615 '(menu-item "Refresh Package List" package-menu-refresh
1616 :help "Download the ELPA archive"))
1617 (define-key menu-map [s4] '("--"))
1618 (define-key menu-map [mt]
1619 '(menu-item "Mark Obsolete Packages" package-menu-mark-obsolete-for-deletion
1620 :help "Mark all obsolete packages for deletion"))
1621 (define-key menu-map [mx]
1622 '(menu-item "Execute Actions" package-menu-execute
1623 :help "Perform all the marked actions"))
1624 (define-key menu-map [s5] '("--"))
1625 (define-key menu-map [mh]
1626 '(menu-item "Help" package-menu-quick-help
1627 :help "Show short key binding help for package-menu-mode"))
1628 (define-key menu-map [mc]
1629 '(menu-item "View Commentary" package-menu-view-commentary
1630 :help "Display information about this package"))
1631 map)
1632 "Local keymap for `package-menu-mode' buffers.")
1633
1634 (defvar package-menu--new-package-list nil
1635 "List of newly-available packages since `list-packages' was last called.")
1636
1637 (define-derived-mode package-menu-mode tabulated-list-mode "Package Menu"
1638 "Major mode for browsing a list of packages.
1639 Letters do not insert themselves; instead, they are commands.
1640 \\<package-menu-mode-map>
1641 \\{package-menu-mode-map}"
1642 (setq tabulated-list-format
1643 `[("Package" 18 package-menu--name-predicate)
1644 ("Version" 12 nil)
1645 ("Status" 10 package-menu--status-predicate)
1646 ,@(if (cdr package-archives)
1647 '(("Archive" 10 package-menu--archive-predicate)))
1648 ("Description" 0 nil)])
1649 (setq tabulated-list-padding 2)
1650 (setq tabulated-list-sort-key (cons "Status" nil))
1651 (add-hook 'tabulated-list-revert-hook 'package-menu--refresh nil t)
1652 (tabulated-list-init-header))
1653
1654 (defmacro package--push (pkg-desc status listname)
1655 "Convenience macro for `package-menu--generate'.
1656 If the alist stored in the symbol LISTNAME lacks an entry for a
1657 package PKG-DESC, add one. The alist is keyed with PKG-DESC."
1658 `(unless (assoc ,pkg-desc ,listname)
1659 ;; FIXME: Should we move status into pkg-desc?
1660 (push (cons ,pkg-desc ,status) ,listname)))
1661
1662 (defvar package-list-unversioned nil
1663 "If non-nil include packages that don't have a version in `list-package'.")
1664
1665 (defun package-desc-status (pkg-desc)
1666 (let* ((name (package-desc-name pkg-desc))
1667 (dir (package-desc-dir pkg-desc))
1668 (lle (assq name package-load-list))
1669 (held (cadr lle))
1670 (version (package-desc-version pkg-desc))
1671 (signed (package-desc-signed pkg-desc)))
1672 (cond
1673 ((eq dir 'builtin) "built-in")
1674 ((and lle (null held)) "disabled")
1675 ((stringp held)
1676 (let ((hv (if (stringp held) (version-to-list held))))
1677 (cond
1678 ((version-list-= version hv) "held")
1679 ((version-list-< version hv) "obsolete")
1680 (t "disabled"))))
1681 ((package-built-in-p name version) "obsolete")
1682 (dir ;One of the installed packages.
1683 (cond
1684 ((not (file-exists-p (package-desc-dir pkg-desc))) "deleted")
1685 ((eq pkg-desc (cadr (assq name package-alist))) (if signed
1686 "installed"
1687 "unsigned"))
1688 (t "obsolete")))
1689 (t
1690 (let* ((ins (cadr (assq name package-alist)))
1691 (ins-v (if ins (package-desc-version ins))))
1692 (cond
1693 ((or (null ins) (version-list-< ins-v version))
1694 (if (memq name package-menu--new-package-list)
1695 "new" "available"))
1696 ((version-list-< version ins-v) "obsolete")
1697 ((version-list-= version ins-v) (if signed
1698 "installed"
1699 "unsigned"))))))))
1700
1701 (defun package-menu--refresh (&optional packages keywords)
1702 "Re-populate the `tabulated-list-entries'.
1703 PACKAGES should be nil or t, which means to display all known packages.
1704 KEYWORDS should be nil or a list of keywords."
1705 ;; Construct list of (PKG-DESC . STATUS).
1706 (unless packages (setq packages t))
1707 (let (info-list name)
1708 ;; Installed packages:
1709 (dolist (elt package-alist)
1710 (setq name (car elt))
1711 (when (or (eq packages t) (memq name packages))
1712 (dolist (pkg (cdr elt))
1713 (when (package--has-keyword-p pkg keywords)
1714 (package--push pkg (package-desc-status pkg) info-list)))))
1715
1716 ;; Built-in packages:
1717 (dolist (elt package--builtins)
1718 (setq name (car elt))
1719 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
1720 (package--has-keyword-p (package--from-builtin elt) keywords)
1721 (or package-list-unversioned
1722 (package--bi-desc-version (cdr elt)))
1723 (or (eq packages t) (memq name packages)))
1724 (package--push (package--from-builtin elt) "built-in" info-list)))
1725
1726 ;; Available and disabled packages:
1727 (dolist (elt package-archive-contents)
1728 (setq name (car elt))
1729 (when (or (eq packages t) (memq name packages))
1730 (dolist (pkg (cdr elt))
1731 ;; Hide obsolete packages.
1732 (when (and (not (package-installed-p (package-desc-name pkg)
1733 (package-desc-version pkg)))
1734 (package--has-keyword-p pkg keywords))
1735 (package--push pkg (package-desc-status pkg) info-list)))))
1736
1737 ;; Print the result.
1738 (setq tabulated-list-entries
1739 (mapcar #'package-menu--print-info info-list))))
1740
1741 (defun package-all-keywords ()
1742 "Collect all package keywords"
1743 (let (keywords)
1744 (package--mapc (lambda (desc)
1745 (let* ((desc-keywords (and desc (package-desc--keywords desc))))
1746 (setq keywords (append keywords desc-keywords)))))
1747 keywords))
1748
1749 (defun package--mapc (function &optional packages)
1750 "Call FUNCTION for all known PACKAGES.
1751 PACKAGES can be nil or t, which means to display all known
1752 packages, or a list of packages.
1753
1754 Built-in packages are converted with `package--from-builtin'."
1755 (unless packages (setq packages t))
1756 (let (name)
1757 ;; Installed packages:
1758 (dolist (elt package-alist)
1759 (setq name (car elt))
1760 (when (or (eq packages t) (memq name packages))
1761 (mapc function (cdr elt))))
1762
1763 ;; Built-in packages:
1764 (dolist (elt package--builtins)
1765 (setq name (car elt))
1766 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
1767 (or package-list-unversioned
1768 (package--bi-desc-version (cdr elt)))
1769 (or (eq packages t) (memq name packages)))
1770 (funcall function (package--from-builtin elt))))
1771
1772 ;; Available and disabled packages:
1773 (dolist (elt package-archive-contents)
1774 (setq name (car elt))
1775 (when (or (eq packages t) (memq name packages))
1776 (dolist (pkg (cdr elt))
1777 ;; Hide obsolete packages.
1778 (unless (package-installed-p (package-desc-name pkg)
1779 (package-desc-version pkg))
1780 (funcall function pkg)))))))
1781
1782 (defun package--has-keyword-p (desc &optional keywords)
1783 "Test if package DESC has any of the given KEYWORDS.
1784 When none are given, the package matches."
1785 (if keywords
1786 (let* ((desc-keywords (and desc (package-desc--keywords desc)))
1787 found)
1788 (dolist (k keywords)
1789 (when (and (not found)
1790 (member k desc-keywords))
1791 (setq found t)))
1792 found)
1793 t))
1794
1795 (defun package-menu--generate (remember-pos packages &optional keywords)
1796 "Populate the Package Menu.
1797 If REMEMBER-POS is non-nil, keep point on the same entry.
1798 PACKAGES should be t, which means to display all known packages,
1799 or a list of package names (symbols) to display.
1800
1801 With KEYWORDS given, only packages with those keywords are
1802 shown."
1803 (package-menu--refresh packages keywords)
1804 (setf (car (aref tabulated-list-format 0))
1805 (if keywords
1806 (let ((filters (mapconcat 'identity keywords ",")))
1807 (concat "Package[" filters "]"))
1808 "Package"))
1809 (if keywords
1810 (define-key package-menu-mode-map "q" 'package-show-package-list)
1811 (define-key package-menu-mode-map "q" 'quit-window))
1812 (tabulated-list-init-header)
1813 (tabulated-list-print remember-pos))
1814
1815 (defun package-menu--print-info (pkg)
1816 "Return a package entry suitable for `tabulated-list-entries'.
1817 PKG has the form (PKG-DESC . STATUS).
1818 Return (PKG-DESC [NAME VERSION STATUS DOC])."
1819 (let* ((pkg-desc (car pkg))
1820 (status (cdr pkg))
1821 (face (pcase status
1822 (`"built-in" 'font-lock-builtin-face)
1823 (`"available" 'default)
1824 (`"new" 'bold)
1825 (`"held" 'font-lock-constant-face)
1826 (`"disabled" 'font-lock-warning-face)
1827 (`"installed" 'font-lock-comment-face)
1828 (`"unsigned" 'font-lock-warning-face)
1829 (_ 'font-lock-warning-face)))) ; obsolete.
1830 (list pkg-desc
1831 `[,(list (symbol-name (package-desc-name pkg-desc))
1832 'face 'link
1833 'follow-link t
1834 'package-desc pkg-desc
1835 'action 'package-menu-describe-package)
1836 ,(propertize (package-version-join
1837 (package-desc-version pkg-desc))
1838 'font-lock-face face)
1839 ,(propertize status 'font-lock-face face)
1840 ,@(if (cdr package-archives)
1841 (list (propertize (or (package-desc-archive pkg-desc) "")
1842 'font-lock-face face)))
1843 ,(propertize (package-desc-summary pkg-desc)
1844 'font-lock-face face)])))
1845
1846 (defun package-menu-refresh ()
1847 "Download the Emacs Lisp package archive.
1848 This fetches the contents of each archive specified in
1849 `package-archives', and then refreshes the package menu."
1850 (interactive)
1851 (unless (derived-mode-p 'package-menu-mode)
1852 (user-error "The current buffer is not a Package Menu"))
1853 (package-refresh-contents)
1854 (package-menu--generate t t))
1855
1856 (defun package-menu-describe-package (&optional button)
1857 "Describe the current package.
1858 If optional arg BUTTON is non-nil, describe its associated package."
1859 (interactive)
1860 (let ((pkg-desc (if button (button-get button 'package-desc)
1861 (tabulated-list-get-id))))
1862 (if pkg-desc
1863 (describe-package pkg-desc)
1864 (user-error "No package here"))))
1865
1866 ;; fixme numeric argument
1867 (defun package-menu-mark-delete (&optional _num)
1868 "Mark a package for deletion and move to the next line."
1869 (interactive "p")
1870 (if (member (package-menu-get-status) '("installed" "obsolete" "unsigned"))
1871 (tabulated-list-put-tag "D" t)
1872 (forward-line)))
1873
1874 (defun package-menu-mark-install (&optional _num)
1875 "Mark a package for installation and move to the next line."
1876 (interactive "p")
1877 (if (member (package-menu-get-status) '("available" "new"))
1878 (tabulated-list-put-tag "I" t)
1879 (forward-line)))
1880
1881 (defun package-menu-mark-unmark (&optional _num)
1882 "Clear any marks on a package and move to the next line."
1883 (interactive "p")
1884 (tabulated-list-put-tag " " t))
1885
1886 (defun package-menu-backup-unmark ()
1887 "Back up one line and clear any marks on that package."
1888 (interactive)
1889 (forward-line -1)
1890 (tabulated-list-put-tag " "))
1891
1892 (defun package-menu-mark-obsolete-for-deletion ()
1893 "Mark all obsolete packages for deletion."
1894 (interactive)
1895 (save-excursion
1896 (goto-char (point-min))
1897 (while (not (eobp))
1898 (if (equal (package-menu-get-status) "obsolete")
1899 (tabulated-list-put-tag "D" t)
1900 (forward-line 1)))))
1901
1902 (defun package-menu-quick-help ()
1903 "Show short key binding help for package-menu-mode."
1904 (interactive)
1905 (message "n-ext, i-nstall, d-elete, u-nmark, x-ecute, r-efresh, h-elp"))
1906
1907 (define-obsolete-function-alias
1908 'package-menu-view-commentary 'package-menu-describe-package "24.1")
1909
1910 (defun package-menu-get-status ()
1911 (let* ((id (tabulated-list-get-id))
1912 (entry (and id (assq id tabulated-list-entries))))
1913 (if entry
1914 (aref (cadr entry) 2)
1915 "")))
1916
1917 (defun package-menu--find-upgrades ()
1918 (let (installed available upgrades)
1919 ;; Build list of installed/available packages in this buffer.
1920 (dolist (entry tabulated-list-entries)
1921 ;; ENTRY is (PKG-DESC [NAME VERSION STATUS DOC])
1922 (let ((pkg-desc (car entry))
1923 (status (aref (cadr entry) 2)))
1924 (cond ((member status '("installed" "unsigned"))
1925 (push pkg-desc installed))
1926 ((member status '("available" "new"))
1927 (push (cons (package-desc-name pkg-desc) pkg-desc)
1928 available)))))
1929 ;; Loop through list of installed packages, finding upgrades.
1930 (dolist (pkg-desc installed)
1931 (let ((avail-pkg (assq (package-desc-name pkg-desc) available)))
1932 (and avail-pkg
1933 (version-list-< (package-desc-version pkg-desc)
1934 (package-desc-version (cdr avail-pkg)))
1935 (push avail-pkg upgrades))))
1936 upgrades))
1937
1938 (defun package-menu-mark-upgrades ()
1939 "Mark all upgradable packages in the Package Menu.
1940 For each installed package with a newer version available, place
1941 an (I)nstall flag on the available version and a (D)elete flag on
1942 the installed version. A subsequent \\[package-menu-execute]
1943 call will upgrade the package."
1944 (interactive)
1945 (unless (derived-mode-p 'package-menu-mode)
1946 (error "The current buffer is not a Package Menu"))
1947 (let ((upgrades (package-menu--find-upgrades)))
1948 (if (null upgrades)
1949 (message "No packages to upgrade.")
1950 (widen)
1951 (save-excursion
1952 (goto-char (point-min))
1953 (while (not (eobp))
1954 (let* ((pkg-desc (tabulated-list-get-id))
1955 (upgrade (cdr (assq (package-desc-name pkg-desc) upgrades))))
1956 (cond ((null upgrade)
1957 (forward-line 1))
1958 ((equal pkg-desc upgrade)
1959 (package-menu-mark-install))
1960 (t
1961 (package-menu-mark-delete))))))
1962 (message "%d package%s marked for upgrading."
1963 (length upgrades)
1964 (if (= (length upgrades) 1) "" "s")))))
1965
1966 (defun package-menu-execute (&optional noquery)
1967 "Perform marked Package Menu actions.
1968 Packages marked for installation are downloaded and installed;
1969 packages marked for deletion are removed.
1970 Optional argument NOQUERY non-nil means do not ask the user to confirm."
1971 (interactive)
1972 (unless (derived-mode-p 'package-menu-mode)
1973 (error "The current buffer is not in Package Menu mode"))
1974 (let (install-list delete-list cmd pkg-desc)
1975 (save-excursion
1976 (goto-char (point-min))
1977 (while (not (eobp))
1978 (setq cmd (char-after))
1979 (unless (eq cmd ?\s)
1980 ;; This is the key PKG-DESC.
1981 (setq pkg-desc (tabulated-list-get-id))
1982 (cond ((eq cmd ?D)
1983 (push pkg-desc delete-list))
1984 ((eq cmd ?I)
1985 (push pkg-desc install-list))))
1986 (forward-line)))
1987 (when install-list
1988 (if (or
1989 noquery
1990 (yes-or-no-p
1991 (if (= (length install-list) 1)
1992 (format "Install package `%s'? "
1993 (package-desc-full-name (car install-list)))
1994 (format "Install these %d packages (%s)? "
1995 (length install-list)
1996 (mapconcat #'package-desc-full-name
1997 install-list ", ")))))
1998 (mapc 'package-install install-list)))
1999 ;; Delete packages, prompting if necessary.
2000 (when delete-list
2001 (if (or
2002 noquery
2003 (yes-or-no-p
2004 (if (= (length delete-list) 1)
2005 (format "Delete package `%s'? "
2006 (package-desc-full-name (car delete-list)))
2007 (format "Delete these %d packages (%s)? "
2008 (length delete-list)
2009 (mapconcat #'package-desc-full-name
2010 delete-list ", ")))))
2011 (dolist (elt delete-list)
2012 (condition-case-unless-debug err
2013 (package-delete elt)
2014 (error (message (cadr err)))))
2015 (error "Aborted")))
2016 (if (or delete-list install-list)
2017 (package-menu--generate t t)
2018 (message "No operations specified."))))
2019
2020 (defun package-menu--version-predicate (A B)
2021 (let ((vA (or (aref (cadr A) 1) '(0)))
2022 (vB (or (aref (cadr B) 1) '(0))))
2023 (if (version-list-= vA vB)
2024 (package-menu--name-predicate A B)
2025 (version-list-< vA vB))))
2026
2027 (defun package-menu--status-predicate (A B)
2028 (let ((sA (aref (cadr A) 2))
2029 (sB (aref (cadr B) 2)))
2030 (cond ((string= sA sB)
2031 (package-menu--name-predicate A B))
2032 ((string= sA "new") t)
2033 ((string= sB "new") nil)
2034 ((string= sA "available") t)
2035 ((string= sB "available") nil)
2036 ((string= sA "installed") t)
2037 ((string= sB "installed") nil)
2038 ((string= sA "unsigned") t)
2039 ((string= sB "unsigned") nil)
2040 ((string= sA "held") t)
2041 ((string= sB "held") nil)
2042 ((string= sA "built-in") t)
2043 ((string= sB "built-in") nil)
2044 ((string= sA "obsolete") t)
2045 ((string= sB "obsolete") nil)
2046 (t (string< sA sB)))))
2047
2048 (defun package-menu--description-predicate (A B)
2049 (let ((dA (aref (cadr A) 3))
2050 (dB (aref (cadr B) 3)))
2051 (if (string= dA dB)
2052 (package-menu--name-predicate A B)
2053 (string< dA dB))))
2054
2055 (defun package-menu--name-predicate (A B)
2056 (string< (symbol-name (package-desc-name (car A)))
2057 (symbol-name (package-desc-name (car B)))))
2058
2059 (defun package-menu--archive-predicate (A B)
2060 (string< (or (package-desc-archive (car A)) "")
2061 (or (package-desc-archive (car B)) "")))
2062
2063 ;;;###autoload
2064 (defun list-packages (&optional no-fetch)
2065 "Display a list of packages.
2066 This first fetches the updated list of packages before
2067 displaying, unless a prefix argument NO-FETCH is specified.
2068 The list is displayed in a buffer named `*Packages*'."
2069 (interactive "P")
2070 (require 'finder-inf nil t)
2071 ;; Initialize the package system if necessary.
2072 (unless package--initialized
2073 (package-initialize t))
2074 (let (old-archives new-packages)
2075 (unless no-fetch
2076 ;; Read the locally-cached archive-contents.
2077 (package-read-all-archive-contents)
2078 (setq old-archives package-archive-contents)
2079 ;; Fetch the remote list of packages.
2080 (package-refresh-contents)
2081 ;; Find which packages are new.
2082 (dolist (elt package-archive-contents)
2083 (unless (assq (car elt) old-archives)
2084 (push (car elt) new-packages))))
2085
2086 ;; Generate the Package Menu.
2087 (let ((buf (get-buffer-create "*Packages*")))
2088 (with-current-buffer buf
2089 (package-menu-mode)
2090 (set (make-local-variable 'package-menu--new-package-list)
2091 new-packages)
2092 (package-menu--generate nil t))
2093 ;; The package menu buffer has keybindings. If the user types
2094 ;; `M-x list-packages', that suggests it should become current.
2095 (switch-to-buffer buf))
2096
2097 (let ((upgrades (package-menu--find-upgrades)))
2098 (if upgrades
2099 (message "%d package%s can be upgraded; type `%s' to mark %s for upgrading."
2100 (length upgrades)
2101 (if (= (length upgrades) 1) "" "s")
2102 (substitute-command-keys "\\[package-menu-mark-upgrades]")
2103 (if (= (length upgrades) 1) "it" "them"))))))
2104
2105 ;;;###autoload
2106 (defalias 'package-list-packages 'list-packages)
2107
2108 ;; Used in finder.el
2109 (defun package-show-package-list (&optional packages keywords)
2110 "Display PACKAGES in a *Packages* buffer.
2111 This is similar to `list-packages', but it does not fetch the
2112 updated list of packages, and it only displays packages with
2113 names in PACKAGES (which should be a list of symbols).
2114
2115 When KEYWORDS are given, only packages with those KEYWORDS are
2116 shown."
2117 (interactive)
2118 (require 'finder-inf nil t)
2119 (let ((buf (get-buffer-create "*Packages*")))
2120 (with-current-buffer buf
2121 (package-menu-mode)
2122 (package-menu--generate nil packages keywords))
2123 (switch-to-buffer buf)))
2124
2125 ;; package-menu--generate rebinds "q" on the fly, so we have to
2126 ;; hard-code the binding in the doc-string here.
2127 (defun package-menu-filter (keyword)
2128 "Filter the *Packages* buffer.
2129 Show only those items that relate to the specified KEYWORD.
2130 To restore the full package list, type `q'."
2131 (interactive (list (completing-read "Keyword: " (package-all-keywords))))
2132 (package-show-package-list t (list keyword)))
2133
2134 (defun package-list-packages-no-fetch ()
2135 "Display a list of packages.
2136 Does not fetch the updated list of packages before displaying.
2137 The list is displayed in a buffer named `*Packages*'."
2138 (interactive)
2139 (list-packages t))
2140
2141 (provide 'package)
2142
2143 ;;; package.el ends here