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