]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/package.el
* lisp/emacs-lisp/package.el: Small improvements
[gnu-emacs] / lisp / emacs-lisp / package.el
1 ;;; package.el --- Simple package system for Emacs -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2007-2015 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 ;; - putting info dirs at the start of the info path means
117 ;; users see a weird ordering of categories. OTOH we want to
118 ;; override later entries. maybe emacs needs to enforce
119 ;; the standard layout?
120 ;; - put bytecode in a separate directory tree
121 ;; - perhaps give users a way to recompile their bytecode
122 ;; or do it automatically when emacs changes
123 ;; - give users a way to know whether a package is installed ok
124 ;; - give users a way to view a package's documentation when it
125 ;; only appears in the .el
126 ;; - use/extend checkdoc so people can tell if their package will work
127 ;; - "installed" instead of a blank in the status column
128 ;; - tramp needs its files to be compiled in a certain order.
129 ;; how to handle this? fix tramp?
130 ;; - on emacs 21 we don't kill the -autoloads.el buffer. what about 22?
131 ;; - maybe we need separate .elc directories for various emacs versions
132 ;; and also emacs-vs-xemacs. That way conditional compilation can
133 ;; work. But would this break anything?
134 ;; - should store the package's keywords in archive-contents, then
135 ;; let the users filter the package-menu by keyword. See
136 ;; finder-by-keyword. (We could also let people view the
137 ;; Commentary, but it isn't clear how useful this is.)
138 ;; - William Xu suggests being able to open a package file without
139 ;; installing it
140 ;; - Interface with desktop.el so that restarting after an install
141 ;; works properly
142 ;; - Use hierarchical layout. PKG/etc PKG/lisp PKG/info
143 ;; ... except maybe lisp?
144 ;; - It may be nice to have a macro that expands to the package's
145 ;; private data dir, aka ".../etc". Or, maybe data-directory
146 ;; needs to be a list (though this would be less nice)
147 ;; a few packages want this, eg sokoban
148 ;; - package menu needs:
149 ;; ability to know which packages are built-in & thus not deletable
150 ;; it can sometimes print odd results, like 0.3 available but 0.4 active
151 ;; why is that?
152 ;; - Allow multiple versions on the server...?
153 ;; [ why bother? ]
154 ;; - Don't install a package which will invalidate dependencies overall
155 ;; - Allow something like (or (>= emacs 21.0) (>= xemacs 21.5))
156 ;; [ currently thinking, why bother.. KISS ]
157 ;; - Allow optional package dependencies
158 ;; then if we require 'bbdb', bbdb-specific lisp in lisp/bbdb
159 ;; and just don't compile to add to load path ...?
160 ;; - Our treatment of the info path is somewhat bogus
161
162 ;;; Code:
163
164 (eval-when-compile (require 'subr-x))
165 (eval-when-compile (require 'cl-lib))
166 (eval-when-compile (require 'epg)) ;For setf accessors.
167
168 (require 'tabulated-list)
169 (require 'macroexp)
170
171 (defgroup package nil
172 "Manager for Emacs Lisp packages."
173 :group 'applications
174 :version "24.1")
175
176 \f
177 ;;; Customization options
178 ;;;###autoload
179 (defcustom package-enable-at-startup t
180 "Whether to activate installed packages when Emacs starts.
181 If non-nil, packages are activated after reading the init file
182 and before `after-init-hook'. Activation is not done if
183 `user-init-file' is nil (e.g. Emacs was started with \"-q\").
184
185 Even if the value is nil, you can type \\[package-initialize] to
186 activate the package system at any time."
187 :type 'boolean
188 :version "24.1")
189
190 (defcustom package-load-list '(all)
191 "List of packages for `package-initialize' to load.
192 Each element in this list should be a list (NAME VERSION), or the
193 symbol `all'. The symbol `all' says to load the latest installed
194 versions of all packages not specified by other elements.
195
196 For an element (NAME VERSION), NAME is a package name (a symbol).
197 VERSION should be t, a string, or nil.
198 If VERSION is t, the most recent version is activated.
199 If VERSION is a string, only that version is ever loaded.
200 Any other version, even if newer, is silently ignored.
201 Hence, the package is \"held\" at that version.
202 If VERSION is nil, the package is not loaded (it is \"disabled\")."
203 :type '(repeat symbol)
204 :risky t
205 :version "24.1")
206
207 (defcustom package-archives '(("gnu" . "http://elpa.gnu.org/packages/"))
208 "An alist of archives from which to fetch.
209 The default value points to the GNU Emacs package repository.
210
211 Each element has the form (ID . LOCATION).
212 ID is an archive name, as a string.
213 LOCATION specifies the base location for the archive.
214 If it starts with \"http:\", it is treated as a HTTP URL;
215 otherwise it should be an absolute directory name.
216 (Other types of URL are currently not supported.)
217
218 Only add locations that you trust, since fetching and installing
219 a package can run arbitrary code."
220 :type '(alist :key-type (string :tag "Archive name")
221 :value-type (string :tag "URL or directory name"))
222 :risky t
223 :version "24.1")
224
225 (defcustom package-menu-hide-low-priority 'archive
226 "If non-nil, hide low priority packages from the packages menu.
227 A package is considered low priority if there's another version
228 of it available such that:
229 (a) the archive of the other package is higher priority than
230 this one, as per `package-archive-priorities';
231 or
232 (b) they both have the same archive priority but the other
233 package has a higher version number.
234
235 This variable has three possible values:
236 nil: no packages are hidden;
237 archive: only criteria (a) is used;
238 t: both criteria are used.
239
240 This variable has no effect if `package-menu--hide-obsolete' is
241 nil, so it can be toggled with \\<package-menu-mode-map> \\[package-menu-hide-obsolete]."
242 :type '(choice (const :tag "Don't hide anything" nil)
243 (const :tag "Hide per package-archive-priorities"
244 archive)
245 (const :tag "Hide per archive and version number" t))
246 :version "25.1")
247
248 (defcustom package-archive-priorities nil
249 "An alist of priorities for packages.
250
251 Each element has the form (ARCHIVE-ID . PRIORITY).
252
253 When installing packages, the package with the highest version
254 number from the archive with the highest priority is
255 selected. When higher versions are available from archives with
256 lower priorities, the user has to select those manually.
257
258 Archives not in this list have the priority 0.
259
260 See also `package-menu-hide-low-priority'."
261 :type '(alist :key-type (string :tag "Archive name")
262 :value-type (integer :tag "Priority (default is 0)"))
263 :risky t
264 :version "25.1")
265
266 (defcustom package-pinned-packages nil
267 "An alist of packages that are pinned to specific archives.
268 This can be useful if you have multiple package archives enabled,
269 and want to control which archive a given package gets installed from.
270
271 Each element of the alist has the form (PACKAGE . ARCHIVE), where:
272 PACKAGE is a symbol representing a package
273 ARCHIVE is a string representing an archive (it should be the car of
274 an element in `package-archives', e.g. \"gnu\").
275
276 Adding an entry to this variable means that only ARCHIVE will be
277 considered as a source for PACKAGE. If other archives provide PACKAGE,
278 they are ignored (for this package). If ARCHIVE does not contain PACKAGE,
279 the package will be unavailable."
280 :type '(alist :key-type (symbol :tag "Package")
281 :value-type (string :tag "Archive name"))
282 ;; I don't really see why this is risky...
283 ;; I suppose it could prevent you receiving updates for a package,
284 ;; via an entry (PACKAGE . NON-EXISTING). Which could be an issue
285 ;; if PACKAGE has a known vulnerability that is fixed in newer versions.
286 :risky t
287 :version "24.4")
288
289 (defcustom package-user-dir (locate-user-emacs-file "elpa")
290 "Directory containing the user's Emacs Lisp packages.
291 The directory name should be absolute.
292 Apart from this directory, Emacs also looks for system-wide
293 packages in `package-directory-list'."
294 :type 'directory
295 :risky t
296 :version "24.1")
297
298 (defcustom package-directory-list
299 ;; Defaults are subdirs named "elpa" in the site-lisp dirs.
300 (let (result)
301 (dolist (f load-path)
302 (and (stringp f)
303 (equal (file-name-nondirectory f) "site-lisp")
304 (push (expand-file-name "elpa" f) result)))
305 (nreverse result))
306 "List of additional directories containing Emacs Lisp packages.
307 Each directory name should be absolute.
308
309 These directories contain packages intended for system-wide; in
310 contrast, `package-user-dir' contains packages for personal use."
311 :type '(repeat directory)
312 :risky t
313 :version "24.1")
314
315 (defvar epg-gpg-program)
316
317 (defcustom package-check-signature
318 (if (progn (require 'epg-config) (executable-find epg-gpg-program))
319 'allow-unsigned)
320 "Non-nil means to check package signatures when installing.
321 The value `allow-unsigned' means to still install a package even if
322 it is unsigned.
323
324 This also applies to the \"archive-contents\" file that lists the
325 contents of the archive."
326 :type '(choice (const nil :tag "Never")
327 (const allow-unsigned :tag "Allow unsigned")
328 (const t :tag "Check always"))
329 :risky t
330 :version "24.4")
331
332 (defcustom package-unsigned-archives nil
333 "List of archives where we do not check for package signatures."
334 :type '(repeat (string :tag "Archive name"))
335 :risky t
336 :version "24.4")
337
338 (defcustom package-selected-packages nil
339 "Store here packages installed explicitly by user.
340 This variable is fed automatically by Emacs when installing a new package.
341 This variable is used by `package-autoremove' to decide
342 which packages are no longer needed.
343 You can use it to (re)install packages on other machines
344 by running `package-user-selected-packages-install'.
345
346 To check if a package is contained in this list here, use
347 `package--user-selected-p', as it may populate the variable with
348 a sane initial value."
349 :type '(repeat symbol))
350
351 (defcustom package-menu-async t
352 "If non-nil, package-menu will use async operations when possible.
353 This includes refreshing archive contents as well as installing
354 packages."
355 :type 'boolean
356 :version "25.1")
357
358 \f
359 ;;; `package-desc' object definition
360 ;; This is the struct used internally to represent packages.
361 ;; Functions that deal with packages should generally take this object
362 ;; as an argument. In some situations (e.g. commands that query the
363 ;; user) it makes sense to take the package name as a symbol instead,
364 ;; but keep in mind there could be multiple `package-desc's with the
365 ;; same name.
366 (defvar package--default-summary "No description available.")
367
368 (cl-defstruct (package-desc
369 ;; Rename the default constructor from `make-package-desc'.
370 (:constructor package-desc-create)
371 ;; Has the same interface as the old `define-package',
372 ;; which is still used in the "foo-pkg.el" files. Extra
373 ;; options can be supported by adding additional keys.
374 (:constructor
375 package-desc-from-define
376 (name-string version-string &optional summary requirements
377 &rest rest-plist
378 &aux
379 (name (intern name-string))
380 (version (version-to-list version-string))
381 (reqs (mapcar #'(lambda (elt)
382 (list (car elt)
383 (version-to-list (cadr elt))))
384 (if (eq 'quote (car requirements))
385 (nth 1 requirements)
386 requirements)))
387 (kind (plist-get rest-plist :kind))
388 (archive (plist-get rest-plist :archive))
389 (extras (let (alist)
390 (while rest-plist
391 (unless (memq (car rest-plist) '(:kind :archive))
392 (let ((value (cadr rest-plist)))
393 (when value
394 (push (cons (car rest-plist)
395 (if (eq (car-safe value) 'quote)
396 (cadr value)
397 value))
398 alist))))
399 (setq rest-plist (cddr rest-plist)))
400 alist)))))
401 "Structure containing information about an individual package.
402 Slots:
403
404 `name' Name of the package, as a symbol.
405
406 `version' Version of the package, as a version list.
407
408 `summary' Short description of the package, typically taken from
409 the first line of the file.
410
411 `reqs' Requirements of the package. A list of (PACKAGE
412 VERSION-LIST) naming the dependent package and the minimum
413 required version.
414
415 `kind' The distribution format of the package. Currently, it is
416 either `single' or `tar'.
417
418 `archive' The name of the archive (as a string) whence this
419 package came.
420
421 `dir' The directory where the package is installed (if installed),
422 `builtin' if it is built-in, or nil otherwise.
423
424 `extras' Optional alist of additional keyword-value pairs.
425
426 `signed' Flag to indicate that the package is signed by provider."
427 name
428 version
429 (summary package--default-summary)
430 reqs
431 kind
432 archive
433 dir
434 extras
435 signed)
436
437 (defun package--from-builtin (bi-desc)
438 (package-desc-create :name (pop bi-desc)
439 :version (package--bi-desc-version bi-desc)
440 :summary (package--bi-desc-summary bi-desc)
441 :dir 'builtin))
442
443 ;; Pseudo fields.
444 (defun package-version-join (vlist)
445 "Return the version string corresponding to the list VLIST.
446 This is, approximately, the inverse of `version-to-list'.
447 \(Actually, it returns only one of the possible inverses, since
448 `version-to-list' is a many-to-one operation.)"
449 (if (null vlist)
450 ""
451 (let ((str-list (list "." (int-to-string (car vlist)))))
452 (dolist (num (cdr vlist))
453 (cond
454 ((>= num 0)
455 (push (int-to-string num) str-list)
456 (push "." str-list))
457 ((< num -4)
458 (error "Invalid version list `%s'" vlist))
459 (t
460 ;; pre, or beta, or alpha
461 (cond ((equal "." (car str-list))
462 (pop str-list))
463 ((not (string-match "[0-9]+" (car str-list)))
464 (error "Invalid version list `%s'" vlist)))
465 (push (cond ((= num -1) "pre")
466 ((= num -2) "beta")
467 ((= num -3) "alpha")
468 ((= num -4) "snapshot"))
469 str-list))))
470 (if (equal "." (car str-list))
471 (pop str-list))
472 (apply 'concat (nreverse str-list)))))
473
474 (defun package-desc-full-name (pkg-desc)
475 (format "%s-%s"
476 (package-desc-name pkg-desc)
477 (package-version-join (package-desc-version pkg-desc))))
478
479 (defun package-desc-suffix (pkg-desc)
480 (pcase (package-desc-kind pkg-desc)
481 (`single ".el")
482 (`tar ".tar")
483 (`dir "")
484 (kind (error "Unknown package kind: %s" kind))))
485
486 (defun package-desc--keywords (pkg-desc)
487 (let ((keywords (cdr (assoc :keywords (package-desc-extras pkg-desc)))))
488 (if (eq (car-safe keywords) 'quote)
489 (nth 1 keywords)
490 keywords)))
491
492 (defun package-desc-priority (p)
493 "Return the priority of the archive of package-desc object P."
494 (package-archive-priority (package-desc-archive p)))
495
496 ;; Package descriptor format used in finder-inf.el and package--builtins.
497 (cl-defstruct (package--bi-desc
498 (:constructor package-make-builtin (version summary))
499 (:type vector))
500 version
501 reqs
502 summary)
503
504 \f
505 ;;; Installed packages
506 ;; The following variables store information about packages present in
507 ;; the system. The most important of these is `package-alist'. The
508 ;; command `package-initialize' is also closely related to this
509 ;; section, but it is left for a later section because it also affects
510 ;; other stuff.
511 (defvar package--builtins nil
512 "Alist of built-in packages.
513 The actual value is initialized by loading the library
514 `finder-inf'; this is not done until it is needed, e.g. by the
515 function `package-built-in-p'.
516
517 Each element has the form (PKG . PACKAGE-BI-DESC), where PKG is a package
518 name (a symbol) and DESC is a `package--bi-desc' structure.")
519 (put 'package--builtins 'risky-local-variable t)
520
521 (defvar package-alist nil
522 "Alist of all packages available for activation.
523 Each element has the form (PKG . DESCS), where PKG is a package
524 name (a symbol) and DESCS is a non-empty list of `package-desc' structure,
525 sorted by decreasing versions.
526
527 This variable is set automatically by `package-load-descriptor',
528 called via `package-initialize'. To change which packages are
529 loaded and/or activated, customize `package-load-list'.")
530 (put 'package-alist 'risky-local-variable t)
531
532 (defvar package-activated-list nil
533 ;; FIXME: This should implicitly include all builtin packages.
534 "List of the names of currently activated packages.")
535 (put 'package-activated-list 'risky-local-variable t)
536
537 ;;;; Populating `package-alist'.
538 ;; The following functions are called on each installed package by
539 ;; `package-load-all-descriptors', which ultimately populates the
540 ;; `package-alist' variable.
541 (defun package-process-define-package (exp)
542 (when (eq (car-safe exp) 'define-package)
543 (let* ((new-pkg-desc (apply #'package-desc-from-define (cdr exp)))
544 (name (package-desc-name new-pkg-desc))
545 (version (package-desc-version new-pkg-desc))
546 (old-pkgs (assq name package-alist)))
547 (if (null old-pkgs)
548 ;; If there's no old package, just add this to `package-alist'.
549 (push (list name new-pkg-desc) package-alist)
550 ;; If there is, insert the new package at the right place in the list.
551 (while
552 (if (and (cdr old-pkgs)
553 (version-list-< version
554 (package-desc-version (cadr old-pkgs))))
555 (setq old-pkgs (cdr old-pkgs))
556 (push new-pkg-desc (cdr old-pkgs))
557 nil)))
558 new-pkg-desc)))
559
560 (defun package-load-descriptor (pkg-dir)
561 "Load the description file in directory PKG-DIR."
562 (let ((pkg-file (expand-file-name (package--description-file pkg-dir)
563 pkg-dir))
564 (signed-file (concat pkg-dir ".signed")))
565 (when (file-exists-p pkg-file)
566 (with-temp-buffer
567 (insert-file-contents pkg-file)
568 (goto-char (point-min))
569 (let ((pkg-desc (or (package-process-define-package
570 (read (current-buffer)))
571 (error "Can't find define-package in %s" pkg-file))))
572 (setf (package-desc-dir pkg-desc) pkg-dir)
573 (if (file-exists-p signed-file)
574 (setf (package-desc-signed pkg-desc) t))
575 pkg-desc)))))
576
577 (defun package-load-all-descriptors ()
578 "Load descriptors for installed Emacs Lisp packages.
579 This looks for package subdirectories in `package-user-dir' and
580 `package-directory-list'. The variable `package-load-list'
581 controls which package subdirectories may be loaded.
582
583 In each valid package subdirectory, this function loads the
584 description file containing a call to `define-package', which
585 updates `package-alist'."
586 (dolist (dir (cons package-user-dir package-directory-list))
587 (when (file-directory-p dir)
588 (dolist (subdir (directory-files dir))
589 (let ((pkg-dir (expand-file-name subdir dir)))
590 (when (file-directory-p pkg-dir)
591 (package-load-descriptor pkg-dir)))))))
592
593 (defun define-package (_name-string _version-string
594 &optional _docstring _requirements
595 &rest _extra-properties)
596 "Define a new package.
597 NAME-STRING is the name of the package, as a string.
598 VERSION-STRING is the version of the package, as a string.
599 DOCSTRING is a short description of the package, a string.
600 REQUIREMENTS is a list of dependencies on other packages.
601 Each requirement is of the form (OTHER-PACKAGE OTHER-VERSION),
602 where OTHER-VERSION is a string.
603
604 EXTRA-PROPERTIES is currently unused."
605 ;; FIXME: Placeholder! Should we keep it?
606 (error "Don't call me!"))
607
608 \f
609 ;;; Package activation
610 ;; Section for functions used by `package-activate', which see.
611 (defun package-disabled-p (pkg-name version)
612 "Return whether PKG-NAME at VERSION can be activated.
613 The decision is made according to `package-load-list'.
614 Return nil if the package can be activated.
615 Return t if the package is completely disabled.
616 Return the max version (as a string) if the package is held at a lower version."
617 (let ((force (assq pkg-name package-load-list)))
618 (cond ((null force) (not (memq 'all package-load-list)))
619 ((null (setq force (cadr force))) t) ; disabled
620 ((eq force t) nil)
621 ((stringp force) ; held
622 (unless (version-list-= version (version-to-list force))
623 force))
624 (t (error "Invalid element in `package-load-list'")))))
625
626 (defun package-built-in-p (package &optional min-version)
627 "Return true if PACKAGE is built-in to Emacs.
628 Optional arg MIN-VERSION, if non-nil, should be a version list
629 specifying the minimum acceptable version."
630 (if (package-desc-p package) ;; was built-in and then was converted
631 (eq 'builtin (package-desc-dir package))
632 (let ((bi (assq package package--builtin-versions)))
633 (cond
634 (bi (version-list-<= min-version (cdr bi)))
635 ((remove 0 min-version) nil)
636 (t
637 (require 'finder-inf nil t) ; For `package--builtins'.
638 (assq package package--builtins))))))
639
640 (defvar Info-directory-list)
641 (declare-function info-initialize "info" ())
642
643 (defun package-activate-1 (pkg-desc &optional reload)
644 "Activate package given by PKG-DESC, even if it was already active.
645 If RELOAD is non-nil, also `load' any files inside the package which
646 correspond to previously loaded files (those returned by
647 `package--list-loaded-files')."
648 (let* ((name (package-desc-name pkg-desc))
649 (pkg-dir (package-desc-dir pkg-desc))
650 (pkg-dir-dir (file-name-as-directory pkg-dir)))
651 (unless pkg-dir
652 (error "Internal error: unable to find directory for `%s'"
653 (package-desc-full-name pkg-desc)))
654 ;; Add to load path, add autoloads, and activate the package.
655 (let* ((old-lp load-path)
656 (autoloads-file (expand-file-name
657 (format "%s-autoloads" name) pkg-dir))
658 (loaded-files-list (and reload (package--list-loaded-files pkg-dir))))
659 (with-demoted-errors "Error in package-activate-1: %s"
660 (load autoloads-file nil t))
661 (when (and (eq old-lp load-path)
662 (not (or (member pkg-dir load-path)
663 (member pkg-dir-dir load-path))))
664 ;; Old packages don't add themselves to the `load-path', so we have to
665 ;; do it ourselves.
666 (push pkg-dir load-path))
667 ;; Call `load' on all files in `pkg-dir' already present in
668 ;; `load-history'. This is done so that macros in these files are updated
669 ;; to their new definitions. If another package is being installed which
670 ;; depends on this new definition, not doing this update would cause
671 ;; compilation errors and break the installation.
672 (with-demoted-errors "Error in package-activate-1: %s"
673 (mapc (lambda (feature) (load feature nil t))
674 ;; Skip autoloads file since we already evaluated it above.
675 (remove (file-truename autoloads-file) loaded-files-list))))
676 ;; Add info node.
677 (when (file-exists-p (expand-file-name "dir" pkg-dir))
678 ;; FIXME: not the friendliest, but simple.
679 (require 'info)
680 (info-initialize)
681 (push pkg-dir Info-directory-list))
682 (push name package-activated-list)
683 ;; Don't return nil.
684 t))
685
686 (declare-function find-library-name "find-func" (library))
687
688 (defun package--list-loaded-files (dir)
689 "Recursively list all files in DIR which correspond to loaded features.
690 Returns the `file-name-sans-extension' of each file, relative to
691 DIR, sorted by most recently loaded last."
692 (let* ((history (delq nil
693 (mapcar (lambda (x)
694 (let ((f (car x)))
695 (and f (file-name-sans-extension f))))
696 load-history)))
697 (dir (file-truename dir))
698 ;; List all files that have already been loaded.
699 (list-of-conflicts
700 (delq
701 nil
702 (mapcar
703 (lambda (x) (let* ((file (file-relative-name x dir))
704 ;; Previously loaded file, if any.
705 (previous
706 (ignore-errors
707 (file-name-sans-extension
708 (file-truename (find-library-name file)))))
709 (pos (when previous (member previous history))))
710 ;; Return (RELATIVE-FILENAME . HISTORY-POSITION)
711 (when pos
712 (cons (file-name-sans-extension file) (length pos)))))
713 (directory-files-recursively dir "\\`[^\\.].*\\.el\\'")))))
714 ;; Turn the list of (FILENAME . POS) back into a list of features. Files in
715 ;; subdirectories are returned relative to DIR (so not actually features).
716 (let ((default-directory (file-name-as-directory dir)))
717 (mapcar (lambda (x) (file-truename (car x)))
718 (sort list-of-conflicts
719 ;; Sort the files by ascending HISTORY-POSITION.
720 (lambda (x y) (< (cdr x) (cdr y))))))))
721
722 ;;;; `package-activate'
723 ;; This function activates a newer version of a package if an older
724 ;; one was already activated. It also loads a features of this
725 ;; package which were already loaded.
726 (defun package-activate (package &optional force)
727 "Activate package PACKAGE.
728 If FORCE is true, (re-)activate it if it's already activated.
729 Newer versions are always activated, regardless of FORCE."
730 (let ((pkg-descs (cdr (assq package package-alist))))
731 ;; Check if PACKAGE is available in `package-alist'.
732 (while
733 (when pkg-descs
734 (let ((available-version (package-desc-version (car pkg-descs))))
735 (or (package-disabled-p package available-version)
736 ;; Prefer a builtin package.
737 (package-built-in-p package available-version))))
738 (setq pkg-descs (cdr pkg-descs)))
739 (cond
740 ;; If no such package is found, maybe it's built-in.
741 ((null pkg-descs)
742 (package-built-in-p package))
743 ;; If the package is already activated, just return t.
744 ((and (memq package package-activated-list) (not force))
745 t)
746 ;; Otherwise, proceed with activation.
747 (t
748 (let* ((pkg-vec (car pkg-descs))
749 (fail (catch 'dep-failure
750 ;; Activate its dependencies recursively.
751 (dolist (req (package-desc-reqs pkg-vec))
752 (unless (package-activate (car req))
753 (throw 'dep-failure req))))))
754 (if fail
755 (warn "Unable to activate package `%s'.
756 Required package `%s-%s' is unavailable"
757 package (car fail) (package-version-join (cadr fail)))
758 ;; If all goes well, activate the package itself.
759 (package-activate-1 pkg-vec force)))))))
760
761 \f
762 ;;; Installation -- Local operations
763 ;; This section contains a variety of features regarding installing a
764 ;; package to/from disk. This includes autoload generation,
765 ;; unpacking, compiling, as well as defining a package from the
766 ;; current buffer.
767
768 ;;;; Unpacking
769 (defvar tar-parse-info)
770 (declare-function tar-untar-buffer "tar-mode" ())
771 (declare-function tar-header-name "tar-mode" (tar-header) t)
772 (declare-function tar-header-link-type "tar-mode" (tar-header) t)
773
774 (defun package-untar-buffer (dir)
775 "Untar the current buffer.
776 This uses `tar-untar-buffer' from Tar mode. All files should
777 untar into a directory named DIR; otherwise, signal an error."
778 (require 'tar-mode)
779 (tar-mode)
780 ;; Make sure everything extracts into DIR.
781 (let ((regexp (concat "\\`" (regexp-quote (expand-file-name dir)) "/"))
782 (case-fold-search (memq system-type '(windows-nt ms-dos cygwin))))
783 (dolist (tar-data tar-parse-info)
784 (let ((name (expand-file-name (tar-header-name tar-data))))
785 (or (string-match regexp name)
786 ;; Tarballs created by some utilities don't list
787 ;; directories with a trailing slash (Bug#13136).
788 (and (string-equal dir name)
789 (eq (tar-header-link-type tar-data) 5))
790 (error "Package does not untar cleanly into directory %s/" dir)))))
791 (tar-untar-buffer))
792
793 (defun package--alist-to-plist-args (alist)
794 (mapcar 'macroexp-quote
795 (apply #'nconc
796 (mapcar (lambda (pair) (list (car pair) (cdr pair))) alist))))
797 (defun package-unpack (pkg-desc)
798 "Install the contents of the current buffer as a package."
799 (let* ((name (package-desc-name pkg-desc))
800 (dirname (package-desc-full-name pkg-desc))
801 (pkg-dir (expand-file-name dirname package-user-dir)))
802 (pcase (package-desc-kind pkg-desc)
803 (`dir
804 (make-directory pkg-dir t)
805 (let ((file-list
806 (directory-files
807 default-directory 'full "\\`[^.].*\\.el\\'" 'nosort)))
808 (dolist (source-file file-list)
809 (let ((target-el-file
810 (expand-file-name (file-name-nondirectory source-file) pkg-dir)))
811 (copy-file source-file target-el-file t)))
812 ;; Now that the files have been installed, this package is
813 ;; indistinguishable from a `tar' or a `single'. Let's make
814 ;; things simple by ensuring we're one of them.
815 (setf (package-desc-kind pkg-desc)
816 (if (> (length file-list) 1) 'tar 'single))))
817 (`tar
818 (make-directory package-user-dir t)
819 ;; FIXME: should we delete PKG-DIR if it exists?
820 (let* ((default-directory (file-name-as-directory package-user-dir)))
821 (package-untar-buffer dirname)))
822 (`single
823 (let ((el-file (expand-file-name (format "%s.el" name) pkg-dir)))
824 (make-directory pkg-dir t)
825 (package--write-file-no-coding el-file)))
826 (kind (error "Unknown package kind: %S" kind)))
827 (package--make-autoloads-and-stuff pkg-desc pkg-dir)
828 ;; Update package-alist.
829 (let ((new-desc (package-load-descriptor pkg-dir)))
830 ;; FIXME: Check that `new-desc' matches `desc'!
831 ;; FIXME: Compilation should be done as a separate, optional, step.
832 ;; E.g. for multi-package installs, we should first install all packages
833 ;; and then compile them.
834 (package--compile new-desc))
835 ;; Try to activate it.
836 (package-activate name 'force)
837 pkg-dir))
838
839 (defun package-generate-description-file (pkg-desc pkg-file)
840 "Create the foo-pkg.el file for single-file packages."
841 (let* ((name (package-desc-name pkg-desc)))
842 (let ((print-level nil)
843 (print-quoted t)
844 (print-length nil))
845 (write-region
846 (concat
847 ";;; -*- no-byte-compile: t -*-\n"
848 (prin1-to-string
849 (nconc
850 (list 'define-package
851 (symbol-name name)
852 (package-version-join (package-desc-version pkg-desc))
853 (package-desc-summary pkg-desc)
854 (let ((requires (package-desc-reqs pkg-desc)))
855 (list 'quote
856 ;; Turn version lists into string form.
857 (mapcar
858 (lambda (elt)
859 (list (car elt)
860 (package-version-join (cadr elt))))
861 requires))))
862 (package--alist-to-plist-args
863 (package-desc-extras pkg-desc))))
864 "\n")
865 nil pkg-file nil 'silent))))
866
867 ;;;; Autoload
868 ;; From Emacs 22, but changed so it adds to load-path.
869 (defun package-autoload-ensure-default-file (file)
870 "Make sure that the autoload file FILE exists and if not create it."
871 (unless (file-exists-p file)
872 (write-region
873 (concat ";;; " (file-name-nondirectory file)
874 " --- automatically extracted autoloads\n"
875 ";;\n"
876 ";;; Code:\n"
877 "(add-to-list 'load-path (or (file-name-directory #$) (car load-path)))\n"
878 "\f\n;; Local Variables:\n"
879 ";; version-control: never\n"
880 ";; no-byte-compile: t\n"
881 ";; no-update-autoloads: t\n"
882 ";; End:\n"
883 ";;; " (file-name-nondirectory file)
884 " ends here\n")
885 nil file nil 'silent))
886 file)
887
888 (defvar generated-autoload-file)
889 (defvar version-control)
890
891 (defvar package--silence nil)
892
893 (defun package-generate-autoloads (name pkg-dir)
894 (let* ((auto-name (format "%s-autoloads.el" name))
895 ;;(ignore-name (concat name "-pkg.el"))
896 (generated-autoload-file (expand-file-name auto-name pkg-dir))
897 ;; Silence `autoload-generate-file-autoloads'.
898 (noninteractive package--silence)
899 (backup-inhibited t)
900 (version-control 'never))
901 (package-autoload-ensure-default-file generated-autoload-file)
902 (update-directory-autoloads pkg-dir)
903 (let ((buf (find-buffer-visiting generated-autoload-file)))
904 (when buf (kill-buffer buf)))
905 auto-name))
906
907 (defun package--make-autoloads-and-stuff (pkg-desc pkg-dir)
908 "Generate autoloads, description file, etc.. for PKG-DESC installed at PKG-DIR."
909 (package-generate-autoloads (package-desc-name pkg-desc) pkg-dir)
910 (let ((desc-file (expand-file-name (package--description-file pkg-dir)
911 pkg-dir)))
912 (unless (file-exists-p desc-file)
913 (package-generate-description-file pkg-desc desc-file)))
914 ;; FIXME: Create foo.info and dir file from foo.texi?
915 )
916
917 ;;;; Compilation
918 (defun package--compile (pkg-desc)
919 "Byte-compile installed package PKG-DESC."
920 (package-activate-1 pkg-desc)
921 (byte-recompile-directory (package-desc-dir pkg-desc) 0 t))
922
923 ;;;; Inferring package from current buffer
924 (defun package-read-from-string (str)
925 "Read a Lisp expression from STR.
926 Signal an error if the entire string was not used."
927 (let* ((read-data (read-from-string str))
928 (more-left
929 (condition-case nil
930 ;; The call to `ignore' suppresses a compiler warning.
931 (progn (ignore (read-from-string
932 (substring str (cdr read-data))))
933 t)
934 (end-of-file nil))))
935 (if more-left
936 (error "Can't read whole string")
937 (car read-data))))
938
939 (defun package--prepare-dependencies (deps)
940 "Turn DEPS into an acceptable list of dependencies.
941
942 Any parts missing a version string get a default version string
943 of \"0\" (meaning any version) and an appropriate level of lists
944 is wrapped around any parts requiring it."
945 (cond
946 ((not (listp deps))
947 (error "Invalid requirement specifier: %S" deps))
948 (t (mapcar (lambda (dep)
949 (cond
950 ((symbolp dep) `(,dep "0"))
951 ((stringp dep)
952 (error "Invalid requirement specifier: %S" dep))
953 ((and (listp dep) (null (cdr dep)))
954 (list (car dep) "0"))
955 (t dep)))
956 deps))))
957
958 (declare-function lm-header "lisp-mnt" (header))
959 (declare-function lm-homepage "lisp-mnt" ())
960
961 (defun package-buffer-info ()
962 "Return a `package-desc' describing the package in the current buffer.
963
964 If the buffer does not contain a conforming package, signal an
965 error. If there is a package, narrow the buffer to the file's
966 boundaries."
967 (goto-char (point-min))
968 (unless (re-search-forward "^;;; \\([^ ]*\\)\\.el ---[ \t]*\\(.*?\\)[ \t]*\\(-\\*-.*-\\*-[ \t]*\\)?$" nil t)
969 (error "Package lacks a file header"))
970 (let ((file-name (match-string-no-properties 1))
971 (desc (match-string-no-properties 2))
972 (start (line-beginning-position)))
973 (unless (search-forward (concat ";;; " file-name ".el ends here"))
974 (error "Package lacks a terminating comment"))
975 ;; Try to include a trailing newline.
976 (forward-line)
977 (narrow-to-region start (point))
978 (require 'lisp-mnt)
979 ;; Use some headers we've invented to drive the process.
980 (let* ((requires-str (lm-header "package-requires"))
981 ;; Prefer Package-Version; if defined, the package author
982 ;; probably wants us to use it. Otherwise try Version.
983 (pkg-version
984 (or (package-strip-rcs-id (lm-header "package-version"))
985 (package-strip-rcs-id (lm-header "version"))))
986 (homepage (lm-homepage)))
987 (unless pkg-version
988 (error
989 "Package lacks a \"Version\" or \"Package-Version\" header"))
990 (package-desc-from-define
991 file-name pkg-version desc
992 (if requires-str
993 (package--prepare-dependencies
994 (package-read-from-string requires-str)))
995 :kind 'single
996 :url homepage))))
997
998 (defun package--read-pkg-desc (kind)
999 "Read a `define-package' form in current buffer.
1000 Return the pkg-desc, with desc-kind set to KIND."
1001 (goto-char (point-min))
1002 (unwind-protect
1003 (let* ((pkg-def-parsed (read (current-buffer)))
1004 (pkg-desc
1005 (when (eq (car pkg-def-parsed) 'define-package)
1006 (apply #'package-desc-from-define
1007 (append (cdr pkg-def-parsed))))))
1008 (when pkg-desc
1009 (setf (package-desc-kind pkg-desc) kind)
1010 pkg-desc))))
1011
1012 (declare-function tar-get-file-descriptor "tar-mode" (file))
1013 (declare-function tar--extract "tar-mode" (descriptor))
1014
1015 (defun package-tar-file-info ()
1016 "Find package information for a tar file.
1017 The return result is a `package-desc'."
1018 (cl-assert (derived-mode-p 'tar-mode))
1019 (let* ((dir-name (file-name-directory
1020 (tar-header-name (car tar-parse-info))))
1021 (desc-file (package--description-file dir-name))
1022 (tar-desc (tar-get-file-descriptor (concat dir-name desc-file))))
1023 (unless tar-desc
1024 (error "No package descriptor file found"))
1025 (with-current-buffer (tar--extract tar-desc)
1026 (unwind-protect
1027 (or (package--read-pkg-desc 'tar)
1028 (error "Can't find define-package in %s"
1029 (tar-header-name tar-desc)))
1030 (kill-buffer (current-buffer))))))
1031
1032 (defun package-dir-info ()
1033 "Find package information for a directory.
1034 The return result is a `package-desc'."
1035 (cl-assert (derived-mode-p 'dired-mode))
1036 (let* ((desc-file (package--description-file default-directory)))
1037 (if (file-readable-p desc-file)
1038 (with-temp-buffer
1039 (insert-file-contents desc-file)
1040 (package--read-pkg-desc 'dir))
1041 (let ((files (directory-files default-directory t "\\.el\\'" t))
1042 info)
1043 (while files
1044 (with-temp-buffer
1045 (insert-file-contents (pop files))
1046 ;; When we find the file with the data,
1047 (when (setq info (ignore-errors (package-buffer-info)))
1048 ;; stop looping,
1049 (setq files nil)
1050 ;; set the 'dir kind,
1051 (setf (package-desc-kind info) 'dir))))
1052 ;; and return the info.
1053 info))))
1054
1055 \f
1056 ;;; Communicating with Archives
1057 ;; Set of low-level functions for communicating with archives and
1058 ;; signature checking.
1059 (defun package--write-file-no-coding (file-name)
1060 (let ((buffer-file-coding-system 'no-conversion))
1061 (write-region (point-min) (point-max) file-name nil 'silent)))
1062
1063 (declare-function url-http-file-exists-p "url-http" (url))
1064
1065 (defun package--archive-file-exists-p (location file)
1066 (let ((http (string-match "\\`https?:" location)))
1067 (if http
1068 (progn
1069 (require 'url-http)
1070 (url-http-file-exists-p (concat location file)))
1071 (file-exists-p (expand-file-name file location)))))
1072
1073 (declare-function epg-make-context "epg"
1074 (&optional protocol armor textmode include-certs
1075 cipher-algorithm
1076 digest-algorithm
1077 compress-algorithm))
1078 (declare-function epg-verify-string "epg" (context signature
1079 &optional signed-text))
1080 (declare-function epg-context-result-for "epg" (context name))
1081 (declare-function epg-signature-status "epg" (signature))
1082 (declare-function epg-signature-to-string "epg" (signature))
1083
1084 (defun package--display-verify-error (context sig-file)
1085 (unless (equal (epg-context-error-output context) "")
1086 (with-output-to-temp-buffer "*Error*"
1087 (with-current-buffer standard-output
1088 (if (epg-context-result-for context 'verify)
1089 (insert (format "Failed to verify signature %s:\n" sig-file)
1090 (mapconcat #'epg-signature-to-string
1091 (epg-context-result-for context 'verify)
1092 "\n"))
1093 (insert (format "Error while verifying signature %s:\n" sig-file)))
1094 (insert "\nCommand output:\n" (epg-context-error-output context))))))
1095
1096 (defmacro package--with-work-buffer (location file &rest body)
1097 "Run BODY in a buffer containing the contents of FILE at LOCATION.
1098 LOCATION is the base location of a package archive, and should be
1099 one of the URLs (or file names) specified in `package-archives'.
1100 FILE is the name of a file relative to that base location.
1101
1102 This macro retrieves FILE from LOCATION into a temporary buffer,
1103 and evaluates BODY while that buffer is current. This work
1104 buffer is killed afterwards. Return the last value in BODY."
1105 (declare (indent 2) (debug t))
1106 `(with-temp-buffer
1107 (if (string-match-p "\\`https?:" ,location)
1108 (url-insert-file-contents (concat ,location ,file))
1109 (unless (file-name-absolute-p ,location)
1110 (error "Archive location %s is not an absolute file name"
1111 ,location))
1112 (insert-file-contents (expand-file-name ,file ,location)))
1113 ,@body))
1114
1115 (defmacro package--with-work-buffer-async (location file async &rest body)
1116 "Run BODY in a buffer containing the contents of FILE at LOCATION.
1117 If ASYNC is non-nil, and if it is possible, run BODY
1118 asynchronously. If an error is encountered and ASYNC is a
1119 function, call it with no arguments (instead of executing BODY),
1120 otherwise propagate the error. For description of the other
1121 arguments see `package--with-work-buffer'."
1122 (declare (indent 3) (debug t))
1123 (macroexp-let2* macroexp-copyable-p
1124 ((async-1 async)
1125 (file-1 file)
1126 (location-1 location))
1127 `(if (or (not ,async-1)
1128 (not (string-match-p "\\`https?:" ,location-1)))
1129 (package--with-work-buffer ,location-1 ,file-1 ,@body)
1130 (url-retrieve (concat ,location-1 ,file-1)
1131 (lambda (status)
1132 (if (eq (car status) :error)
1133 (if (functionp ,async-1)
1134 (funcall ,async-1)
1135 (signal (cdar status) (cddr status)))
1136 (goto-char (point-min))
1137 (unless (search-forward "\n\n" nil 'noerror)
1138 (error "Invalid url response in buffer %s"
1139 (current-buffer)))
1140 (delete-region (point-min) (point))
1141 ,@body)
1142 (kill-buffer (current-buffer)))
1143 nil
1144 'silent))))
1145
1146 (defun package--check-signature-content (content string &optional sig-file)
1147 "Check signature CONTENT against STRING.
1148 SIG-FILE is the name of the signature file, used when signaling
1149 errors."
1150 (let* ((context (epg-make-context 'OpenPGP))
1151 (homedir (expand-file-name "gnupg" package-user-dir)))
1152 (setf (epg-context-home-directory context) homedir)
1153 (condition-case error
1154 (epg-verify-string context content string)
1155 (error (package--display-verify-error context sig-file)
1156 (signal (car error) (cdr error))))
1157 (let (good-signatures had-fatal-error)
1158 ;; The .sig file may contain multiple signatures. Success if one
1159 ;; of the signatures is good.
1160 (dolist (sig (epg-context-result-for context 'verify))
1161 (if (eq (epg-signature-status sig) 'good)
1162 (push sig good-signatures)
1163 ;; If package-check-signature is allow-unsigned, don't
1164 ;; signal error when we can't verify signature because of
1165 ;; missing public key. Other errors are still treated as
1166 ;; fatal (bug#17625).
1167 (unless (and (eq package-check-signature 'allow-unsigned)
1168 (eq (epg-signature-status sig) 'no-pubkey))
1169 (setq had-fatal-error t))))
1170 (when (and (null good-signatures) had-fatal-error)
1171 (package--display-verify-error context sig-file)
1172 (error "Failed to verify signature %s" sig-file))
1173 good-signatures)))
1174
1175 (defun package--check-signature (location file &optional string async callback)
1176 "Check signature of the current buffer.
1177 Download the signature file from LOCATION by appending \".sig\"
1178 to FILE.
1179 GnuPG keyring is located under \"gnupg\" in `package-user-dir'.
1180 STRING is the string to verify, it defaults to `buffer-string'.
1181 If ASYNC is non-nil, the download of the signature file is
1182 done asynchronously.
1183
1184 If the signature is verified and CALLBACK was provided, CALLBACK
1185 is `funcall'ed with the list of good signatures as argument (the
1186 list can be empty). If the signatures file is not found,
1187 CALLBACK is called with no arguments."
1188 (let ((sig-file (concat file ".sig"))
1189 (string (or string (buffer-string))))
1190 (condition-case nil
1191 (package--with-work-buffer-async
1192 location sig-file (when async (or callback t))
1193 (let ((sig (package--check-signature-content
1194 (buffer-string) string sig-file)))
1195 (when callback (funcall callback sig))
1196 sig))
1197 (file-error (funcall callback)))))
1198
1199 \f
1200 ;;; Packages on Archives
1201 ;; The following variables store information about packages available
1202 ;; from archives. The most important of these is
1203 ;; `package-archive-contents' which is initially populated by the
1204 ;; function `package-read-all-archive-contents' from a cache on disk.
1205 ;; The `package-initialize' command is also closely related to this
1206 ;; section, but it has its own section.
1207 (defconst package-archive-version 1
1208 "Version number of the package archive understood by this file.
1209 Lower version numbers than this will probably be understood as well.")
1210
1211 ;; We don't prime the cache since it tends to get out of date.
1212 (defvar package-archive-contents nil
1213 "Cache of the contents of the Emacs Lisp Package Archive.
1214 This is an alist mapping package names (symbols) to
1215 non-empty lists of `package-desc' structures.")
1216 (put 'package-archive-contents 'risky-local-variable t)
1217
1218 (defvar package--compatibility-table nil
1219 "Hash table connecting package names to their compatibility.
1220 Each key is a symbol, the name of a package.
1221
1222 The value is either nil, representing an incompatible package, or
1223 a version list, representing the highest compatible version of
1224 that package which is available.
1225
1226 A package is considered incompatible if it requires an Emacs
1227 version higher than the one being used. To check for package
1228 \(in)compatibility, don't read this table directly, use
1229 `package--incompatible-p' which also checks dependencies.")
1230
1231 (defun package--build-compatibility-table ()
1232 "Build `package--compatibility-table' with `package--mapc'."
1233 ;; Initialize the list of built-ins.
1234 (require 'finder-inf nil t)
1235 ;; Build compat table.
1236 (setq package--compatibility-table (make-hash-table :test 'eq))
1237 (package--mapc #'package--add-to-compatibility-table))
1238
1239 (defun package--add-to-compatibility-table (pkg)
1240 "If PKG is compatible (without dependencies), add to the compatibility table.
1241 PKG is a package-desc object.
1242 Only adds if its version is higher than what's already stored in
1243 the table."
1244 (unless (package--incompatible-p pkg 'shallow)
1245 (let* ((name (package-desc-name pkg))
1246 (version (or (package-desc-version pkg) '(0)))
1247 (table-version (gethash name package--compatibility-table)))
1248 (when (or (not table-version)
1249 (version-list-< table-version version))
1250 (puthash name version package--compatibility-table)))))
1251
1252 ;; Package descriptor objects used inside the "archive-contents" file.
1253 ;; Changing this defstruct implies changing the format of the
1254 ;; "archive-contents" files.
1255 (cl-defstruct (package--ac-desc
1256 (:constructor package-make-ac-desc (version reqs summary kind extras))
1257 (:copier nil)
1258 (:type vector))
1259 version reqs summary kind extras)
1260
1261 (defun package--append-to-alist (pkg-desc alist)
1262 "Append an entry for PKG-DESC to the start of ALIST and return it.
1263 This entry takes the form (`package-desc-name' PKG-DESC).
1264
1265 If ALIST already has an entry with this name, destructively add
1266 PKG-DESC to the cdr of this entry instead, sorted by version
1267 number."
1268 (let* ((name (package-desc-name pkg-desc))
1269 (priority-version (package-desc-priority-version pkg-desc))
1270 (existing-packages (assq name alist)))
1271 (if (not existing-packages)
1272 (cons (list name pkg-desc)
1273 alist)
1274 (while (if (and (cdr existing-packages)
1275 (version-list-< priority-version
1276 (package-desc-priority-version
1277 (cadr existing-packages))))
1278 (setq existing-packages (cdr existing-packages))
1279 (push pkg-desc (cdr existing-packages))
1280 nil))
1281 alist)))
1282
1283 (defun package--add-to-archive-contents (package archive)
1284 "Add the PACKAGE from the given ARCHIVE if necessary.
1285 PACKAGE should have the form (NAME . PACKAGE--AC-DESC).
1286 Also, add the originating archive to the `package-desc' structure."
1287 (let* ((name (car package))
1288 (version (package--ac-desc-version (cdr package)))
1289 (pkg-desc
1290 (package-desc-create
1291 :name name
1292 :version version
1293 :reqs (package--ac-desc-reqs (cdr package))
1294 :summary (package--ac-desc-summary (cdr package))
1295 :kind (package--ac-desc-kind (cdr package))
1296 :archive archive
1297 :extras (and (> (length (cdr package)) 4)
1298 ;; Older archive-contents files have only 4
1299 ;; elements here.
1300 (package--ac-desc-extras (cdr package)))))
1301 (pinned-to-archive (assoc name package-pinned-packages)))
1302 ;; Skip entirely if pinned to another archive.
1303 (when (not (and pinned-to-archive
1304 (not (equal (cdr pinned-to-archive) archive))))
1305 (setq package-archive-contents
1306 (package--append-to-alist pkg-desc package-archive-contents)))))
1307
1308 (defun package--read-archive-file (file)
1309 "Re-read archive file FILE, if it exists.
1310 Will return the data from the file, or nil if the file does not exist.
1311 Will throw an error if the archive version is too new."
1312 (let ((filename (expand-file-name file package-user-dir)))
1313 (when (file-exists-p filename)
1314 (with-temp-buffer
1315 (let ((coding-system-for-read 'utf-8))
1316 (insert-file-contents filename))
1317 (let ((contents (read (current-buffer))))
1318 (if (> (car contents) package-archive-version)
1319 (error "Package archive version %d is higher than %d"
1320 (car contents) package-archive-version))
1321 (cdr contents))))))
1322
1323 (defun package-read-archive-contents (archive)
1324 "Re-read archive contents for ARCHIVE.
1325 If successful, set the variable `package-archive-contents'.
1326 If the archive version is too new, signal an error."
1327 ;; Version 1 of 'archive-contents' is identical to our internal
1328 ;; representation.
1329 (let* ((contents-file (format "archives/%s/archive-contents" archive))
1330 (contents (package--read-archive-file contents-file)))
1331 (when contents
1332 (dolist (package contents)
1333 (package--add-to-archive-contents package archive)))))
1334
1335 (defun package-read-all-archive-contents ()
1336 "Re-read `archive-contents', if it exists.
1337 If successful, set `package-archive-contents'."
1338 (setq package-archive-contents nil)
1339 (dolist (archive package-archives)
1340 (package-read-archive-contents (car archive))))
1341
1342 ;;;; Package Initialize
1343 ;; A bit of a milestone. This brings together some of the above
1344 ;; sections and populates all relevant lists of packages from contents
1345 ;; available on disk.
1346 (defvar package--initialized nil)
1347
1348 ;;;###autoload
1349 (defun package-initialize (&optional no-activate)
1350 "Load Emacs Lisp packages, and activate them.
1351 The variable `package-load-list' controls which packages to load.
1352 If optional arg NO-ACTIVATE is non-nil, don't activate packages.
1353 If `user-init-file' does not mention `(package-initialize)', add
1354 it to the file."
1355 (interactive)
1356 (setq package-alist nil)
1357 (package--ensure-init-file)
1358 (package-load-all-descriptors)
1359 (package-read-all-archive-contents)
1360 (unless no-activate
1361 (dolist (elt package-alist)
1362 (package-activate (car elt))))
1363 (setq package--initialized t)
1364 ;; This uses `package--mapc' so it must be called after
1365 ;; `package--initialized' is t.
1366 (package--build-compatibility-table))
1367
1368 \f
1369 ;;;; Populating `package-archive-contents' from archives
1370 ;; This subsection populates the variables listed above from the
1371 ;; actual archives, instead of from a local cache.
1372 (defvar package--downloads-in-progress nil
1373 "List of in-progress asynchronous downloads.")
1374
1375 (declare-function epg-check-configuration "epg-config"
1376 (config &optional minimum-version))
1377 (declare-function epg-configuration "epg-config" ())
1378 (declare-function epg-import-keys-from-file "epg" (context keys))
1379
1380 (defun package--message (format &rest args)
1381 "Like `message', except sometimes don't print to minibuffer.
1382 If the variable `package--silence' is non-nil, the message is not
1383 displayed on the minibuffer."
1384 (apply #'message format args)
1385 (when package--silence
1386 (message nil)))
1387
1388 ;;;###autoload
1389 (defun package-import-keyring (&optional file)
1390 "Import keys from FILE."
1391 (interactive "fFile: ")
1392 (setq file (expand-file-name file))
1393 (let ((context (epg-make-context 'OpenPGP))
1394 (homedir (expand-file-name "gnupg" package-user-dir)))
1395 (with-file-modes 448
1396 (make-directory homedir t))
1397 (setf (epg-context-home-directory context) homedir)
1398 (package--message "Importing %s..." (file-name-nondirectory file))
1399 (epg-import-keys-from-file context file)
1400 (package--message "Importing %s...done" (file-name-nondirectory file))))
1401
1402 (defvar package--post-download-archives-hook nil
1403 "Hook run after the archive contents are downloaded.
1404 Don't run this hook directly. It is meant to be run as part of
1405 `package--update-downloads-in-progress'.")
1406 (put 'package--post-download-archives-hook 'risky-local-variable t)
1407
1408 (defun package--update-downloads-in-progress (entry)
1409 "Remove ENTRY from `package--downloads-in-progress'.
1410 Once it's empty, run `package--post-download-archives-hook'."
1411 ;; Keep track of the downloading progress.
1412 (setq package--downloads-in-progress
1413 (remove entry package--downloads-in-progress))
1414 ;; If this was the last download, run the hook.
1415 (unless package--downloads-in-progress
1416 (package-read-all-archive-contents)
1417 (package--build-compatibility-table)
1418 ;; We message before running the hook, so the hook can give
1419 ;; messages as well.
1420 (message "Package refresh done")
1421 (run-hooks 'package--post-download-archives-hook)))
1422
1423 (defun package--download-one-archive (archive file &optional async)
1424 "Retrieve an archive file FILE from ARCHIVE, and cache it.
1425 ARCHIVE should be a cons cell of the form (NAME . LOCATION),
1426 similar to an entry in `package-alist'. Save the cached copy to
1427 \"archives/NAME/FILE\" in `package-user-dir'."
1428 (package--with-work-buffer-async (cdr archive) file async
1429 (let* ((location (cdr archive))
1430 (name (car archive))
1431 (content (buffer-string))
1432 (dir (expand-file-name (format "archives/%s" name) package-user-dir))
1433 (local-file (expand-file-name file dir)))
1434 (when (listp (read-from-string content))
1435 (make-directory dir t)
1436 (if (or (not package-check-signature)
1437 (member archive package-unsigned-archives))
1438 ;; If we don't care about the signature, save the file and
1439 ;; we're done.
1440 (progn (write-region content nil local-file nil 'silent)
1441 (package--update-downloads-in-progress archive))
1442 ;; If we care, check it (perhaps async) and *then* write the file.
1443 (package--check-signature
1444 location file content async
1445 ;; This function will be called after signature checking.
1446 (lambda (&optional good-sigs)
1447 (unless (or good-sigs (eq package-check-signature 'allow-unsigned))
1448 ;; Even if the sig fails, this download is done, so
1449 ;; remove it from the in-progress list.
1450 (package--update-downloads-in-progress archive)
1451 (error "Unsigned archive `%s'" name))
1452 ;; Write out the archives file.
1453 (write-region content nil local-file nil 'silent)
1454 ;; Write out good signatures into archive-contents.signed file.
1455 (when good-sigs
1456 (write-region (mapconcat #'epg-signature-to-string good-sigs "\n")
1457 nil (concat local-file ".signed") nil 'silent))
1458 (package--update-downloads-in-progress archive))))))))
1459
1460 (defun package--download-and-read-archives (&optional async)
1461 "Download descriptions of all `package-archives' and read them.
1462 This populates `package-archive-contents'. If ASYNC is non-nil,
1463 perform the downloads asynchronously."
1464 ;; The downloaded archive contents will be read as part of
1465 ;; `package--update-downloads-in-progress'.
1466 (setq package--downloads-in-progress
1467 (append package-archives
1468 package--downloads-in-progress))
1469 (dolist (archive package-archives)
1470 (condition-case-unless-debug nil
1471 (package--download-one-archive
1472 archive "archive-contents"
1473 ;; Called if the async download fails
1474 (when async
1475 (lambda () (package--update-downloads-in-progress archive))))
1476 (error (message "Failed to download `%s' archive."
1477 (car archive))))))
1478
1479 ;;;###autoload
1480 (defun package-refresh-contents (&optional async)
1481 "Download descriptions of all configured ELPA packages.
1482 For each archive configured in the variable `package-archives',
1483 inform Emacs about the latest versions of all packages it offers,
1484 and make them available for download.
1485 Optional argument ASYNC specifies whether to perform the
1486 downloads in the background."
1487 (interactive)
1488 (unless (file-exists-p package-user-dir)
1489 (make-directory package-user-dir t))
1490 (let ((default-keyring (expand-file-name "package-keyring.gpg"
1491 data-directory))
1492 (package--silence async))
1493 (when (and package-check-signature (file-exists-p default-keyring))
1494 (condition-case-unless-debug error
1495 (progn
1496 (epg-check-configuration (epg-configuration))
1497 (package-import-keyring default-keyring))
1498 (error (message "Cannot import default keyring: %S" (cdr error)))))
1499 (package--download-and-read-archives async)))
1500
1501 \f
1502 ;;; Dependency Management
1503 ;; Calculating the full transaction necessary for an installation,
1504 ;; keeping track of which packages were installed strictly as
1505 ;; dependencies, and determining which packages cannot be removed
1506 ;; because they are dependencies.
1507 (defun package-compute-transaction (packages requirements &optional seen)
1508 "Return a list of packages to be installed, including PACKAGES.
1509 PACKAGES should be a list of `package-desc'.
1510
1511 REQUIREMENTS should be a list of additional requirements; each
1512 element in this list should have the form (PACKAGE VERSION-LIST),
1513 where PACKAGE is a package name and VERSION-LIST is the required
1514 version of that package.
1515
1516 This function recursively computes the requirements of the
1517 packages in REQUIREMENTS, and returns a list of all the packages
1518 that must be installed. Packages that are already installed are
1519 not included in this list.
1520
1521 SEEN is used internally to detect infinite recursion."
1522 ;; FIXME: We really should use backtracking to explore the whole
1523 ;; search space (e.g. if foo require bar-1.3, and bar-1.4 requires toto-1.1
1524 ;; whereas bar-1.3 requires toto-1.0 and the user has put a hold on toto-1.0:
1525 ;; the current code might fail to see that it could install foo by using the
1526 ;; older bar-1.3).
1527 (dolist (elt requirements)
1528 (let* ((next-pkg (car elt))
1529 (next-version (cadr elt))
1530 (already ()))
1531 (dolist (pkg packages)
1532 (if (eq next-pkg (package-desc-name pkg))
1533 (setq already pkg)))
1534 (when already
1535 (if (version-list-<= next-version (package-desc-version already))
1536 ;; `next-pkg' is already in `packages', but its position there
1537 ;; means it might be installed too late: remove it from there, so
1538 ;; we re-add it (along with its dependencies) at an earlier place
1539 ;; below (bug#16994).
1540 (if (memq already seen) ;Avoid inf-loop on dependency cycles.
1541 (package--message "Dependency cycle going through %S"
1542 (package-desc-full-name already))
1543 (setq packages (delq already packages))
1544 (setq already nil))
1545 (error "Need package `%s-%s', but only %s is being installed"
1546 next-pkg (package-version-join next-version)
1547 (package-version-join (package-desc-version already)))))
1548 (cond
1549 (already nil)
1550 ((package-installed-p next-pkg next-version) nil)
1551
1552 (t
1553 ;; A package is required, but not installed. It might also be
1554 ;; blocked via `package-load-list'.
1555 (let ((pkg-descs (cdr (assq next-pkg package-archive-contents)))
1556 (found nil)
1557 (problem nil))
1558 (while (and pkg-descs (not found))
1559 (let* ((pkg-desc (pop pkg-descs))
1560 (version (package-desc-version pkg-desc))
1561 (disabled (package-disabled-p next-pkg version)))
1562 (cond
1563 ((version-list-< version next-version)
1564 (error
1565 "Need package `%s-%s', but only %s is available"
1566 next-pkg (package-version-join next-version)
1567 (package-version-join version)))
1568 (disabled
1569 (unless problem
1570 (setq problem
1571 (if (stringp disabled)
1572 (format "Package `%s' held at version %s, \
1573 but version %s required"
1574 next-pkg disabled
1575 (package-version-join next-version))
1576 (format "Required package '%s' is disabled"
1577 next-pkg)))))
1578 (t (setq found pkg-desc)))))
1579 (unless found
1580 (if problem
1581 (error "%s" problem)
1582 (error "Package `%s-%s' is unavailable"
1583 next-pkg (package-version-join next-version))))
1584 (setq packages
1585 (package-compute-transaction (cons found packages)
1586 (package-desc-reqs found)
1587 (cons found seen))))))))
1588 packages)
1589
1590 (defun package--find-non-dependencies ()
1591 "Return a list of installed packages which are not dependencies.
1592 Finds all packages in `package-alist' which are not dependencies
1593 of any other packages.
1594 Used to populate `package-selected-packages'."
1595 (let ((dep-list
1596 (delete-dups
1597 (apply #'append
1598 (mapcar (lambda (p) (mapcar #'car (package-desc-reqs (cadr p))))
1599 package-alist)))))
1600 (cl-loop for p in package-alist
1601 for name = (car p)
1602 unless (memq name dep-list)
1603 collect name)))
1604
1605 (defun package--save-selected-packages (value)
1606 "Set and save `package-selected-packages' to VALUE."
1607 (let ((save-silently package--silence))
1608 (customize-save-variable
1609 'package-selected-packages
1610 (setq package-selected-packages value))))
1611
1612 (defun package--user-selected-p (pkg)
1613 "Return non-nil if PKG is a package was installed by the user.
1614 PKG is a package name.
1615 This looks into `package-selected-packages', populating it first
1616 if it is still empty."
1617 (unless (consp package-selected-packages)
1618 (package--save-selected-packages (package--find-non-dependencies)))
1619 (memq pkg package-selected-packages))
1620
1621 (defun package--get-deps (pkg &optional only)
1622 (let* ((pkg-desc (cadr (assq pkg package-alist)))
1623 (direct-deps (cl-loop for p in (package-desc-reqs pkg-desc)
1624 for name = (car p)
1625 when (assq name package-alist)
1626 collect name))
1627 (indirect-deps (unless (eq only 'direct)
1628 (delete-dups
1629 (cl-loop for p in direct-deps
1630 append (package--get-deps p))))))
1631 (cl-case only
1632 (direct direct-deps)
1633 (separate (list direct-deps indirect-deps))
1634 (indirect indirect-deps)
1635 (t (delete-dups (append direct-deps indirect-deps))))))
1636
1637 (defun package--removable-packages ()
1638 "Return a list of names of packages no longer needed.
1639 These are packages which are neither contained in
1640 `package-selected-packages' nor a dependency of one that is."
1641 (let ((needed (cl-loop for p in package-selected-packages
1642 if (assq p package-alist)
1643 ;; `p' and its dependencies are needed.
1644 append (cons p (package--get-deps p)))))
1645 (cl-loop for p in (mapcar #'car package-alist)
1646 unless (memq p needed)
1647 collect p)))
1648
1649 (defun package--used-elsewhere-p (pkg-desc &optional pkg-list)
1650 "Non-nil if PKG-DESC is a dependency of a package in PKG-LIST.
1651 Return the first package found in PKG-LIST of which PKG is a
1652 dependency.
1653
1654 When not specified, PKG-LIST defaults to `package-alist'
1655 with PKG-DESC entry removed."
1656 (unless (string= (package-desc-status pkg-desc) "obsolete")
1657 (let ((pkg (package-desc-name pkg-desc)))
1658 (cl-loop with alist = (or pkg-list
1659 (remove (assq pkg package-alist)
1660 package-alist))
1661 for p in alist thereis
1662 (and (memq pkg (mapcar #'car (package-desc-reqs (cadr p))))
1663 (car p))))))
1664
1665 (defun package--sort-deps-in-alist (package only)
1666 "Return a list of dependencies for PACKAGE sorted by dependency.
1667 PACKAGE is included as the first element of the returned list.
1668 ONLY is an alist associating package names to package objects.
1669 Only these packages will be in the return value an their cdrs are
1670 destructively set to nil in ONLY."
1671 (let ((out))
1672 (dolist (dep (package-desc-reqs package))
1673 (when-let ((cell (assq (car dep) only))
1674 (dep-package (cdr-safe cell)))
1675 (setcdr cell nil)
1676 (setq out (append (package--sort-deps-in-alist dep-package only)
1677 out))))
1678 (cons package out)))
1679
1680 (defun package--sort-by-dependence (package-list)
1681 "Return PACKAGE-LIST sorted by dependence.
1682 That is, any element of the returned list is guaranteed to not
1683 directly depend on any elements that come before it.
1684
1685 PACKAGE-LIST is a list of package-desc objects.
1686 Indirect dependencies are guaranteed to be returned in order only
1687 if all the in-between dependencies are also in PACKAGE-LIST."
1688 (let ((alist (mapcar (lambda (p) (cons (package-desc-name p) p)) package-list))
1689 out-list)
1690 (dolist (cell alist out-list)
1691 ;; `package--sort-deps-in-alist' destructively changes alist, so
1692 ;; some cells might already be empty. We check this here.
1693 (when-let ((pkg-desc (cdr cell)))
1694 (setcdr cell nil)
1695 (setq out-list
1696 (append (package--sort-deps-in-alist pkg-desc alist)
1697 out-list))))))
1698
1699 \f
1700 ;;; Installation Functions
1701 ;; As opposed to the previous section (which listed some underlying
1702 ;; functions necessary for installation), this one contains the actual
1703 ;; functions that install packages. The package itself can be
1704 ;; installed in a variety of ways (archives, buffer, file), but
1705 ;; requirements (dependencies) are always satisfied by looking in
1706 ;; `package-archive-contents'.
1707 (defun package-archive-base (desc)
1708 "Return the archive containing the package NAME."
1709 (cdr (assoc (package-desc-archive desc) package-archives)))
1710
1711 (defun package-install-from-archive (pkg-desc &optional async callback)
1712 "Download and install a tar package.
1713 If ASYNC is non-nil, perform the download asynchronously.
1714 If CALLBACK is non-nil, call it with no arguments once the
1715 operation is done."
1716 ;; This won't happen, unless the archive is doing something wrong.
1717 (when (eq (package-desc-kind pkg-desc) 'dir)
1718 (error "Can't install directory package from archive"))
1719 (let* ((location (package-archive-base pkg-desc))
1720 (file (concat (package-desc-full-name pkg-desc)
1721 (package-desc-suffix pkg-desc))))
1722 (package--with-work-buffer-async location file async
1723 (if (or (not package-check-signature)
1724 (member (package-desc-archive pkg-desc)
1725 package-unsigned-archives))
1726 ;; If we don't care about the signature, unpack and we're
1727 ;; done.
1728 (progn (let ((save-silently async))
1729 (package-unpack pkg-desc))
1730 (funcall callback))
1731 ;; If we care, check it and *then* write the file.
1732 (let ((content (buffer-string)))
1733 (package--check-signature
1734 location file content async
1735 ;; This function will be called after signature checking.
1736 (lambda (&optional good-sigs)
1737 (unless (or good-sigs (eq package-check-signature 'allow-unsigned))
1738 ;; Even if the sig fails, this download is done, so
1739 ;; remove it from the in-progress list.
1740 (error "Unsigned package: `%s'"
1741 (package-desc-name pkg-desc)))
1742 ;; Signature checked, unpack now.
1743 (with-temp-buffer (insert content)
1744 (let ((save-silently async))
1745 (package-unpack pkg-desc)))
1746 ;; Here the package has been installed successfully, mark it as
1747 ;; signed if appropriate.
1748 (when good-sigs
1749 ;; Write out good signatures into NAME-VERSION.signed file.
1750 (write-region (mapconcat #'epg-signature-to-string good-sigs "\n")
1751 nil
1752 (expand-file-name
1753 (concat (package-desc-full-name pkg-desc) ".signed")
1754 package-user-dir)
1755 nil 'silent)
1756 ;; Update the old pkg-desc which will be shown on the description buffer.
1757 (setf (package-desc-signed pkg-desc) t)
1758 ;; Update the new (activated) pkg-desc as well.
1759 (when-let ((pkg-descs (cdr (assq (package-desc-name pkg-desc) package-alist))))
1760 (setf (package-desc-signed (car pkg-descs)) t)))
1761 (when (functionp callback)
1762 (funcall callback)))))))))
1763
1764 (defun package-installed-p (package &optional min-version)
1765 "Return true if PACKAGE, of MIN-VERSION or newer, is installed.
1766 If PACKAGE is a symbol, it is the package name and MIN-VERSION
1767 should be a version list.
1768
1769 If PACKAGE is a package-desc object, MIN-VERSION is ignored."
1770 (unless package--initialized (error "package.el is not yet initialized!"))
1771 (if (package-desc-p package)
1772 (let ((dir (package-desc-dir package)))
1773 (and (stringp dir)
1774 (file-exists-p dir)))
1775 (or
1776 (let ((pkg-descs (cdr (assq package package-alist))))
1777 (and pkg-descs
1778 (version-list-<= min-version
1779 (package-desc-version (car pkg-descs)))))
1780 ;; Also check built-in packages.
1781 (package-built-in-p package min-version))))
1782
1783 (defun package-download-transaction (packages &optional async callback)
1784 "Download and install all the packages in PACKAGES.
1785 PACKAGES should be a list of package-desc.
1786 If ASYNC is non-nil, perform the downloads asynchronously.
1787 If CALLBACK is non-nil, call it with no arguments once the
1788 entire operation is done.
1789
1790 This function assumes that all package requirements in
1791 PACKAGES are satisfied, i.e. that PACKAGES is computed
1792 using `package-compute-transaction'."
1793 (cond
1794 (packages (package-install-from-archive
1795 (car packages)
1796 async
1797 (lambda ()
1798 (package-download-transaction (cdr packages))
1799 (when (functionp callback)
1800 (funcall callback)))))
1801 (callback (funcall callback))))
1802
1803 (defun package--ensure-init-file ()
1804 "Ensure that the user's init file calls `package-initialize'."
1805 ;; Don't mess with the init-file from "emacs -Q".
1806 (when user-init-file
1807 (let* ((buffer (find-buffer-visiting user-init-file))
1808 (contains-init
1809 (if buffer
1810 (with-current-buffer buffer
1811 (save-excursion
1812 (save-restriction
1813 (widen)
1814 (goto-char (point-min))
1815 (search-forward "(package-initialize)" nil 'noerror))))
1816 (with-temp-buffer
1817 (insert-file-contents user-init-file)
1818 (goto-char (point-min))
1819 (search-forward "(package-initialize)" nil 'noerror)))))
1820 (unless contains-init
1821 (with-current-buffer (or buffer
1822 (let ((delay-mode-hooks t))
1823 (find-file-noselect user-init-file)))
1824 (save-excursion
1825 (save-restriction
1826 (widen)
1827 (goto-char (point-min))
1828 (insert
1829 ";; Added by Package.el. This must come before configurations of\n"
1830 ";; installed packages. Don't delete this line. If you don't want it,\n"
1831 ";; just comment it out by adding a semicolon to the start of the line.\n"
1832 ";; You may delete these explanatory comments.\n"
1833 "(package-initialize)\n")
1834 (unless (looking-at-p "$")
1835 (insert "\n"))
1836 (let ((file-precious-flag t))
1837 (save-buffer))
1838 (unless buffer
1839 (kill-buffer (current-buffer))))))))))
1840
1841 ;;;###autoload
1842 (defun package-install (pkg &optional dont-select async callback)
1843 "Install the package PKG.
1844 PKG can be a package-desc or the package name of one the available packages
1845 in an archive in `package-archives'. Interactively, prompt for its name.
1846
1847 If called interactively or if DONT-SELECT nil, add PKG to
1848 `package-selected-packages'.
1849 If ASYNC is non-nil, perform the downloads asynchronously.
1850 If CALLBACK is non-nil, call it with no arguments once the
1851 entire operation is done.
1852
1853 If PKG is a package-desc and it is already installed, don't try
1854 to install it but still mark it as selected."
1855 (interactive
1856 (progn
1857 ;; Initialize the package system to get the list of package
1858 ;; symbols for completion.
1859 (unless package--initialized
1860 (package-initialize t))
1861 (unless package-archive-contents
1862 (package-refresh-contents))
1863 (list (intern (completing-read
1864 "Install package: "
1865 (delq nil
1866 (mapcar (lambda (elt)
1867 (unless (package-installed-p (car elt))
1868 (symbol-name (car elt))))
1869 package-archive-contents))
1870 nil t))
1871 nil)))
1872 (let ((name (if (package-desc-p pkg)
1873 (package-desc-name pkg)
1874 pkg)))
1875 (unless (or dont-select (package--user-selected-p name))
1876 (package--save-selected-packages
1877 (cons name package-selected-packages))))
1878 (if-let ((transaction
1879 (if (package-desc-p pkg)
1880 (unless (package-installed-p pkg)
1881 (package-compute-transaction (list pkg)
1882 (package-desc-reqs pkg)))
1883 (package-compute-transaction () (list (list pkg))))))
1884 (package-download-transaction transaction async callback)
1885 (package--message "`%s' is already installed" (package-desc-full-name pkg))))
1886
1887 (defun package-strip-rcs-id (str)
1888 "Strip RCS version ID from the version string STR.
1889 If the result looks like a dotted numeric version, return it.
1890 Otherwise return nil."
1891 (when str
1892 (when (string-match "\\`[ \t]*[$]Revision:[ \t]+" str)
1893 (setq str (substring str (match-end 0))))
1894 (condition-case nil
1895 (if (version-to-list str)
1896 str)
1897 (error nil))))
1898
1899 (declare-function lm-homepage "lisp-mnt" (&optional file))
1900
1901 ;;;###autoload
1902 (defun package-install-from-buffer ()
1903 "Install a package from the current buffer.
1904 The current buffer is assumed to be a single .el or .tar file or
1905 a directory. These must follow the packaging guidelines (see
1906 info node `(elisp)Packaging').
1907
1908 Specially, if current buffer is a directory, the -pkg.el
1909 description file is not mandatory, in which case the information
1910 is derived from the main .el file in the directory.
1911
1912 Downloads and installs required packages as needed."
1913 (interactive)
1914 (let* ((pkg-desc
1915 (cond
1916 ((derived-mode-p 'dired-mode)
1917 ;; This is the only way a package-desc object with a `dir'
1918 ;; desc-kind can be created. Such packages can't be
1919 ;; uploaded or installed from archives, they can only be
1920 ;; installed from local buffers or directories.
1921 (package-dir-info))
1922 ((derived-mode-p 'tar-mode)
1923 (package-tar-file-info))
1924 (t
1925 (package-buffer-info))))
1926 (name (package-desc-name pkg-desc)))
1927 ;; Download and install the dependencies.
1928 (let* ((requires (package-desc-reqs pkg-desc))
1929 (transaction (package-compute-transaction nil requires)))
1930 (package-download-transaction transaction))
1931 ;; Install the package itself.
1932 (package-unpack pkg-desc)
1933 (unless (package--user-selected-p name)
1934 (package--save-selected-packages
1935 (cons name package-selected-packages)))
1936 pkg-desc))
1937
1938 ;;;###autoload
1939 (defun package-install-file (file)
1940 "Install a package from a file.
1941 The file can either be a tar file or an Emacs Lisp file."
1942 (interactive "fPackage file name: ")
1943 (with-temp-buffer
1944 (if (file-directory-p file)
1945 (progn
1946 (setq default-directory file)
1947 (dired-mode))
1948 (insert-file-contents-literally file)
1949 (when (string-match "\\.tar\\'" file) (tar-mode)))
1950 (package-install-from-buffer)))
1951
1952 ;;;###autoload
1953 (defun package-install-selected-packages ()
1954 "Ensure packages in `package-selected-packages' are installed.
1955 If some packages are not installed propose to install them."
1956 (interactive)
1957 ;; We don't need to populate `package-selected-packages' before
1958 ;; using here, because the outcome is the same either way (nothing
1959 ;; gets installed).
1960 (if (not package-selected-packages)
1961 (message "`package-selected-packages' is empty, nothing to install")
1962 (cl-loop for p in package-selected-packages
1963 unless (package-installed-p p)
1964 collect p into lst
1965 finally
1966 (if lst
1967 (when (y-or-n-p
1968 (format "%s packages will be installed:\n%s, proceed?"
1969 (length lst)
1970 (mapconcat #'symbol-name lst ", ")))
1971 (mapc #'package-install lst))
1972 (message "All your packages are already installed")))))
1973
1974 \f
1975 ;;; Package Deletion
1976 (defun package--newest-p (pkg)
1977 "Return t if PKG is the newest package with its name."
1978 (equal (cadr (assq (package-desc-name pkg) package-alist))
1979 pkg))
1980
1981 (defun package-delete (pkg-desc &optional force nosave)
1982 "Delete package PKG-DESC.
1983
1984 Argument PKG-DESC is a full description of package as vector.
1985 When package is used elsewhere as dependency of another package,
1986 refuse deleting it and return an error.
1987 If FORCE is non-nil package will be deleted even if it is used
1988 elsewhere.
1989 If NOSAVE is non-nil, the package is not removed from
1990 `package-selected-packages'."
1991 (let ((dir (package-desc-dir pkg-desc))
1992 (name (package-desc-name pkg-desc))
1993 pkg-used-elsewhere-by)
1994 ;; If the user is trying to delete this package, they definitely
1995 ;; don't want it marked as selected, so we remove it from
1996 ;; `package-selected-packages' even if it can't be deleted.
1997 (when (and (null nosave)
1998 (package--user-selected-p name)
1999 ;; Don't deselect if this is an older version of an
2000 ;; upgraded package.
2001 (package--newest-p pkg-desc))
2002 (package--save-selected-packages (remove name package-selected-packages)))
2003 (cond ((not (string-prefix-p (file-name-as-directory
2004 (expand-file-name package-user-dir))
2005 (expand-file-name dir)))
2006 ;; Don't delete "system" packages.
2007 (error "Package `%s' is a system package, not deleting"
2008 (package-desc-full-name pkg-desc)))
2009 ((and (null force)
2010 (setq pkg-used-elsewhere-by
2011 (package--used-elsewhere-p pkg-desc)))
2012 ;; Don't delete packages used as dependency elsewhere.
2013 (error "Package `%s' is used by `%s' as dependency, not deleting"
2014 (package-desc-full-name pkg-desc)
2015 pkg-used-elsewhere-by))
2016 (t
2017 (delete-directory dir t t)
2018 ;; Remove NAME-VERSION.signed file.
2019 (let ((signed-file (concat dir ".signed")))
2020 (if (file-exists-p signed-file)
2021 (delete-file signed-file)))
2022 ;; Update package-alist.
2023 (let ((pkgs (assq name package-alist)))
2024 (delete pkg-desc pkgs)
2025 (unless (cdr pkgs)
2026 (setq package-alist (delq pkgs package-alist))))
2027 (package--message "Package `%s' deleted." (package-desc-full-name pkg-desc))))))
2028
2029 ;;;###autoload
2030 (defun package-reinstall (pkg)
2031 "Reinstall package PKG.
2032 PKG should be either a symbol, the package name, or a package-desc
2033 object."
2034 (interactive (list (intern (completing-read
2035 "Reinstall package: "
2036 (mapcar #'symbol-name
2037 (mapcar #'car package-alist))))))
2038 (package-delete
2039 (if (package-desc-p pkg) pkg (cadr (assq pkg package-alist)))
2040 'force 'nosave)
2041 (package-install pkg 'dont-select))
2042
2043 ;;;###autoload
2044 (defun package-autoremove ()
2045 "Remove packages that are no more needed.
2046
2047 Packages that are no more needed by other packages in
2048 `package-selected-packages' and their dependencies
2049 will be deleted."
2050 (interactive)
2051 ;; If `package-selected-packages' is nil, it would make no sense to
2052 ;; try to populate it here, because then `package-autoremove' will
2053 ;; do absolutely nothing.
2054 (when (or package-selected-packages
2055 (yes-or-no-p
2056 "`package-selected-packages' is empty! Really remove ALL packages? "))
2057 (let ((removable (package--removable-packages)))
2058 (if removable
2059 (when (y-or-n-p
2060 (format "%s packages will be deleted:\n%s, proceed? "
2061 (length removable)
2062 (mapconcat #'symbol-name removable ", ")))
2063 (mapc (lambda (p)
2064 (package-delete (cadr (assq p package-alist)) t))
2065 removable))
2066 (message "Nothing to autoremove")))))
2067
2068 \f
2069 ;;;; Package description buffer.
2070
2071 ;;;###autoload
2072 (defun describe-package (package)
2073 "Display the full documentation of PACKAGE (a symbol)."
2074 (interactive
2075 (let* ((guess (function-called-at-point)))
2076 (require 'finder-inf nil t)
2077 ;; Load the package list if necessary (but don't activate them).
2078 (unless package--initialized
2079 (package-initialize t))
2080 (let ((packages (append (mapcar 'car package-alist)
2081 (mapcar 'car package-archive-contents)
2082 (mapcar 'car package--builtins))))
2083 (unless (memq guess packages)
2084 (setq guess nil))
2085 (setq packages (mapcar 'symbol-name packages))
2086 (let ((val
2087 (completing-read (if guess
2088 (format "Describe package (default %s): "
2089 guess)
2090 "Describe package: ")
2091 packages nil t nil nil guess)))
2092 (list (intern val))))))
2093 (if (not (or (package-desc-p package) (and package (symbolp package))))
2094 (message "No package specified")
2095 (help-setup-xref (list #'describe-package package)
2096 (called-interactively-p 'interactive))
2097 (with-help-window (help-buffer)
2098 (with-current-buffer standard-output
2099 (describe-package-1 package)))))
2100
2101 (declare-function lm-commentary "lisp-mnt" (&optional file))
2102
2103 (defun describe-package-1 (pkg)
2104 (require 'lisp-mnt)
2105 (let* ((desc (or
2106 (if (package-desc-p pkg) pkg)
2107 (cadr (assq pkg package-alist))
2108 (let ((built-in (assq pkg package--builtins)))
2109 (if built-in
2110 (package--from-builtin built-in)
2111 (cadr (assq pkg package-archive-contents))))))
2112 (name (if desc (package-desc-name desc) pkg))
2113 (pkg-dir (if desc (package-desc-dir desc)))
2114 (reqs (if desc (package-desc-reqs desc)))
2115 (version (if desc (package-desc-version desc)))
2116 (archive (if desc (package-desc-archive desc)))
2117 (extras (and desc (package-desc-extras desc)))
2118 (homepage (cdr (assoc :url extras)))
2119 (keywords (if desc (package-desc--keywords desc)))
2120 (built-in (eq pkg-dir 'builtin))
2121 (installable (and archive (not built-in)))
2122 (status (if desc (package-desc-status desc) "orphan"))
2123 (incompatible-reason (package--incompatible-p desc))
2124 (signed (if desc (package-desc-signed desc))))
2125 (when incompatible-reason
2126 (setq status "incompatible"))
2127 (prin1 name)
2128 (princ " is ")
2129 (princ (if (memq (aref status 0) '(?a ?e ?i ?o ?u)) "an " "a "))
2130 (princ status)
2131 (princ " package.\n\n")
2132
2133 (insert " " (propertize "Status" 'font-lock-face 'bold) ": ")
2134 (cond (built-in
2135 (insert (propertize (capitalize status)
2136 'font-lock-face 'font-lock-builtin-face)
2137 "."))
2138 (pkg-dir
2139 (insert (propertize (if (member status '("unsigned" "dependency"))
2140 "Installed"
2141 (capitalize status)) ;FIXME: Why comment-face?
2142 'font-lock-face 'font-lock-comment-face))
2143 (insert " in `")
2144 ;; Todo: Add button for uninstalling.
2145 (help-insert-xref-button (abbreviate-file-name
2146 (file-name-as-directory pkg-dir))
2147 'help-package-def pkg-dir)
2148 (if (and (package-built-in-p name)
2149 (not (package-built-in-p name version)))
2150 (insert "',\n shadowing a "
2151 (propertize "built-in package"
2152 'font-lock-face 'font-lock-builtin-face))
2153 (insert "'"))
2154 (if signed
2155 (insert ".")
2156 (insert " (unsigned).")))
2157 (incompatible-reason
2158 (insert (propertize "Incompatible" 'face font-lock-warning-face)
2159 " because it depends on ")
2160 (if (stringp incompatible-reason)
2161 (insert "Emacs " incompatible-reason ".")
2162 (insert "uninstallable packages.")))
2163 (installable
2164 (insert (capitalize status))
2165 (insert " from " (format "%s" archive))
2166 (insert " -- ")
2167 (package-make-button
2168 "Install"
2169 'action 'package-install-button-action
2170 'package-desc desc))
2171 (t (insert (capitalize status) ".")))
2172 (insert "\n")
2173 (insert " " (propertize "Archive" 'font-lock-face 'bold)
2174 ": " (or archive "n/a") "\n")
2175 (and version
2176 (insert " "
2177 (propertize "Version" 'font-lock-face 'bold) ": "
2178 (package-version-join version) "\n"))
2179
2180 (setq reqs (if desc (package-desc-reqs desc)))
2181 (when reqs
2182 (insert " " (propertize "Requires" 'font-lock-face 'bold) ": ")
2183 (let ((first t))
2184 (dolist (req reqs)
2185 (let* ((name (car req))
2186 (vers (cadr req))
2187 (text (format "%s-%s" (symbol-name name)
2188 (package-version-join vers)))
2189 (reason (if (and (listp incompatible-reason)
2190 (assq name incompatible-reason))
2191 " (not available)" "")))
2192 (cond (first (setq first nil))
2193 ((>= (+ 2 (current-column) (length text) (length reason))
2194 (window-width))
2195 (insert ",\n "))
2196 (t (insert ", ")))
2197 (help-insert-xref-button text 'help-package name)
2198 (insert reason)))
2199 (insert "\n")))
2200 (insert " " (propertize "Summary" 'font-lock-face 'bold)
2201 ": " (if desc (package-desc-summary desc)) "\n")
2202 (when homepage
2203 (insert " " (propertize "Homepage" 'font-lock-face 'bold) ": ")
2204 (help-insert-xref-button homepage 'help-url homepage)
2205 (insert "\n"))
2206 (when keywords
2207 (insert " " (propertize "Keywords" 'font-lock-face 'bold) ": ")
2208 (dolist (k keywords)
2209 (package-make-button
2210 k
2211 'package-keyword k
2212 'action 'package-keyword-button-action)
2213 (insert " "))
2214 (insert "\n"))
2215 (let* ((all-pkgs (append (cdr (assq name package-alist))
2216 (cdr (assq name package-archive-contents))
2217 (let ((bi (assq name package--builtins)))
2218 (if bi (list (package--from-builtin bi))))))
2219 (other-pkgs (delete desc all-pkgs)))
2220 (when other-pkgs
2221 (insert " " (propertize "Other versions" 'font-lock-face 'bold) ": "
2222 (mapconcat
2223 (lambda (opkg)
2224 (let* ((ov (package-desc-version opkg))
2225 (dir (package-desc-dir opkg))
2226 (from (or (package-desc-archive opkg)
2227 (if (stringp dir) "installed" dir))))
2228 (if (not ov) (format "%s" from)
2229 (format "%s (%s)"
2230 (make-text-button (package-version-join ov) nil
2231 'face 'link
2232 'follow-link t
2233 'action
2234 (lambda (_button)
2235 (describe-package opkg)))
2236 from))))
2237 other-pkgs ", ")
2238 ".\n")))
2239
2240 (insert "\n")
2241
2242 (if built-in
2243 ;; For built-in packages, insert the commentary.
2244 (let ((fn (locate-file (format "%s.el" name) load-path
2245 load-file-rep-suffixes))
2246 (opoint (point)))
2247 (insert (or (lm-commentary fn) ""))
2248 (save-excursion
2249 (goto-char opoint)
2250 (when (re-search-forward "^;;; Commentary:\n" nil t)
2251 (replace-match ""))
2252 (while (re-search-forward "^\\(;+ ?\\)" nil t)
2253 (replace-match ""))))
2254 (let ((readme (expand-file-name (format "%s-readme.txt" name)
2255 package-user-dir))
2256 readme-string)
2257 ;; For elpa packages, try downloading the commentary. If that
2258 ;; fails, try an existing readme file in `package-user-dir'.
2259 (cond ((condition-case nil
2260 (save-excursion
2261 (package--with-work-buffer
2262 (package-archive-base desc)
2263 (format "%s-readme.txt" name)
2264 (save-excursion
2265 (goto-char (point-max))
2266 (unless (bolp)
2267 (insert ?\n)))
2268 (write-region nil nil
2269 (expand-file-name readme package-user-dir)
2270 nil 'silent)
2271 (setq readme-string (buffer-string))
2272 t))
2273 (error nil))
2274 (insert readme-string))
2275 ((file-readable-p readme)
2276 (insert-file-contents readme)
2277 (goto-char (point-max))))))))
2278
2279 (defun package-install-button-action (button)
2280 (let ((pkg-desc (button-get button 'package-desc)))
2281 (when (y-or-n-p (format "Install package `%s'? "
2282 (package-desc-full-name pkg-desc)))
2283 (package-install pkg-desc nil)
2284 (revert-buffer nil t)
2285 (goto-char (point-min)))))
2286
2287 (defun package-keyword-button-action (button)
2288 (let ((pkg-keyword (button-get button 'package-keyword)))
2289 (package-show-package-list t (list pkg-keyword))))
2290
2291 (defun package-make-button (text &rest props)
2292 (let ((button-text (if (display-graphic-p) text (concat "[" text "]")))
2293 (button-face (if (display-graphic-p)
2294 '(:box (:line-width 2 :color "dark grey")
2295 :background "light grey"
2296 :foreground "black")
2297 'link)))
2298 (apply 'insert-text-button button-text 'face button-face 'follow-link t
2299 props)))
2300
2301 \f
2302 ;;;; Package menu mode.
2303
2304 (defvar package-menu-mode-map
2305 (let ((map (make-sparse-keymap))
2306 (menu-map (make-sparse-keymap "Package")))
2307 (set-keymap-parent map tabulated-list-mode-map)
2308 (define-key map "\C-m" 'package-menu-describe-package)
2309 (define-key map "u" 'package-menu-mark-unmark)
2310 (define-key map "\177" 'package-menu-backup-unmark)
2311 (define-key map "d" 'package-menu-mark-delete)
2312 (define-key map "i" 'package-menu-mark-install)
2313 (define-key map "U" 'package-menu-mark-upgrades)
2314 (define-key map "r" 'package-menu-refresh)
2315 (define-key map "f" 'package-menu-filter)
2316 (define-key map "~" 'package-menu-mark-obsolete-for-deletion)
2317 (define-key map "x" 'package-menu-execute)
2318 (define-key map "h" 'package-menu-quick-help)
2319 (define-key map "?" 'package-menu-describe-package)
2320 (define-key map "(" #'package-menu-hide-obsolete)
2321 (define-key map [menu-bar package-menu] (cons "Package" menu-map))
2322 (define-key menu-map [mq]
2323 '(menu-item "Quit" quit-window
2324 :help "Quit package selection"))
2325 (define-key menu-map [s1] '("--"))
2326 (define-key menu-map [mn]
2327 '(menu-item "Next" next-line
2328 :help "Next Line"))
2329 (define-key menu-map [mp]
2330 '(menu-item "Previous" previous-line
2331 :help "Previous Line"))
2332 (define-key menu-map [s2] '("--"))
2333 (define-key menu-map [mu]
2334 '(menu-item "Unmark" package-menu-mark-unmark
2335 :help "Clear any marks on a package and move to the next line"))
2336 (define-key menu-map [munm]
2337 '(menu-item "Unmark Backwards" package-menu-backup-unmark
2338 :help "Back up one line and clear any marks on that package"))
2339 (define-key menu-map [md]
2340 '(menu-item "Mark for Deletion" package-menu-mark-delete
2341 :help "Mark a package for deletion and move to the next line"))
2342 (define-key menu-map [mi]
2343 '(menu-item "Mark for Install" package-menu-mark-install
2344 :help "Mark a package for installation and move to the next line"))
2345 (define-key menu-map [mupgrades]
2346 '(menu-item "Mark Upgradable Packages" package-menu-mark-upgrades
2347 :help "Mark packages that have a newer version for upgrading"))
2348 (define-key menu-map [s3] '("--"))
2349 (define-key menu-map [mf]
2350 '(menu-item "Filter Package List..." package-menu-filter
2351 :help "Filter package selection (q to go back)"))
2352 (define-key menu-map [mg]
2353 '(menu-item "Update Package List" revert-buffer
2354 :help "Update the list of packages"))
2355 (define-key menu-map [mr]
2356 '(menu-item "Refresh Package List" package-menu-refresh
2357 :help "Download the ELPA archive"))
2358 (define-key menu-map [s4] '("--"))
2359 (define-key menu-map [mt]
2360 '(menu-item "Mark Obsolete Packages" package-menu-mark-obsolete-for-deletion
2361 :help "Mark all obsolete packages for deletion"))
2362 (define-key menu-map [mx]
2363 '(menu-item "Execute Actions" package-menu-execute
2364 :help "Perform all the marked actions"))
2365 (define-key menu-map [s5] '("--"))
2366 (define-key menu-map [mh]
2367 '(menu-item "Help" package-menu-quick-help
2368 :help "Show short key binding help for package-menu-mode"))
2369 (define-key menu-map [mc]
2370 '(menu-item "Describe Package" package-menu-describe-package
2371 :help "Display information about this package"))
2372 map)
2373 "Local keymap for `package-menu-mode' buffers.")
2374
2375 (defvar package-menu--new-package-list nil
2376 "List of newly-available packages since `list-packages' was last called.")
2377
2378 (define-derived-mode package-menu-mode tabulated-list-mode "Package Menu"
2379 "Major mode for browsing a list of packages.
2380 Letters do not insert themselves; instead, they are commands.
2381 \\<package-menu-mode-map>
2382 \\{package-menu-mode-map}"
2383 (setq mode-line-process '(package--downloads-in-progress ":Loading"))
2384 (setq tabulated-list-format
2385 `[("Package" 18 package-menu--name-predicate)
2386 ("Version" 13 nil)
2387 ("Status" 10 package-menu--status-predicate)
2388 ,@(if (cdr package-archives)
2389 '(("Archive" 10 package-menu--archive-predicate)))
2390 ("Description" 0 nil)])
2391 (setq tabulated-list-padding 2)
2392 (setq tabulated-list-sort-key (cons "Status" nil))
2393 (add-hook 'tabulated-list-revert-hook 'package-menu--refresh nil t)
2394 (tabulated-list-init-header))
2395
2396 (defmacro package--push (pkg-desc status listname)
2397 "Convenience macro for `package-menu--generate'.
2398 If the alist stored in the symbol LISTNAME lacks an entry for a
2399 package PKG-DESC, add one. The alist is keyed with PKG-DESC."
2400 `(unless (assoc ,pkg-desc ,listname)
2401 ;; FIXME: Should we move status into pkg-desc?
2402 (push (cons ,pkg-desc ,status) ,listname)))
2403
2404 (defvar package-list-unversioned nil
2405 "If non-nil include packages that don't have a version in `list-package'.")
2406
2407 (defvar package-list-unsigned nil
2408 "If non-nil, mention in the list which packages were installed w/o signature.")
2409
2410 (defvar package--emacs-version-list (version-to-list emacs-version)
2411 "`emacs-version', as a list.")
2412
2413 (defun package--incompatible-p (pkg &optional shallow)
2414 "Return non-nil if PKG has no chance of being installable.
2415 PKG is a package-desc object.
2416
2417 If SHALLOW is non-nil, this only checks if PKG depends on a
2418 higher `emacs-version' than the one being used. Otherwise, also
2419 checks the viability of dependencies, according to
2420 `package--compatibility-table'.
2421
2422 If PKG requires an incompatible Emacs version, the return value
2423 is this version (as a string).
2424 If PKG requires incompatible packages, the return value is a list
2425 of these dependencies, similar to the list returned by
2426 `package-desc-reqs'."
2427 (let* ((reqs (package-desc-reqs pkg))
2428 (version (cadr (assq 'emacs reqs))))
2429 (if (and version (version-list-< package--emacs-version-list version))
2430 (package-version-join version)
2431 (unless shallow
2432 (let (out)
2433 (dolist (dep (package-desc-reqs pkg) out)
2434 (let ((dep-name (car dep)))
2435 (unless (eq 'emacs dep-name)
2436 (let ((cv (gethash dep-name package--compatibility-table)))
2437 (when (version-list-< (or cv '(0)) (or (cadr dep) '(0)))
2438 (push dep out)))))))))))
2439
2440 (defun package-desc-status (pkg-desc)
2441 (let* ((name (package-desc-name pkg-desc))
2442 (dir (package-desc-dir pkg-desc))
2443 (lle (assq name package-load-list))
2444 (held (cadr lle))
2445 (version (package-desc-version pkg-desc))
2446 (signed (or (not package-list-unsigned)
2447 (package-desc-signed pkg-desc))))
2448 (cond
2449 ((eq dir 'builtin) "built-in")
2450 ((and lle (null held)) "disabled")
2451 ((stringp held)
2452 (let ((hv (if (stringp held) (version-to-list held))))
2453 (cond
2454 ((version-list-= version hv) "held")
2455 ((version-list-< version hv) "obsolete")
2456 (t "disabled"))))
2457 ((package-built-in-p name version) "obsolete")
2458 ((package--incompatible-p pkg-desc) "incompat")
2459 (dir ;One of the installed packages.
2460 (cond
2461 ((not (file-exists-p (package-desc-dir pkg-desc))) "deleted")
2462 ((eq pkg-desc (cadr (assq name package-alist)))
2463 (if (not signed) "unsigned"
2464 (if (package--user-selected-p name)
2465 "installed" "dependency")))
2466 (t "obsolete")))
2467 (t
2468 (let* ((ins (cadr (assq name package-alist)))
2469 (ins-v (if ins (package-desc-version ins))))
2470 (cond
2471 ;; Installed obsolete packages are handled in the `dir'
2472 ;; clause above. Here we handle available obsolete, which
2473 ;; are displayed depending on `package-menu--hide-obsolete'.
2474 ((and ins (version-list-<= version ins-v)) "avail-obso")
2475 (t
2476 (if (memq name package-menu--new-package-list)
2477 "new" "available"))))))))
2478
2479 (defvar package-menu--hide-obsolete t
2480 "Whether available obsolete packages should be hidden.
2481 Can be toggled with \\<package-menu-mode-map> \\[package-menu-hide-obsolete].
2482 Installed obsolete packages are always displayed.")
2483
2484 (defun package-menu-hide-obsolete ()
2485 "Toggle visibility of obsolete available packages."
2486 (interactive)
2487 (unless (derived-mode-p 'package-menu-mode)
2488 (user-error "The current buffer is not a Package Menu"))
2489 (setq package-menu--hide-obsolete
2490 (not package-menu--hide-obsolete))
2491 (message "%s available-obsolete packages" (if package-menu--hide-obsolete
2492 "Hiding" "Displaying"))
2493 (revert-buffer nil 'no-confirm))
2494
2495 (defun package--remove-hidden (pkg-list)
2496 "Filter PKG-LIST according to `package-archive-priorities'.
2497 PKG-LIST must be a list of package-desc objects sorted by
2498 decreasing version number.
2499 Return a list of packages tied for the highest priority according
2500 to their archives."
2501 (when pkg-list
2502 ;; The first is a variable toggled with
2503 ;; `package-menu-hide-obsolete', the second is a static user
2504 ;; option that defines *what* we hide.
2505 (if (and package-menu--hide-obsolete
2506 package-menu-hide-low-priority)
2507 (let ((max-priority (package-desc-priority (car pkg-list)))
2508 (out (list (pop pkg-list))))
2509 (dolist (p pkg-list (nreverse out))
2510 (let ((priority (package-desc-priority p)))
2511 (cond
2512 ((> priority max-priority)
2513 (setq max-priority priority)
2514 (setq out (list p)))
2515 ;; This assumes pkg-list is sorted by version number.
2516 ((and (= priority max-priority)
2517 (eq package-menu-hide-low-priority 'archive))
2518 (push p out))))))
2519 pkg-list)))
2520
2521 (defun package-menu--refresh (&optional packages keywords)
2522 "Re-populate the `tabulated-list-entries'.
2523 PACKAGES should be nil or t, which means to display all known packages.
2524 KEYWORDS should be nil or a list of keywords."
2525 ;; Construct list of (PKG-DESC . STATUS).
2526 (unless packages (setq packages t))
2527 (let (info-list name)
2528 ;; Installed packages:
2529 (dolist (elt package-alist)
2530 (setq name (car elt))
2531 (when (or (eq packages t) (memq name packages))
2532 (dolist (pkg (cdr elt))
2533 (when (package--has-keyword-p pkg keywords)
2534 (package--push pkg (package-desc-status pkg) info-list)))))
2535
2536 ;; Built-in packages:
2537 (dolist (elt package--builtins)
2538 (setq name (car elt))
2539 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
2540 (package--has-keyword-p (package--from-builtin elt) keywords)
2541 (or package-list-unversioned
2542 (package--bi-desc-version (cdr elt)))
2543 (or (eq packages t) (memq name packages)))
2544 (package--push (package--from-builtin elt) "built-in" info-list)))
2545
2546 ;; Available and disabled packages:
2547 (dolist (elt package-archive-contents)
2548 (setq name (car elt))
2549 (when (or (eq packages t) (memq name packages))
2550 (dolist (pkg (package--remove-hidden (cdr elt)))
2551 ;; Hide available obsolete packages.
2552 (when (and (not (and package-menu--hide-obsolete
2553 (package-installed-p (package-desc-name pkg)
2554 (package-desc-version pkg))))
2555 (package--has-keyword-p pkg keywords))
2556 (package--push pkg (package-desc-status pkg) info-list)))))
2557
2558 ;; Print the result.
2559 (setq tabulated-list-entries
2560 (mapcar #'package-menu--print-info info-list))))
2561
2562 (defun package-all-keywords ()
2563 "Collect all package keywords"
2564 (let ((key-list))
2565 (package--mapc (lambda (desc)
2566 (setq key-list (append (package-desc--keywords desc)
2567 key-list))))
2568 key-list))
2569
2570 (defun package--mapc (function &optional packages)
2571 "Call FUNCTION for all known PACKAGES.
2572 PACKAGES can be nil or t, which means to display all known
2573 packages, or a list of packages.
2574
2575 Built-in packages are converted with `package--from-builtin'."
2576 (unless packages (setq packages t))
2577 (let (name)
2578 ;; Installed packages:
2579 (dolist (elt package-alist)
2580 (setq name (car elt))
2581 (when (or (eq packages t) (memq name packages))
2582 (mapc function (cdr elt))))
2583
2584 ;; Built-in packages:
2585 (dolist (elt package--builtins)
2586 (setq name (car elt))
2587 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
2588 (or package-list-unversioned
2589 (package--bi-desc-version (cdr elt)))
2590 (or (eq packages t) (memq name packages)))
2591 (funcall function (package--from-builtin elt))))
2592
2593 ;; Available and disabled packages:
2594 (dolist (elt package-archive-contents)
2595 (setq name (car elt))
2596 (when (or (eq packages t) (memq name packages))
2597 (dolist (pkg (cdr elt))
2598 ;; Hide obsolete packages.
2599 (unless (package-installed-p (package-desc-name pkg)
2600 (package-desc-version pkg))
2601 (funcall function pkg)))))))
2602
2603 (defun package--has-keyword-p (desc &optional keywords)
2604 "Test if package DESC has any of the given KEYWORDS.
2605 When none are given, the package matches."
2606 (if keywords
2607 (let ((desc-keywords (and desc (package-desc--keywords desc)))
2608 found)
2609 (while (and (not found) keywords)
2610 (let ((k (pop keywords)))
2611 (setq found
2612 (or (string= k (concat "arc:" (package-desc-archive desc)))
2613 (string= k (concat "status:" (package-desc-status desc)))
2614 (member k desc-keywords)))))
2615 found)
2616 t))
2617
2618 (defun package-menu--generate (remember-pos packages &optional keywords)
2619 "Populate the Package Menu.
2620 If REMEMBER-POS is non-nil, keep point on the same entry.
2621 PACKAGES should be t, which means to display all known packages,
2622 or a list of package names (symbols) to display.
2623
2624 With KEYWORDS given, only packages with those keywords are
2625 shown."
2626 (package-menu--refresh packages keywords)
2627 (setf (car (aref tabulated-list-format 0))
2628 (if keywords
2629 (let ((filters (mapconcat 'identity keywords ",")))
2630 (concat "Package[" filters "]"))
2631 "Package"))
2632 (if keywords
2633 (define-key package-menu-mode-map "q" 'package-show-package-list)
2634 (define-key package-menu-mode-map "q" 'quit-window))
2635 (tabulated-list-init-header)
2636 (tabulated-list-print remember-pos))
2637
2638 (defun package-menu--print-info (pkg)
2639 "Return a package entry suitable for `tabulated-list-entries'.
2640 PKG has the form (PKG-DESC . STATUS).
2641 Return (PKG-DESC [NAME VERSION STATUS DOC])."
2642 (let* ((pkg-desc (car pkg))
2643 (status (cdr pkg))
2644 (face (pcase status
2645 (`"built-in" 'font-lock-builtin-face)
2646 (`"available" 'default)
2647 (`"avail-obso" 'font-lock-comment-face)
2648 (`"new" 'bold)
2649 (`"held" 'font-lock-constant-face)
2650 (`"disabled" 'font-lock-warning-face)
2651 (`"installed" 'font-lock-comment-face)
2652 (`"dependency" 'font-lock-comment-face)
2653 (`"unsigned" 'font-lock-warning-face)
2654 (`"incompat" 'font-lock-comment-face)
2655 (_ 'font-lock-warning-face)))) ; obsolete.
2656 (list pkg-desc
2657 `[,(list (symbol-name (package-desc-name pkg-desc))
2658 'face 'link
2659 'follow-link t
2660 'package-desc pkg-desc
2661 'action 'package-menu-describe-package)
2662 ,(propertize (package-version-join
2663 (package-desc-version pkg-desc))
2664 'font-lock-face face)
2665 ,(propertize status 'font-lock-face face)
2666 ,@(if (cdr package-archives)
2667 (list (propertize (or (package-desc-archive pkg-desc) "")
2668 'font-lock-face face)))
2669 ,(propertize (package-desc-summary pkg-desc)
2670 'font-lock-face face)])))
2671
2672 (defvar package-menu--old-archive-contents nil
2673 "`package-archive-contents' before the latest refresh.")
2674
2675 (defun package-menu-refresh ()
2676 "Download the Emacs Lisp package archive.
2677 This fetches the contents of each archive specified in
2678 `package-archives', and then refreshes the package menu."
2679 (interactive)
2680 (unless (derived-mode-p 'package-menu-mode)
2681 (user-error "The current buffer is not a Package Menu"))
2682 (setq package-menu--old-archive-contents package-archive-contents)
2683 (setq package-menu--new-package-list nil)
2684 (package-refresh-contents package-menu-async))
2685
2686 (defun package-menu-describe-package (&optional button)
2687 "Describe the current package.
2688 If optional arg BUTTON is non-nil, describe its associated package."
2689 (interactive)
2690 (let ((pkg-desc (if button (button-get button 'package-desc)
2691 (tabulated-list-get-id))))
2692 (if pkg-desc
2693 (describe-package pkg-desc)
2694 (user-error "No package here"))))
2695
2696 ;; fixme numeric argument
2697 (defun package-menu-mark-delete (&optional _num)
2698 "Mark a package for deletion and move to the next line."
2699 (interactive "p")
2700 (if (member (package-menu-get-status)
2701 '("installed" "dependency" "obsolete" "unsigned"))
2702 (tabulated-list-put-tag "D" t)
2703 (forward-line)))
2704
2705 (defun package-menu-mark-install (&optional _num)
2706 "Mark a package for installation and move to the next line."
2707 (interactive "p")
2708 (if (member (package-menu-get-status) '("available" "avail-obso" "new" "dependency"))
2709 (tabulated-list-put-tag "I" t)
2710 (forward-line)))
2711
2712 (defun package-menu-mark-unmark (&optional _num)
2713 "Clear any marks on a package and move to the next line."
2714 (interactive "p")
2715 (tabulated-list-put-tag " " t))
2716
2717 (defun package-menu-backup-unmark ()
2718 "Back up one line and clear any marks on that package."
2719 (interactive)
2720 (forward-line -1)
2721 (tabulated-list-put-tag " "))
2722
2723 (defun package-menu-mark-obsolete-for-deletion ()
2724 "Mark all obsolete packages for deletion."
2725 (interactive)
2726 (save-excursion
2727 (goto-char (point-min))
2728 (while (not (eobp))
2729 (if (equal (package-menu-get-status) "obsolete")
2730 (tabulated-list-put-tag "D" t)
2731 (forward-line 1)))))
2732
2733 (defvar package--quick-help-keys
2734 '(("install," "delete," "unmark," ("execute" . 1))
2735 ("next," "previous")
2736 ("refresh-contents," "g-redisplay," "filter," "(-toggle-obsolete" "help")))
2737
2738 (defun package--prettify-quick-help-key (desc)
2739 "Prettify DESC to be displayed as a help menu."
2740 (if (listp desc)
2741 (if (listp (cdr desc))
2742 (mapconcat #'package--prettify-quick-help-key desc " ")
2743 (let ((place (cdr desc))
2744 (out (car desc)))
2745 ;; (setq out (propertize out 'face 'paradox-comment-face))
2746 (add-text-properties place (1+ place)
2747 '(face (bold font-lock-function-name-face))
2748 out)
2749 out))
2750 (package--prettify-quick-help-key (cons desc 0))))
2751
2752 (defun package-menu-quick-help ()
2753 "Show short key binding help for `package-menu-mode'.
2754 The full list of keys can be viewed with \\[describe-mode]."
2755 (interactive)
2756 (message (mapconcat #'package--prettify-quick-help-key
2757 package--quick-help-keys "\n")))
2758
2759 (define-obsolete-function-alias
2760 'package-menu-view-commentary 'package-menu-describe-package "24.1")
2761
2762 (defun package-menu-get-status ()
2763 (let* ((id (tabulated-list-get-id))
2764 (entry (and id (assq id tabulated-list-entries))))
2765 (if entry
2766 (aref (cadr entry) 2)
2767 "")))
2768
2769 (defun package-archive-priority (archive)
2770 "Return the priority of ARCHIVE.
2771
2772 The archive priorities are specified in
2773 `package-archive-priorities'. If not given there, the priority
2774 defaults to 0."
2775 (or (cdr (assoc archive package-archive-priorities))
2776 0))
2777
2778 (defun package-desc-priority-version (pkg-desc)
2779 "Return the version PKG-DESC with the archive priority prepended.
2780
2781 This allows for easy comparison of package versions from
2782 different archives if archive priorities are meant to be taken in
2783 consideration."
2784 (cons (package-desc-priority pkg-desc)
2785 (package-desc-version pkg-desc)))
2786
2787 (defun package-menu--find-upgrades ()
2788 (let (installed available upgrades)
2789 ;; Build list of installed/available packages in this buffer.
2790 (dolist (entry tabulated-list-entries)
2791 ;; ENTRY is (PKG-DESC [NAME VERSION STATUS DOC])
2792 (let ((pkg-desc (car entry))
2793 (status (aref (cadr entry) 2)))
2794 (cond ((member status '("installed" "dependency" "unsigned"))
2795 (push pkg-desc installed))
2796 ((member status '("available" "new"))
2797 (setq available (package--append-to-alist pkg-desc available))))))
2798 ;; Loop through list of installed packages, finding upgrades.
2799 (dolist (pkg-desc installed)
2800 (let* ((name (package-desc-name pkg-desc))
2801 (avail-pkg (cadr (assq name available))))
2802 (and avail-pkg
2803 (version-list-< (package-desc-priority-version pkg-desc)
2804 (package-desc-priority-version avail-pkg))
2805 (push (cons name avail-pkg) upgrades))))
2806 upgrades))
2807
2808 (defun package-menu-mark-upgrades ()
2809 "Mark all upgradable packages in the Package Menu.
2810 For each installed package with a newer version available, place
2811 an (I)nstall flag on the available version and a (D)elete flag on
2812 the installed version. A subsequent \\[package-menu-execute]
2813 call will upgrade the package."
2814 (interactive)
2815 (unless (derived-mode-p 'package-menu-mode)
2816 (error "The current buffer is not a Package Menu"))
2817 (let ((upgrades (package-menu--find-upgrades)))
2818 (if (null upgrades)
2819 (message "No packages to upgrade.")
2820 (widen)
2821 (save-excursion
2822 (goto-char (point-min))
2823 (while (not (eobp))
2824 (let* ((pkg-desc (tabulated-list-get-id))
2825 (upgrade (cdr (assq (package-desc-name pkg-desc) upgrades))))
2826 (cond ((null upgrade)
2827 (forward-line 1))
2828 ((equal pkg-desc upgrade)
2829 (package-menu-mark-install))
2830 (t
2831 (package-menu-mark-delete))))))
2832 (message "%d package%s marked for upgrading."
2833 (length upgrades)
2834 (if (= (length upgrades) 1) "" "s")))))
2835
2836 (defun package-menu--list-to-prompt (packages)
2837 "Return a string listing PACKAGES that's usable in a prompt.
2838 PACKAGES is a list of `package-desc' objects.
2839 Formats the returned string to be usable in a minibuffer
2840 prompt (see `package-menu--prompt-transaction-p')."
2841 (cond
2842 ;; None
2843 ((not packages) "")
2844 ;; More than 1
2845 ((cdr packages)
2846 (format "these %d packages (%s)"
2847 (length packages)
2848 (mapconcat #'package-desc-full-name packages ", ")))
2849 ;; Exactly 1
2850 (t (format "package `%s'"
2851 (package-desc-full-name (car packages))))))
2852
2853 (defun package-menu--prompt-transaction-p (install delete)
2854 "Prompt the user about installing INSTALL and deleting DELETE.
2855 INSTALL and DELETE are lists of `package-desc'. Either may be
2856 nil, but not both."
2857 (let* ((upg (cl-intersection install delete :key #'package-desc-name))
2858 (ins (cl-set-difference install upg :key #'package-desc-name))
2859 (del (cl-set-difference delete upg :key #'package-desc-name)))
2860 (y-or-n-p
2861 (concat
2862 (when del "Delete ")
2863 (package-menu--list-to-prompt del)
2864 (when (and del ins)
2865 (if upg "; " "; and "))
2866 (when ins "Install ")
2867 (package-menu--list-to-prompt ins)
2868 (when (and upg (or ins del)) "; and ")
2869 (when upg "Upgrade ")
2870 (package-menu--list-to-prompt upg)
2871 "? "))))
2872
2873 (defun package-menu--perform-transaction (install-list delete-list &optional async)
2874 "Install packages in INSTALL-LIST and delete DELETE-LIST.
2875 If ASYNC is non-nil, perform the installation downloads
2876 asynchronously."
2877 ;; While there are packages to install, call `package-install' on
2878 ;; the next one and defer deletion to the callback function.
2879 (if install-list
2880 (let* ((pkg (car install-list))
2881 (rest (cdr install-list))
2882 ;; Don't mark as selected if it's a new version of an
2883 ;; installed package.
2884 (dont-mark (and (not (package-installed-p pkg))
2885 (package-installed-p
2886 (package-desc-name pkg)))))
2887 (package-install
2888 pkg dont-mark async
2889 (lambda () (package-menu--perform-transaction rest delete-list async))))
2890 ;; Once there are no more packages to install, proceed to
2891 ;; deletion.
2892 (let ((package--silence async))
2893 (dolist (elt (package--sort-by-dependence delete-list))
2894 (condition-case-unless-debug err
2895 (package-delete elt)
2896 (error (message (cadr err)))))
2897 (when package-selected-packages
2898 (when-let ((removable (package--removable-packages)))
2899 (package--message "These %d packages are no longer needed, type `M-x package-autoremove' to remove them (%s)"
2900 (length removable)
2901 (mapconcat #'symbol-name removable ", ")))))
2902 (message "Transaction done")
2903 (package-menu--post-refresh)))
2904
2905 (defun package-menu-execute (&optional noquery)
2906 "Perform marked Package Menu actions.
2907 Packages marked for installation are downloaded and installed;
2908 packages marked for deletion are removed.
2909 Optional argument NOQUERY non-nil means do not ask the user to confirm."
2910 (interactive)
2911 (unless (derived-mode-p 'package-menu-mode)
2912 (error "The current buffer is not in Package Menu mode"))
2913 (let (install-list delete-list cmd pkg-desc)
2914 (save-excursion
2915 (goto-char (point-min))
2916 (while (not (eobp))
2917 (setq cmd (char-after))
2918 (unless (eq cmd ?\s)
2919 ;; This is the key PKG-DESC.
2920 (setq pkg-desc (tabulated-list-get-id))
2921 (cond ((eq cmd ?D)
2922 (push pkg-desc delete-list))
2923 ((eq cmd ?I)
2924 (push pkg-desc install-list))))
2925 (forward-line)))
2926 (unless (or delete-list install-list)
2927 (user-error "No operations specified"))
2928 (when (or noquery
2929 (package-menu--prompt-transaction-p install-list delete-list))
2930 (message "Transaction started")
2931 ;; This calls `package-menu--generate' after everything's done.
2932 (package-menu--perform-transaction
2933 install-list delete-list package-menu-async))))
2934
2935 (defun package-menu--version-predicate (A B)
2936 (let ((vA (or (aref (cadr A) 1) '(0)))
2937 (vB (or (aref (cadr B) 1) '(0))))
2938 (if (version-list-= vA vB)
2939 (package-menu--name-predicate A B)
2940 (version-list-< vA vB))))
2941
2942 (defun package-menu--status-predicate (A B)
2943 (let ((sA (aref (cadr A) 2))
2944 (sB (aref (cadr B) 2)))
2945 (cond ((string= sA sB)
2946 (package-menu--name-predicate A B))
2947 ((string= sA "new") t)
2948 ((string= sB "new") nil)
2949 ((string-prefix-p "avail" sA)
2950 (if (string-prefix-p "avail" sB)
2951 (package-menu--name-predicate A B)
2952 t))
2953 ((string-prefix-p "avail" sB) nil)
2954 ((string= sA "installed") t)
2955 ((string= sB "installed") nil)
2956 ((string= sA "dependency") t)
2957 ((string= sB "dependency") nil)
2958 ((string= sA "unsigned") t)
2959 ((string= sB "unsigned") nil)
2960 ((string= sA "held") t)
2961 ((string= sB "held") nil)
2962 ((string= sA "built-in") t)
2963 ((string= sB "built-in") nil)
2964 ((string= sA "obsolete") t)
2965 ((string= sB "obsolete") nil)
2966 ((string= sA "incompat") t)
2967 ((string= sB "incompat") nil)
2968 (t (string< sA sB)))))
2969
2970 (defun package-menu--description-predicate (A B)
2971 (let ((dA (aref (cadr A) 3))
2972 (dB (aref (cadr B) 3)))
2973 (if (string= dA dB)
2974 (package-menu--name-predicate A B)
2975 (string< dA dB))))
2976
2977 (defun package-menu--name-predicate (A B)
2978 (string< (symbol-name (package-desc-name (car A)))
2979 (symbol-name (package-desc-name (car B)))))
2980
2981 (defun package-menu--archive-predicate (A B)
2982 (string< (or (package-desc-archive (car A)) "")
2983 (or (package-desc-archive (car B)) "")))
2984
2985 (defun package-menu--populate-new-package-list ()
2986 "Decide which packages are new in `package-archives-contents'.
2987 Store this list in `package-menu--new-package-list'."
2988 ;; Find which packages are new.
2989 (when package-menu--old-archive-contents
2990 (dolist (elt package-archive-contents)
2991 (unless (assq (car elt) package-menu--old-archive-contents)
2992 (push (car elt) package-menu--new-package-list)))
2993 (setq package-menu--old-archive-contents nil)))
2994
2995 (defun package-menu--find-and-notify-upgrades ()
2996 "Notify the user of upgradable packages."
2997 (when-let ((upgrades (package-menu--find-upgrades)))
2998 (message "%d package%s can be upgraded; type `%s' to mark %s for upgrading."
2999 (length upgrades)
3000 (if (= (length upgrades) 1) "" "s")
3001 (substitute-command-keys "\\[package-menu-mark-upgrades]")
3002 (if (= (length upgrades) 1) "it" "them"))))
3003
3004 (defun package-menu--post-refresh ()
3005 "Check for new packages, revert the *Packages* buffer, and check for upgrades.
3006 This function is called after `package-refresh-contents' and
3007 after `package-menu--perform-transaction'."
3008 (package-menu--populate-new-package-list)
3009 (let ((buf (get-buffer "*Packages*")))
3010 (when (buffer-live-p buf)
3011 (with-current-buffer buf
3012 (revert-buffer nil 'noconfirm))))
3013 (package-menu--find-and-notify-upgrades))
3014
3015 ;;;###autoload
3016 (defun list-packages (&optional no-fetch)
3017 "Display a list of packages.
3018 This first fetches the updated list of packages before
3019 displaying, unless a prefix argument NO-FETCH is specified.
3020 The list is displayed in a buffer named `*Packages*'."
3021 (interactive "P")
3022 (require 'finder-inf nil t)
3023 ;; Initialize the package system if necessary.
3024 (unless package--initialized
3025 (package-initialize t))
3026 ;; Integrate the package-menu with updating the archives.
3027 (add-hook 'package--post-download-archives-hook
3028 #'package-menu--post-refresh)
3029
3030 ;; Generate the Package Menu.
3031 (let ((buf (get-buffer-create "*Packages*")))
3032 (with-current-buffer buf
3033 (package-menu-mode)
3034
3035 ;; Fetch the remote list of packages.
3036 (unless no-fetch (package-menu-refresh))
3037
3038 ;; If we're not async, this would be redundant.
3039 (when package-menu-async
3040 (package-menu--generate nil t)))
3041 ;; The package menu buffer has keybindings. If the user types
3042 ;; `M-x list-packages', that suggests it should become current.
3043 (switch-to-buffer buf)))
3044
3045 ;;;###autoload
3046 (defalias 'package-list-packages 'list-packages)
3047
3048 ;; Used in finder.el
3049 (defun package-show-package-list (&optional packages keywords)
3050 "Display PACKAGES in a *Packages* buffer.
3051 This is similar to `list-packages', but it does not fetch the
3052 updated list of packages, and it only displays packages with
3053 names in PACKAGES (which should be a list of symbols).
3054
3055 When KEYWORDS are given, only packages with those KEYWORDS are
3056 shown."
3057 (interactive)
3058 (require 'finder-inf nil t)
3059 (let* ((buf (get-buffer-create "*Packages*"))
3060 (win (get-buffer-window buf)))
3061 (with-current-buffer buf
3062 (package-menu-mode)
3063 (package-menu--generate nil packages keywords))
3064 (if win
3065 (select-window win)
3066 (switch-to-buffer buf))))
3067
3068 ;; package-menu--generate rebinds "q" on the fly, so we have to
3069 ;; hard-code the binding in the doc-string here.
3070 (defun package-menu-filter (keyword)
3071 "Filter the *Packages* buffer.
3072 Show only those items that relate to the specified KEYWORD.
3073 KEYWORD can be a string or a list of strings. If it is a list, a
3074 package will be displayed if it matches any of the keywords.
3075 Interactively, it is a list of strings separated by commas.
3076
3077 To restore the full package list, type `q'."
3078 (interactive
3079 (list (completing-read-multiple
3080 "Keywords (comma separated): " (package-all-keywords))))
3081 (package-show-package-list t (if (stringp keyword)
3082 (list keyword)
3083 keyword)))
3084
3085 (defun package-list-packages-no-fetch ()
3086 "Display a list of packages.
3087 Does not fetch the updated list of packages before displaying.
3088 The list is displayed in a buffer named `*Packages*'."
3089 (interactive)
3090 (list-packages t))
3091
3092 (provide 'package)
3093
3094 ;;; package.el ends here