]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/package.el
text-quoting-style in emacs-lisp diagnostics
[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 (declare-function lm-maintainer "lisp-mnt" (&optional file))
964 (declare-function lm-authors "lisp-mnt" (&optional file))
965
966 (defun package-buffer-info ()
967 "Return a `package-desc' describing the package in the current buffer.
968
969 If the buffer does not contain a conforming package, signal an
970 error. If there is a package, narrow the buffer to the file's
971 boundaries."
972 (goto-char (point-min))
973 (unless (re-search-forward "^;;; \\([^ ]*\\)\\.el ---[ \t]*\\(.*?\\)[ \t]*\\(-\\*-.*-\\*-[ \t]*\\)?$" nil t)
974 (error "Package lacks a file header"))
975 (let ((file-name (match-string-no-properties 1))
976 (desc (match-string-no-properties 2))
977 (start (line-beginning-position)))
978 (unless (search-forward (concat ";;; " file-name ".el ends here"))
979 (error "Package lacks a terminating comment"))
980 ;; Try to include a trailing newline.
981 (forward-line)
982 (narrow-to-region start (point))
983 (require 'lisp-mnt)
984 ;; Use some headers we've invented to drive the process.
985 (let* ((requires-str (lm-header "package-requires"))
986 ;; Prefer Package-Version; if defined, the package author
987 ;; probably wants us to use it. Otherwise try Version.
988 (pkg-version
989 (or (package-strip-rcs-id (lm-header "package-version"))
990 (package-strip-rcs-id (lm-header "version"))))
991 (homepage (lm-homepage)))
992 (unless pkg-version
993 (error
994 "Package lacks a \"Version\" or \"Package-Version\" header"))
995 (package-desc-from-define
996 file-name pkg-version desc
997 (if requires-str
998 (package--prepare-dependencies
999 (package-read-from-string requires-str)))
1000 :kind 'single
1001 :url homepage
1002 :maintainer (lm-maintainer)
1003 :authors (lm-authors)))))
1004
1005 (defun package--read-pkg-desc (kind)
1006 "Read a `define-package' form in current buffer.
1007 Return the pkg-desc, with desc-kind set to KIND."
1008 (goto-char (point-min))
1009 (unwind-protect
1010 (let* ((pkg-def-parsed (read (current-buffer)))
1011 (pkg-desc
1012 (when (eq (car pkg-def-parsed) 'define-package)
1013 (apply #'package-desc-from-define
1014 (append (cdr pkg-def-parsed))))))
1015 (when pkg-desc
1016 (setf (package-desc-kind pkg-desc) kind)
1017 pkg-desc))))
1018
1019 (declare-function tar-get-file-descriptor "tar-mode" (file))
1020 (declare-function tar--extract "tar-mode" (descriptor))
1021
1022 (defun package-tar-file-info ()
1023 "Find package information for a tar file.
1024 The return result is a `package-desc'."
1025 (cl-assert (derived-mode-p 'tar-mode))
1026 (let* ((dir-name (file-name-directory
1027 (tar-header-name (car tar-parse-info))))
1028 (desc-file (package--description-file dir-name))
1029 (tar-desc (tar-get-file-descriptor (concat dir-name desc-file))))
1030 (unless tar-desc
1031 (error "No package descriptor file found"))
1032 (with-current-buffer (tar--extract tar-desc)
1033 (unwind-protect
1034 (or (package--read-pkg-desc 'tar)
1035 (error "Can't find define-package in %s"
1036 (tar-header-name tar-desc)))
1037 (kill-buffer (current-buffer))))))
1038
1039 (defun package-dir-info ()
1040 "Find package information for a directory.
1041 The return result is a `package-desc'."
1042 (cl-assert (derived-mode-p 'dired-mode))
1043 (let* ((desc-file (package--description-file default-directory)))
1044 (if (file-readable-p desc-file)
1045 (with-temp-buffer
1046 (insert-file-contents desc-file)
1047 (package--read-pkg-desc 'dir))
1048 (let ((files (directory-files default-directory t "\\.el\\'" t))
1049 info)
1050 (while files
1051 (with-temp-buffer
1052 (insert-file-contents (pop files))
1053 ;; When we find the file with the data,
1054 (when (setq info (ignore-errors (package-buffer-info)))
1055 ;; stop looping,
1056 (setq files nil)
1057 ;; set the 'dir kind,
1058 (setf (package-desc-kind info) 'dir))))
1059 ;; and return the info.
1060 info))))
1061
1062 \f
1063 ;;; Communicating with Archives
1064 ;; Set of low-level functions for communicating with archives and
1065 ;; signature checking.
1066 (defun package--write-file-no-coding (file-name)
1067 (let ((buffer-file-coding-system 'no-conversion))
1068 (write-region (point-min) (point-max) file-name nil 'silent)))
1069
1070 (declare-function url-http-file-exists-p "url-http" (url))
1071
1072 (defun package--archive-file-exists-p (location file)
1073 (let ((http (string-match "\\`https?:" location)))
1074 (if http
1075 (progn
1076 (require 'url-http)
1077 (url-http-file-exists-p (concat location file)))
1078 (file-exists-p (expand-file-name file location)))))
1079
1080 (declare-function epg-make-context "epg"
1081 (&optional protocol armor textmode include-certs
1082 cipher-algorithm
1083 digest-algorithm
1084 compress-algorithm))
1085 (declare-function epg-verify-string "epg" (context signature
1086 &optional signed-text))
1087 (declare-function epg-context-result-for "epg" (context name))
1088 (declare-function epg-signature-status "epg" (signature) t)
1089 (declare-function epg-signature-to-string "epg" (signature))
1090
1091 (defun package--display-verify-error (context sig-file)
1092 (unless (equal (epg-context-error-output context) "")
1093 (with-output-to-temp-buffer "*Error*"
1094 (with-current-buffer standard-output
1095 (if (epg-context-result-for context 'verify)
1096 (insert (format "Failed to verify signature %s:\n" sig-file)
1097 (mapconcat #'epg-signature-to-string
1098 (epg-context-result-for context 'verify)
1099 "\n"))
1100 (insert (format "Error while verifying signature %s:\n" sig-file)))
1101 (insert "\nCommand output:\n" (epg-context-error-output context))))))
1102
1103 (defmacro package--with-work-buffer (location file &rest body)
1104 "Run BODY in a buffer containing the contents of FILE at LOCATION.
1105 LOCATION is the base location of a package archive, and should be
1106 one of the URLs (or file names) specified in `package-archives'.
1107 FILE is the name of a file relative to that base location.
1108
1109 This macro retrieves FILE from LOCATION into a temporary buffer,
1110 and evaluates BODY while that buffer is current. This work
1111 buffer is killed afterwards. Return the last value in BODY."
1112 (declare (indent 2) (debug t))
1113 `(with-temp-buffer
1114 (if (string-match-p "\\`https?:" ,location)
1115 (url-insert-file-contents (concat ,location ,file))
1116 (unless (file-name-absolute-p ,location)
1117 (error "Archive location %s is not an absolute file name"
1118 ,location))
1119 (insert-file-contents (expand-file-name ,file ,location)))
1120 ,@body))
1121
1122 (defmacro package--with-work-buffer-async (location file async &rest body)
1123 "Run BODY in a buffer containing the contents of FILE at LOCATION.
1124 If ASYNC is non-nil, and if it is possible, run BODY
1125 asynchronously. If an error is encountered and ASYNC is a
1126 function, call it with no arguments (instead of executing BODY).
1127 If it returns non-nil, or if it wasn't a function, propagate the
1128 error.
1129
1130 For a description of the other arguments see
1131 `package--with-work-buffer'."
1132 (declare (indent 3) (debug t))
1133 (macroexp-let2* macroexp-copyable-p
1134 ((async-1 async)
1135 (file-1 file)
1136 (location-1 location))
1137 `(if (or (not ,async-1)
1138 (not (string-match-p "\\`https?:" ,location-1)))
1139 (package--with-work-buffer ,location-1 ,file-1 ,@body)
1140 ;; This `condition-case' is to catch connection errors.
1141 (condition-case error-signal
1142 (url-retrieve (concat ,location-1 ,file-1)
1143 ;; This is to catch execution errors.
1144 (lambda (status)
1145 (condition-case error-signal
1146 (progn
1147 (when-let ((er (plist-get status :error)))
1148 (error "Error retrieving: %s %S" (concat ,location-1 ,file-1) er))
1149 (goto-char (point-min))
1150 (unless (search-forward "\n\n" nil 'noerror)
1151 (error "Invalid url response in buffer %s"
1152 (current-buffer)))
1153 (delete-region (point-min) (point))
1154 ,@body
1155 (kill-buffer (current-buffer)))
1156 (error (when (if (functionp ,async-1) (funcall ,async-1) t)
1157 (signal (car error-signal) (cdr error-signal))))))
1158 nil
1159 'silent)
1160 (error (when (if (functionp ,async-1) (funcall ,async-1) t)
1161 (message "Error contacting: %s" (concat ,location-1 ,file-1))
1162 (signal (car error-signal) (cdr error-signal))))))))
1163
1164 (defun package--check-signature-content (content string &optional sig-file)
1165 "Check signature CONTENT against STRING.
1166 SIG-FILE is the name of the signature file, used when signaling
1167 errors."
1168 (let* ((context (epg-make-context 'OpenPGP))
1169 (homedir (expand-file-name "gnupg" package-user-dir)))
1170 (setf (epg-context-home-directory context) homedir)
1171 (condition-case error
1172 (epg-verify-string context content string)
1173 (error (package--display-verify-error context sig-file)
1174 (signal (car error) (cdr error))))
1175 (let (good-signatures had-fatal-error)
1176 ;; The .sig file may contain multiple signatures. Success if one
1177 ;; of the signatures is good.
1178 (dolist (sig (epg-context-result-for context 'verify))
1179 (if (eq (epg-signature-status sig) 'good)
1180 (push sig good-signatures)
1181 ;; If package-check-signature is allow-unsigned, don't
1182 ;; signal error when we can't verify signature because of
1183 ;; missing public key. Other errors are still treated as
1184 ;; fatal (bug#17625).
1185 (unless (and (eq package-check-signature 'allow-unsigned)
1186 (eq (epg-signature-status sig) 'no-pubkey))
1187 (setq had-fatal-error t))))
1188 (when (and (null good-signatures) had-fatal-error)
1189 (package--display-verify-error context sig-file)
1190 (error "Failed to verify signature %s" sig-file))
1191 good-signatures)))
1192
1193 (defun package--check-signature (location file &optional string async callback)
1194 "Check signature of the current buffer.
1195 Download the signature file from LOCATION by appending \".sig\"
1196 to FILE.
1197 GnuPG keyring is located under \"gnupg\" in `package-user-dir'.
1198 STRING is the string to verify, it defaults to `buffer-string'.
1199 If ASYNC is non-nil, the download of the signature file is
1200 done asynchronously.
1201
1202 If the signature is verified and CALLBACK was provided, CALLBACK
1203 is `funcall'ed with the list of good signatures as argument (the
1204 list can be empty). If the signatures file is not found,
1205 CALLBACK is called with no arguments."
1206 (let ((sig-file (concat file ".sig"))
1207 (string (or string (buffer-string))))
1208 (condition-case nil
1209 (package--with-work-buffer-async
1210 location sig-file (when async (or callback t))
1211 (let ((sig (package--check-signature-content
1212 (buffer-string) string sig-file)))
1213 (when callback (funcall callback sig))
1214 sig))
1215 (file-error (funcall callback)))))
1216
1217 \f
1218 ;;; Packages on Archives
1219 ;; The following variables store information about packages available
1220 ;; from archives. The most important of these is
1221 ;; `package-archive-contents' which is initially populated by the
1222 ;; function `package-read-all-archive-contents' from a cache on disk.
1223 ;; The `package-initialize' command is also closely related to this
1224 ;; section, but it has its own section.
1225 (defconst package-archive-version 1
1226 "Version number of the package archive understood by this file.
1227 Lower version numbers than this will probably be understood as well.")
1228
1229 ;; We don't prime the cache since it tends to get out of date.
1230 (defvar package-archive-contents nil
1231 "Cache of the contents of the Emacs Lisp Package Archive.
1232 This is an alist mapping package names (symbols) to
1233 non-empty lists of `package-desc' structures.")
1234 (put 'package-archive-contents 'risky-local-variable t)
1235
1236 (defvar package--compatibility-table nil
1237 "Hash table connecting package names to their compatibility.
1238 Each key is a symbol, the name of a package.
1239
1240 The value is either nil, representing an incompatible package, or
1241 a version list, representing the highest compatible version of
1242 that package which is available.
1243
1244 A package is considered incompatible if it requires an Emacs
1245 version higher than the one being used. To check for package
1246 \(in)compatibility, don't read this table directly, use
1247 `package--incompatible-p' which also checks dependencies.")
1248
1249 (defun package--build-compatibility-table ()
1250 "Build `package--compatibility-table' with `package--mapc'."
1251 ;; Initialize the list of built-ins.
1252 (require 'finder-inf nil t)
1253 ;; Build compat table.
1254 (setq package--compatibility-table (make-hash-table :test 'eq))
1255 (package--mapc #'package--add-to-compatibility-table))
1256
1257 (defun package--add-to-compatibility-table (pkg)
1258 "If PKG is compatible (without dependencies), add to the compatibility table.
1259 PKG is a package-desc object.
1260 Only adds if its version is higher than what's already stored in
1261 the table."
1262 (unless (package--incompatible-p pkg 'shallow)
1263 (let* ((name (package-desc-name pkg))
1264 (version (or (package-desc-version pkg) '(0)))
1265 (table-version (gethash name package--compatibility-table)))
1266 (when (or (not table-version)
1267 (version-list-< table-version version))
1268 (puthash name version package--compatibility-table)))))
1269
1270 ;; Package descriptor objects used inside the "archive-contents" file.
1271 ;; Changing this defstruct implies changing the format of the
1272 ;; "archive-contents" files.
1273 (cl-defstruct (package--ac-desc
1274 (:constructor package-make-ac-desc (version reqs summary kind extras))
1275 (:copier nil)
1276 (:type vector))
1277 version reqs summary kind extras)
1278
1279 (defun package--append-to-alist (pkg-desc alist)
1280 "Append an entry for PKG-DESC to the start of ALIST and return it.
1281 This entry takes the form (`package-desc-name' PKG-DESC).
1282
1283 If ALIST already has an entry with this name, destructively add
1284 PKG-DESC to the cdr of this entry instead, sorted by version
1285 number."
1286 (let* ((name (package-desc-name pkg-desc))
1287 (priority-version (package-desc-priority-version pkg-desc))
1288 (existing-packages (assq name alist)))
1289 (if (not existing-packages)
1290 (cons (list name pkg-desc)
1291 alist)
1292 (while (if (and (cdr existing-packages)
1293 (version-list-< priority-version
1294 (package-desc-priority-version
1295 (cadr existing-packages))))
1296 (setq existing-packages (cdr existing-packages))
1297 (push pkg-desc (cdr existing-packages))
1298 nil))
1299 alist)))
1300
1301 (defun package--add-to-archive-contents (package archive)
1302 "Add the PACKAGE from the given ARCHIVE if necessary.
1303 PACKAGE should have the form (NAME . PACKAGE--AC-DESC).
1304 Also, add the originating archive to the `package-desc' structure."
1305 (let* ((name (car package))
1306 (version (package--ac-desc-version (cdr package)))
1307 (pkg-desc
1308 (package-desc-create
1309 :name name
1310 :version version
1311 :reqs (package--ac-desc-reqs (cdr package))
1312 :summary (package--ac-desc-summary (cdr package))
1313 :kind (package--ac-desc-kind (cdr package))
1314 :archive archive
1315 :extras (and (> (length (cdr package)) 4)
1316 ;; Older archive-contents files have only 4
1317 ;; elements here.
1318 (package--ac-desc-extras (cdr package)))))
1319 (pinned-to-archive (assoc name package-pinned-packages)))
1320 ;; Skip entirely if pinned to another archive.
1321 (when (not (and pinned-to-archive
1322 (not (equal (cdr pinned-to-archive) archive))))
1323 (setq package-archive-contents
1324 (package--append-to-alist pkg-desc package-archive-contents)))))
1325
1326 (defun package--read-archive-file (file)
1327 "Re-read archive file FILE, if it exists.
1328 Will return the data from the file, or nil if the file does not exist.
1329 Will throw an error if the archive version is too new."
1330 (let ((filename (expand-file-name file package-user-dir)))
1331 (when (file-exists-p filename)
1332 (with-temp-buffer
1333 (let ((coding-system-for-read 'utf-8))
1334 (insert-file-contents filename))
1335 (let ((contents (read (current-buffer))))
1336 (if (> (car contents) package-archive-version)
1337 (error "Package archive version %d is higher than %d"
1338 (car contents) package-archive-version))
1339 (cdr contents))))))
1340
1341 (defun package-read-archive-contents (archive)
1342 "Re-read archive contents for ARCHIVE.
1343 If successful, set the variable `package-archive-contents'.
1344 If the archive version is too new, signal an error."
1345 ;; Version 1 of 'archive-contents' is identical to our internal
1346 ;; representation.
1347 (let* ((contents-file (format "archives/%s/archive-contents" archive))
1348 (contents (package--read-archive-file contents-file)))
1349 (when contents
1350 (dolist (package contents)
1351 (package--add-to-archive-contents package archive)))))
1352
1353 (defun package-read-all-archive-contents ()
1354 "Re-read `archive-contents', if it exists.
1355 If successful, set `package-archive-contents'."
1356 (setq package-archive-contents nil)
1357 (dolist (archive package-archives)
1358 (package-read-archive-contents (car archive))))
1359
1360 ;;;; Package Initialize
1361 ;; A bit of a milestone. This brings together some of the above
1362 ;; sections and populates all relevant lists of packages from contents
1363 ;; available on disk.
1364 (defvar package--initialized nil)
1365
1366 (defvar package--init-file-ensured nil
1367 "Whether we know the init file has package-initialize.")
1368
1369 ;;;###autoload
1370 (defun package-initialize (&optional no-activate)
1371 "Load Emacs Lisp packages, and activate them.
1372 The variable `package-load-list' controls which packages to load.
1373 If optional arg NO-ACTIVATE is non-nil, don't activate packages.
1374 If `user-init-file' does not mention `(package-initialize)', add
1375 it to the file."
1376 (interactive)
1377 (setq package-alist nil)
1378 (if (equal user-init-file load-file-name)
1379 ;; If `package-initialize' is being called as part of loading
1380 ;; the init file, it's obvious we don't need to ensure-init.
1381 (setq package--init-file-ensured t)
1382 (package--ensure-init-file))
1383 (package-load-all-descriptors)
1384 (package-read-all-archive-contents)
1385 (unless no-activate
1386 (dolist (elt package-alist)
1387 (package-activate (car elt))))
1388 (setq package--initialized t)
1389 ;; This uses `package--mapc' so it must be called after
1390 ;; `package--initialized' is t.
1391 (package--build-compatibility-table))
1392
1393 \f
1394 ;;;; Populating `package-archive-contents' from archives
1395 ;; This subsection populates the variables listed above from the
1396 ;; actual archives, instead of from a local cache.
1397 (defvar package--downloads-in-progress nil
1398 "List of in-progress asynchronous downloads.")
1399
1400 (declare-function epg-check-configuration "epg-config"
1401 (config &optional minimum-version))
1402 (declare-function epg-configuration "epg-config" ())
1403 (declare-function epg-import-keys-from-file "epg" (context keys))
1404
1405 ;;;###autoload
1406 (defun package-import-keyring (&optional file)
1407 "Import keys from FILE."
1408 (interactive "fFile: ")
1409 (setq file (expand-file-name file))
1410 (let ((context (epg-make-context 'OpenPGP))
1411 (homedir (expand-file-name "gnupg" package-user-dir)))
1412 (with-file-modes 448
1413 (make-directory homedir t))
1414 (setf (epg-context-home-directory context) homedir)
1415 (message "Importing %s..." (file-name-nondirectory file))
1416 (epg-import-keys-from-file context file)
1417 (message "Importing %s...done" (file-name-nondirectory file))))
1418
1419 (defvar package--post-download-archives-hook nil
1420 "Hook run after the archive contents are downloaded.
1421 Don't run this hook directly. It is meant to be run as part of
1422 `package--update-downloads-in-progress'.")
1423 (put 'package--post-download-archives-hook 'risky-local-variable t)
1424
1425 (defun package--update-downloads-in-progress (entry)
1426 "Remove ENTRY from `package--downloads-in-progress'.
1427 Once it's empty, run `package--post-download-archives-hook'."
1428 ;; Keep track of the downloading progress.
1429 (setq package--downloads-in-progress
1430 (remove entry package--downloads-in-progress))
1431 ;; If this was the last download, run the hook.
1432 (unless package--downloads-in-progress
1433 (package-read-all-archive-contents)
1434 (package--build-compatibility-table)
1435 ;; We message before running the hook, so the hook can give
1436 ;; messages as well.
1437 (message "Package refresh done")
1438 (run-hooks 'package--post-download-archives-hook)))
1439
1440 (defun package--download-one-archive (archive file &optional async)
1441 "Retrieve an archive file FILE from ARCHIVE, and cache it.
1442 ARCHIVE should be a cons cell of the form (NAME . LOCATION),
1443 similar to an entry in `package-alist'. Save the cached copy to
1444 \"archives/NAME/FILE\" in `package-user-dir'."
1445 (package--with-work-buffer-async (cdr archive) file async
1446 (let* ((location (cdr archive))
1447 (name (car archive))
1448 (content (buffer-string))
1449 (dir (expand-file-name (format "archives/%s" name) package-user-dir))
1450 (local-file (expand-file-name file dir)))
1451 (when (listp (read-from-string content))
1452 (make-directory dir t)
1453 (if (or (not package-check-signature)
1454 (member archive package-unsigned-archives))
1455 ;; If we don't care about the signature, save the file and
1456 ;; we're done.
1457 (progn (write-region content nil local-file nil 'silent)
1458 (package--update-downloads-in-progress archive))
1459 ;; If we care, check it (perhaps async) and *then* write the file.
1460 (package--check-signature
1461 location file content async
1462 ;; This function will be called after signature checking.
1463 (lambda (&optional good-sigs)
1464 (unless (or good-sigs (eq package-check-signature 'allow-unsigned))
1465 ;; Even if the sig fails, this download is done, so
1466 ;; remove it from the in-progress list.
1467 (package--update-downloads-in-progress archive)
1468 (error "Unsigned archive ‘%s’" name))
1469 ;; Write out the archives file.
1470 (write-region content nil local-file nil 'silent)
1471 ;; Write out good signatures into archive-contents.signed file.
1472 (when good-sigs
1473 (write-region (mapconcat #'epg-signature-to-string good-sigs "\n")
1474 nil (concat local-file ".signed") nil 'silent))
1475 (package--update-downloads-in-progress archive)
1476 ;; If we got this far, either everything worked or we don't mind
1477 ;; not signing, so tell `package--with-work-buffer-async' to not
1478 ;; propagate errors.
1479 nil)))))))
1480
1481 (defun package--download-and-read-archives (&optional async)
1482 "Download descriptions of all `package-archives' and read them.
1483 This populates `package-archive-contents'. If ASYNC is non-nil,
1484 perform the downloads asynchronously."
1485 ;; The downloaded archive contents will be read as part of
1486 ;; `package--update-downloads-in-progress'.
1487 (dolist (archive package-archives)
1488 (cl-pushnew archive package--downloads-in-progress
1489 :test #'equal))
1490 (dolist (archive package-archives)
1491 (condition-case-unless-debug nil
1492 (package--download-one-archive
1493 archive "archive-contents"
1494 ;; Called if the async download fails
1495 (when async
1496 ;; The t at the end means to propagate connection errors.
1497 (lambda () (package--update-downloads-in-progress archive) t)))
1498 (error (message "Failed to download ‘%s’ archive."
1499 (car archive))))))
1500
1501 ;;;###autoload
1502 (defun package-refresh-contents (&optional async)
1503 "Download descriptions of all configured ELPA packages.
1504 For each archive configured in the variable `package-archives',
1505 inform Emacs about the latest versions of all packages it offers,
1506 and make them available for download.
1507 Optional argument ASYNC specifies whether to perform the
1508 downloads in the background."
1509 (interactive)
1510 (unless (file-exists-p package-user-dir)
1511 (make-directory package-user-dir t))
1512 (let ((default-keyring (expand-file-name "package-keyring.gpg"
1513 data-directory))
1514 (inhibit-message async))
1515 (when (and package-check-signature (file-exists-p default-keyring))
1516 (condition-case-unless-debug error
1517 (progn
1518 (epg-check-configuration (epg-configuration))
1519 (package-import-keyring default-keyring))
1520 (error (message "Cannot import default keyring: %S" (cdr error))))))
1521 (package--download-and-read-archives async))
1522
1523 \f
1524 ;;; Dependency Management
1525 ;; Calculating the full transaction necessary for an installation,
1526 ;; keeping track of which packages were installed strictly as
1527 ;; dependencies, and determining which packages cannot be removed
1528 ;; because they are dependencies.
1529 (defun package-compute-transaction (packages requirements &optional seen)
1530 "Return a list of packages to be installed, including PACKAGES.
1531 PACKAGES should be a list of `package-desc'.
1532
1533 REQUIREMENTS should be a list of additional requirements; each
1534 element in this list should have the form (PACKAGE VERSION-LIST),
1535 where PACKAGE is a package name and VERSION-LIST is the required
1536 version of that package.
1537
1538 This function recursively computes the requirements of the
1539 packages in REQUIREMENTS, and returns a list of all the packages
1540 that must be installed. Packages that are already installed are
1541 not included in this list.
1542
1543 SEEN is used internally to detect infinite recursion."
1544 ;; FIXME: We really should use backtracking to explore the whole
1545 ;; search space (e.g. if foo require bar-1.3, and bar-1.4 requires toto-1.1
1546 ;; whereas bar-1.3 requires toto-1.0 and the user has put a hold on toto-1.0:
1547 ;; the current code might fail to see that it could install foo by using the
1548 ;; older bar-1.3).
1549 (dolist (elt requirements)
1550 (let* ((next-pkg (car elt))
1551 (next-version (cadr elt))
1552 (already ()))
1553 (dolist (pkg packages)
1554 (if (eq next-pkg (package-desc-name pkg))
1555 (setq already pkg)))
1556 (when already
1557 (if (version-list-<= next-version (package-desc-version already))
1558 ;; `next-pkg' is already in `packages', but its position there
1559 ;; means it might be installed too late: remove it from there, so
1560 ;; we re-add it (along with its dependencies) at an earlier place
1561 ;; below (bug#16994).
1562 (if (memq already seen) ;Avoid inf-loop on dependency cycles.
1563 (message "Dependency cycle going through %S"
1564 (package-desc-full-name already))
1565 (setq packages (delq already packages))
1566 (setq already nil))
1567 (error "Need package ‘%s-%s’, but only %s is being installed"
1568 next-pkg (package-version-join next-version)
1569 (package-version-join (package-desc-version already)))))
1570 (cond
1571 (already nil)
1572 ((package-installed-p next-pkg next-version) nil)
1573
1574 (t
1575 ;; A package is required, but not installed. It might also be
1576 ;; blocked via `package-load-list'.
1577 (let ((pkg-descs (cdr (assq next-pkg package-archive-contents)))
1578 (found nil)
1579 (found-something nil)
1580 (problem nil))
1581 (while (and pkg-descs (not found))
1582 (let* ((pkg-desc (pop pkg-descs))
1583 (version (package-desc-version pkg-desc))
1584 (disabled (package-disabled-p next-pkg version)))
1585 (cond
1586 ((version-list-< version next-version)
1587 ;; pkg-descs is sorted by priority, not version, so
1588 ;; don't error just yet.
1589 (unless found-something
1590 (setq found-something (package-version-join version))))
1591 (disabled
1592 (unless problem
1593 (setq problem
1594 (if (stringp disabled)
1595 (format "Package ‘%s’ held at version %s, but version %s required"
1596 next-pkg disabled
1597 (package-version-join next-version))
1598 (format "Required package ‘%s’ is disabled"
1599 next-pkg)))))
1600 (t (setq found pkg-desc)))))
1601 (unless found
1602 (cond
1603 (problem (error "%s" problem))
1604 (found-something
1605 (error "Need package ‘%s-%s’, but only %s is available"
1606 next-pkg (package-version-join next-version)
1607 found-something))
1608 (t (error "Package ‘%s-%s’ is unavailable"
1609 next-pkg (package-version-join next-version)))))
1610 (setq packages
1611 (package-compute-transaction (cons found packages)
1612 (package-desc-reqs found)
1613 (cons found seen))))))))
1614 packages)
1615
1616 (defun package--find-non-dependencies ()
1617 "Return a list of installed packages which are not dependencies.
1618 Finds all packages in `package-alist' which are not dependencies
1619 of any other packages.
1620 Used to populate `package-selected-packages'."
1621 (let ((dep-list
1622 (delete-dups
1623 (apply #'append
1624 (mapcar (lambda (p) (mapcar #'car (package-desc-reqs (cadr p))))
1625 package-alist)))))
1626 (cl-loop for p in package-alist
1627 for name = (car p)
1628 unless (memq name dep-list)
1629 collect name)))
1630
1631 (defun package--save-selected-packages (&optional value)
1632 "Set and save `package-selected-packages' to VALUE."
1633 (when value
1634 (setq package-selected-packages value))
1635 (if after-init-time
1636 (let ((save-silently inhibit-message))
1637 (customize-save-variable 'package-selected-packages package-selected-packages))
1638 (add-hook 'after-init-hook #'package--save-selected-packages)))
1639
1640 (defun package--user-selected-p (pkg)
1641 "Return non-nil if PKG is a package was installed by the user.
1642 PKG is a package name.
1643 This looks into `package-selected-packages', populating it first
1644 if it is still empty."
1645 (unless (consp package-selected-packages)
1646 (package--save-selected-packages (package--find-non-dependencies)))
1647 (memq pkg package-selected-packages))
1648
1649 (defun package--get-deps (pkg &optional only)
1650 (let* ((pkg-desc (cadr (assq pkg package-alist)))
1651 (direct-deps (cl-loop for p in (package-desc-reqs pkg-desc)
1652 for name = (car p)
1653 when (assq name package-alist)
1654 collect name))
1655 (indirect-deps (unless (eq only 'direct)
1656 (delete-dups
1657 (cl-loop for p in direct-deps
1658 append (package--get-deps p))))))
1659 (cl-case only
1660 (direct direct-deps)
1661 (separate (list direct-deps indirect-deps))
1662 (indirect indirect-deps)
1663 (t (delete-dups (append direct-deps indirect-deps))))))
1664
1665 (defun package--removable-packages ()
1666 "Return a list of names of packages no longer needed.
1667 These are packages which are neither contained in
1668 `package-selected-packages' nor a dependency of one that is."
1669 (let ((needed (cl-loop for p in package-selected-packages
1670 if (assq p package-alist)
1671 ;; `p' and its dependencies are needed.
1672 append (cons p (package--get-deps p)))))
1673 (cl-loop for p in (mapcar #'car package-alist)
1674 unless (memq p needed)
1675 collect p)))
1676
1677 (defun package--used-elsewhere-p (pkg-desc &optional pkg-list all)
1678 "Non-nil if PKG-DESC is a dependency of a package in PKG-LIST.
1679 Return the first package found in PKG-LIST of which PKG is a
1680 dependency. If ALL is non-nil, return all such packages instead.
1681
1682 When not specified, PKG-LIST defaults to `package-alist'
1683 with PKG-DESC entry removed."
1684 (unless (string= (package-desc-status pkg-desc) "obsolete")
1685 (let* ((pkg (package-desc-name pkg-desc))
1686 (alist (or pkg-list
1687 (remove (assq pkg package-alist)
1688 package-alist))))
1689 (if all
1690 (cl-loop for p in alist
1691 if (assq pkg (package-desc-reqs (cadr p)))
1692 collect (cadr p))
1693 (cl-loop for p in alist thereis
1694 (and (assq pkg (package-desc-reqs (cadr p)))
1695 (cadr p)))))))
1696
1697 (defun package--sort-deps-in-alist (package only)
1698 "Return a list of dependencies for PACKAGE sorted by dependency.
1699 PACKAGE is included as the first element of the returned list.
1700 ONLY is an alist associating package names to package objects.
1701 Only these packages will be in the return value an their cdrs are
1702 destructively set to nil in ONLY."
1703 (let ((out))
1704 (dolist (dep (package-desc-reqs package))
1705 (when-let ((cell (assq (car dep) only))
1706 (dep-package (cdr-safe cell)))
1707 (setcdr cell nil)
1708 (setq out (append (package--sort-deps-in-alist dep-package only)
1709 out))))
1710 (cons package out)))
1711
1712 (defun package--sort-by-dependence (package-list)
1713 "Return PACKAGE-LIST sorted by dependence.
1714 That is, any element of the returned list is guaranteed to not
1715 directly depend on any elements that come before it.
1716
1717 PACKAGE-LIST is a list of package-desc objects.
1718 Indirect dependencies are guaranteed to be returned in order only
1719 if all the in-between dependencies are also in PACKAGE-LIST."
1720 (let ((alist (mapcar (lambda (p) (cons (package-desc-name p) p)) package-list))
1721 out-list)
1722 (dolist (cell alist out-list)
1723 ;; `package--sort-deps-in-alist' destructively changes alist, so
1724 ;; some cells might already be empty. We check this here.
1725 (when-let ((pkg-desc (cdr cell)))
1726 (setcdr cell nil)
1727 (setq out-list
1728 (append (package--sort-deps-in-alist pkg-desc alist)
1729 out-list))))))
1730
1731 \f
1732 ;;; Installation Functions
1733 ;; As opposed to the previous section (which listed some underlying
1734 ;; functions necessary for installation), this one contains the actual
1735 ;; functions that install packages. The package itself can be
1736 ;; installed in a variety of ways (archives, buffer, file), but
1737 ;; requirements (dependencies) are always satisfied by looking in
1738 ;; `package-archive-contents'.
1739 (defun package-archive-base (desc)
1740 "Return the archive containing the package NAME."
1741 (cdr (assoc (package-desc-archive desc) package-archives)))
1742
1743 (defun package-install-from-archive (pkg-desc)
1744 "Download and install a tar package."
1745 ;; This won't happen, unless the archive is doing something wrong.
1746 (when (eq (package-desc-kind pkg-desc) 'dir)
1747 (error "Can't install directory package from archive"))
1748 (let* ((location (package-archive-base pkg-desc))
1749 (file (concat (package-desc-full-name pkg-desc)
1750 (package-desc-suffix pkg-desc))))
1751 (package--with-work-buffer location file
1752 (if (or (not package-check-signature)
1753 (member (package-desc-archive pkg-desc)
1754 package-unsigned-archives))
1755 ;; If we don't care about the signature, unpack and we're
1756 ;; done.
1757 (let ((save-silently t))
1758 (package-unpack pkg-desc))
1759 ;; If we care, check it and *then* write the file.
1760 (let ((content (buffer-string)))
1761 (package--check-signature
1762 location file content nil
1763 ;; This function will be called after signature checking.
1764 (lambda (&optional good-sigs)
1765 (unless (or good-sigs (eq package-check-signature 'allow-unsigned))
1766 ;; Even if the sig fails, this download is done, so
1767 ;; remove it from the in-progress list.
1768 (error "Unsigned package: ‘%s’"
1769 (package-desc-name pkg-desc)))
1770 ;; Signature checked, unpack now.
1771 (with-temp-buffer (insert content)
1772 (let ((save-silently t))
1773 (package-unpack pkg-desc)))
1774 ;; Here the package has been installed successfully, mark it as
1775 ;; signed if appropriate.
1776 (when good-sigs
1777 ;; Write out good signatures into NAME-VERSION.signed file.
1778 (write-region (mapconcat #'epg-signature-to-string good-sigs "\n")
1779 nil
1780 (expand-file-name
1781 (concat (package-desc-full-name pkg-desc) ".signed")
1782 package-user-dir)
1783 nil 'silent)
1784 ;; Update the old pkg-desc which will be shown on the description buffer.
1785 (setf (package-desc-signed pkg-desc) t)
1786 ;; Update the new (activated) pkg-desc as well.
1787 (when-let ((pkg-descs (cdr (assq (package-desc-name pkg-desc) package-alist))))
1788 (setf (package-desc-signed (car pkg-descs)) t))))))))))
1789
1790 (defun package-installed-p (package &optional min-version)
1791 "Return true if PACKAGE, of MIN-VERSION or newer, is installed.
1792 If PACKAGE is a symbol, it is the package name and MIN-VERSION
1793 should be a version list.
1794
1795 If PACKAGE is a package-desc object, MIN-VERSION is ignored."
1796 (unless package--initialized (error "package.el is not yet initialized!"))
1797 (if (package-desc-p package)
1798 (let ((dir (package-desc-dir package)))
1799 (and (stringp dir)
1800 (file-exists-p dir)))
1801 (or
1802 (let ((pkg-descs (cdr (assq package package-alist))))
1803 (and pkg-descs
1804 (version-list-<= min-version
1805 (package-desc-version (car pkg-descs)))))
1806 ;; Also check built-in packages.
1807 (package-built-in-p package min-version))))
1808
1809 (defun package-download-transaction (packages)
1810 "Download and install all the packages in PACKAGES.
1811 PACKAGES should be a list of package-desc.
1812 This function assumes that all package requirements in
1813 PACKAGES are satisfied, i.e. that PACKAGES is computed
1814 using `package-compute-transaction'."
1815 (mapc #'package-install-from-archive packages))
1816
1817 (defun package--ensure-init-file ()
1818 "Ensure that the user's init file has `package-initialize'.
1819 `package-initialize' doesn't have to be called, as long as it is
1820 present somewhere in the file, even as a comment. If it is not,
1821 add a call to it along with some explanatory comments."
1822 ;; Don't mess with the init-file from "emacs -Q".
1823 (when (and (stringp user-init-file)
1824 (not package--init-file-ensured)
1825 (file-readable-p user-init-file)
1826 (file-writable-p user-init-file))
1827 (let* ((buffer (find-buffer-visiting user-init-file))
1828 (contains-init
1829 (if buffer
1830 (with-current-buffer buffer
1831 (save-excursion
1832 (save-restriction
1833 (widen)
1834 (goto-char (point-min))
1835 (search-forward "(package-initialize)" nil 'noerror))))
1836 ;; Don't visit the file if we don't have to.
1837 (with-temp-buffer
1838 (insert-file-contents user-init-file)
1839 (goto-char (point-min))
1840 (search-forward "(package-initialize)" nil 'noerror)))))
1841 (unless contains-init
1842 (with-current-buffer (or buffer
1843 (let ((delay-mode-hooks t))
1844 (find-file-noselect user-init-file)))
1845 (save-excursion
1846 (save-restriction
1847 (widen)
1848 (goto-char (point-min))
1849 (while (and (looking-at-p "[[:blank:]]*\\(;\\|$\\)")
1850 (not (eobp)))
1851 (forward-line 1))
1852 (insert
1853 "\n"
1854 ";; Added by Package.el. This must come before configurations of\n"
1855 ";; installed packages. Don't delete this line. If you don't want it,\n"
1856 ";; just comment it out by adding a semicolon to the start of the line.\n"
1857 ";; You may delete these explanatory comments.\n"
1858 "(package-initialize)\n")
1859 (unless (looking-at-p "$")
1860 (insert "\n"))
1861 (let ((file-precious-flag t))
1862 (save-buffer))
1863 (unless buffer
1864 (kill-buffer (current-buffer)))))))))
1865 (setq package--init-file-ensured t))
1866
1867 ;;;###autoload
1868 (defun package-install (pkg &optional dont-select)
1869 "Install the package PKG.
1870 PKG can be a package-desc or the package name of one the available packages
1871 in an archive in `package-archives'. Interactively, prompt for its name.
1872
1873 If called interactively or if DONT-SELECT nil, add PKG to
1874 `package-selected-packages'.
1875
1876 If PKG is a package-desc and it is already installed, don't try
1877 to install it but still mark it as selected."
1878 (interactive
1879 (progn
1880 ;; Initialize the package system to get the list of package
1881 ;; symbols for completion.
1882 (unless package--initialized
1883 (package-initialize t))
1884 (unless package-archive-contents
1885 (package-refresh-contents))
1886 (list (intern (completing-read
1887 "Install package: "
1888 (delq nil
1889 (mapcar (lambda (elt)
1890 (unless (package-installed-p (car elt))
1891 (symbol-name (car elt))))
1892 package-archive-contents))
1893 nil t))
1894 nil)))
1895 (add-hook 'post-command-hook #'package-menu--post-refresh)
1896 (let ((name (if (package-desc-p pkg)
1897 (package-desc-name pkg)
1898 pkg)))
1899 (unless (or dont-select (package--user-selected-p name))
1900 (package--save-selected-packages
1901 (cons name package-selected-packages))))
1902 (if-let ((transaction
1903 (if (package-desc-p pkg)
1904 (unless (package-installed-p pkg)
1905 (package-compute-transaction (list pkg)
1906 (package-desc-reqs pkg)))
1907 (package-compute-transaction () (list (list pkg))))))
1908 (package-download-transaction transaction)
1909 (message "‘%s’ is already installed" (package-desc-full-name pkg))))
1910
1911 (defun package-strip-rcs-id (str)
1912 "Strip RCS version ID from the version string STR.
1913 If the result looks like a dotted numeric version, return it.
1914 Otherwise return nil."
1915 (when str
1916 (when (string-match "\\`[ \t]*[$]Revision:[ \t]+" str)
1917 (setq str (substring str (match-end 0))))
1918 (ignore-errors
1919 (if (version-to-list str) str))))
1920
1921 (declare-function lm-homepage "lisp-mnt" (&optional file))
1922
1923 ;;;###autoload
1924 (defun package-install-from-buffer ()
1925 "Install a package from the current buffer.
1926 The current buffer is assumed to be a single .el or .tar file or
1927 a directory. These must follow the packaging guidelines (see
1928 info node `(elisp)Packaging').
1929
1930 Specially, if current buffer is a directory, the -pkg.el
1931 description file is not mandatory, in which case the information
1932 is derived from the main .el file in the directory.
1933
1934 Downloads and installs required packages as needed."
1935 (interactive)
1936 (let* ((pkg-desc
1937 (cond
1938 ((derived-mode-p 'dired-mode)
1939 ;; This is the only way a package-desc object with a `dir'
1940 ;; desc-kind can be created. Such packages can't be
1941 ;; uploaded or installed from archives, they can only be
1942 ;; installed from local buffers or directories.
1943 (package-dir-info))
1944 ((derived-mode-p 'tar-mode)
1945 (package-tar-file-info))
1946 (t
1947 (package-buffer-info))))
1948 (name (package-desc-name pkg-desc)))
1949 ;; Download and install the dependencies.
1950 (let* ((requires (package-desc-reqs pkg-desc))
1951 (transaction (package-compute-transaction nil requires)))
1952 (package-download-transaction transaction))
1953 ;; Install the package itself.
1954 (package-unpack pkg-desc)
1955 (unless (package--user-selected-p name)
1956 (package--save-selected-packages
1957 (cons name package-selected-packages)))
1958 pkg-desc))
1959
1960 ;;;###autoload
1961 (defun package-install-file (file)
1962 "Install a package from a file.
1963 The file can either be a tar file, an Emacs Lisp file, or a
1964 directory."
1965 (interactive "fPackage file name: ")
1966 (with-temp-buffer
1967 (if (file-directory-p file)
1968 (progn
1969 (setq default-directory file)
1970 (dired-mode))
1971 (insert-file-contents-literally file)
1972 (when (string-match "\\.tar\\'" file) (tar-mode)))
1973 (package-install-from-buffer)))
1974
1975 ;;;###autoload
1976 (defun package-install-selected-packages ()
1977 "Ensure packages in `package-selected-packages' are installed.
1978 If some packages are not installed propose to install them."
1979 (interactive)
1980 ;; We don't need to populate `package-selected-packages' before
1981 ;; using here, because the outcome is the same either way (nothing
1982 ;; gets installed).
1983 (if (not package-selected-packages)
1984 (message "‘package-selected-packages’ is empty, nothing to install")
1985 (cl-loop for p in package-selected-packages
1986 unless (package-installed-p p)
1987 collect p into lst
1988 finally
1989 (if lst
1990 (when (y-or-n-p
1991 (format "%s packages will be installed:\n%s, proceed?"
1992 (length lst)
1993 (mapconcat #'symbol-name lst ", ")))
1994 (mapc #'package-install lst))
1995 (message "All your packages are already installed")))))
1996
1997 \f
1998 ;;; Package Deletion
1999 (defun package--newest-p (pkg)
2000 "Return t if PKG is the newest package with its name."
2001 (equal (cadr (assq (package-desc-name pkg) package-alist))
2002 pkg))
2003
2004 (defun package-delete (pkg-desc &optional force nosave)
2005 "Delete package PKG-DESC.
2006
2007 Argument PKG-DESC is a full description of package as vector.
2008 Interactively, prompt the user for the package name and version.
2009
2010 When package is used elsewhere as dependency of another package,
2011 refuse deleting it and return an error.
2012 If prefix argument FORCE is non-nil, package will be deleted even
2013 if it is used elsewhere.
2014 If NOSAVE is non-nil, the package is not removed from
2015 `package-selected-packages'."
2016 (interactive
2017 (progn
2018 ;; Initialize the package system to get the list of package
2019 ;; symbols for completion.
2020 (unless package--initialized
2021 (package-initialize t))
2022 (let* ((package-table
2023 (mapcar
2024 (lambda (p) (cons (package-desc-full-name p) p))
2025 (delq nil
2026 (mapcar (lambda (p) (unless (package-built-in-p p) p))
2027 (apply #'append (mapcar #'cdr package-alist))))))
2028 (package-name (completing-read "Delete package: "
2029 (mapcar #'car package-table)
2030 nil t)))
2031 (list (cdr (assoc package-name package-table))
2032 current-prefix-arg nil))))
2033 (let ((dir (package-desc-dir pkg-desc))
2034 (name (package-desc-name pkg-desc))
2035 pkg-used-elsewhere-by)
2036 ;; If the user is trying to delete this package, they definitely
2037 ;; don't want it marked as selected, so we remove it from
2038 ;; `package-selected-packages' even if it can't be deleted.
2039 (when (and (null nosave)
2040 (package--user-selected-p name)
2041 ;; Don't deselect if this is an older version of an
2042 ;; upgraded package.
2043 (package--newest-p pkg-desc))
2044 (package--save-selected-packages (remove name package-selected-packages)))
2045 (cond ((not (string-prefix-p (file-name-as-directory
2046 (expand-file-name package-user-dir))
2047 (expand-file-name dir)))
2048 ;; Don't delete "system" packages.
2049 (error "Package ‘%s’ is a system package, not deleting"
2050 (package-desc-full-name pkg-desc)))
2051 ((and (null force)
2052 (setq pkg-used-elsewhere-by
2053 (package--used-elsewhere-p pkg-desc)))
2054 ;; Don't delete packages used as dependency elsewhere.
2055 (error "Package ‘%s’ is used by ‘%s’ as dependency, not deleting"
2056 (package-desc-full-name pkg-desc)
2057 (package-desc-name pkg-used-elsewhere-by)))
2058 (t
2059 (add-hook 'post-command-hook #'package-menu--post-refresh)
2060 (delete-directory dir t t)
2061 ;; Remove NAME-VERSION.signed file.
2062 (let ((signed-file (concat dir ".signed")))
2063 (if (file-exists-p signed-file)
2064 (delete-file signed-file)))
2065 ;; Update package-alist.
2066 (let ((pkgs (assq name package-alist)))
2067 (delete pkg-desc pkgs)
2068 (unless (cdr pkgs)
2069 (setq package-alist (delq pkgs package-alist))))
2070 (message "Package ‘%s’ deleted." (package-desc-full-name pkg-desc))))))
2071
2072 ;;;###autoload
2073 (defun package-reinstall (pkg)
2074 "Reinstall package PKG.
2075 PKG should be either a symbol, the package name, or a package-desc
2076 object."
2077 (interactive (list (intern (completing-read
2078 "Reinstall package: "
2079 (mapcar #'symbol-name
2080 (mapcar #'car package-alist))))))
2081 (package-delete
2082 (if (package-desc-p pkg) pkg (cadr (assq pkg package-alist)))
2083 'force 'nosave)
2084 (package-install pkg 'dont-select))
2085
2086 ;;;###autoload
2087 (defun package-autoremove ()
2088 "Remove packages that are no more needed.
2089
2090 Packages that are no more needed by other packages in
2091 `package-selected-packages' and their dependencies
2092 will be deleted."
2093 (interactive)
2094 ;; If `package-selected-packages' is nil, it would make no sense to
2095 ;; try to populate it here, because then `package-autoremove' will
2096 ;; do absolutely nothing.
2097 (when (or package-selected-packages
2098 (yes-or-no-p
2099 "‘package-selected-packages’ is empty! Really remove ALL packages? "))
2100 (let ((removable (package--removable-packages)))
2101 (if removable
2102 (when (y-or-n-p
2103 (format "%s packages will be deleted:\n%s, proceed? "
2104 (length removable)
2105 (mapconcat #'symbol-name removable ", ")))
2106 (mapc (lambda (p)
2107 (package-delete (cadr (assq p package-alist)) t))
2108 removable))
2109 (message "Nothing to autoremove")))))
2110
2111 \f
2112 ;;;; Package description buffer.
2113
2114 ;;;###autoload
2115 (defun describe-package (package)
2116 "Display the full documentation of PACKAGE (a symbol)."
2117 (interactive
2118 (let* ((guess (or (function-called-at-point)
2119 (symbol-at-point))))
2120 (require 'finder-inf nil t)
2121 ;; Load the package list if necessary (but don't activate them).
2122 (unless package--initialized
2123 (package-initialize t))
2124 (let ((packages (append (mapcar 'car package-alist)
2125 (mapcar 'car package-archive-contents)
2126 (mapcar 'car package--builtins))))
2127 (unless (memq guess packages)
2128 (setq guess nil))
2129 (setq packages (mapcar 'symbol-name packages))
2130 (let ((val
2131 (completing-read (if guess
2132 (format "Describe package (default %s): "
2133 guess)
2134 "Describe package: ")
2135 packages nil t nil nil (when guess
2136 (symbol-name guess)))))
2137 (list (intern val))))))
2138 (if (not (or (package-desc-p package) (and package (symbolp package))))
2139 (message "No package specified")
2140 (help-setup-xref (list #'describe-package package)
2141 (called-interactively-p 'interactive))
2142 (with-help-window (help-buffer)
2143 (with-current-buffer standard-output
2144 (describe-package-1 package)))))
2145
2146 (defface package-help-section-name-face
2147 '((t :inherit (bold font-lock-function-name-face)))
2148 "Face used on section names in package description buffers."
2149 :version "25.1")
2150
2151 (defun package--print-help-section (name &rest strings)
2152 "Print \"NAME: \", right aligned to the 13th column.
2153 If more STRINGS are provided, insert them followed by a newline.
2154 Otherwise no newline is inserted."
2155 (declare (indent 1))
2156 (insert (make-string (max 0 (- 11 (string-width name))) ?\s)
2157 (propertize (concat name ": ") 'font-lock-face 'package-help-section-name-face))
2158 (when strings
2159 (apply #'insert strings)
2160 (insert "\n")))
2161
2162 (declare-function lm-commentary "lisp-mnt" (&optional file))
2163
2164 (defun describe-package-1 (pkg)
2165 (require 'lisp-mnt)
2166 (let* ((desc (or
2167 (if (package-desc-p pkg) pkg)
2168 (cadr (assq pkg package-alist))
2169 (let ((built-in (assq pkg package--builtins)))
2170 (if built-in
2171 (package--from-builtin built-in)
2172 (cadr (assq pkg package-archive-contents))))))
2173 (name (if desc (package-desc-name desc) pkg))
2174 (pkg-dir (if desc (package-desc-dir desc)))
2175 (reqs (if desc (package-desc-reqs desc)))
2176 (required-by (if desc (package--used-elsewhere-p desc nil 'all)))
2177 (version (if desc (package-desc-version desc)))
2178 (archive (if desc (package-desc-archive desc)))
2179 (extras (and desc (package-desc-extras desc)))
2180 (homepage (cdr (assoc :url extras)))
2181 (keywords (if desc (package-desc--keywords desc)))
2182 (built-in (eq pkg-dir 'builtin))
2183 (installable (and archive (not built-in)))
2184 (status (if desc (package-desc-status desc) "orphan"))
2185 (incompatible-reason (package--incompatible-p desc))
2186 (signed (if desc (package-desc-signed desc))))
2187 (when (string= status "avail-obso")
2188 (setq status "available obsolete"))
2189 (when incompatible-reason
2190 (setq status "incompatible"))
2191 (prin1 name)
2192 (princ " is ")
2193 (princ (if (memq (aref status 0) '(?a ?e ?i ?o ?u)) "an " "a "))
2194 (princ status)
2195 (princ " package.\n\n")
2196
2197 (package--print-help-section "Status")
2198 (cond (built-in
2199 (insert (propertize (capitalize status)
2200 'font-lock-face 'package-status-builtin-face)
2201 "."))
2202 (pkg-dir
2203 (insert (propertize (if (member status '("unsigned" "dependency"))
2204 "Installed"
2205 (capitalize status))
2206 'font-lock-face 'package-status-builtin-face))
2207 (insert (format " in ‘"))
2208 (let ((dir (abbreviate-file-name
2209 (file-name-as-directory
2210 (if (file-in-directory-p pkg-dir package-user-dir)
2211 (file-relative-name pkg-dir package-user-dir)
2212 pkg-dir)))))
2213 (help-insert-xref-button dir 'help-package-def pkg-dir))
2214 (if (and (package-built-in-p name)
2215 (not (package-built-in-p name version)))
2216 (insert (format "’,\n shadowing a ")
2217 (propertize "built-in package"
2218 'font-lock-face 'package-status-builtin-face))
2219 (insert (format "’")))
2220 (if signed
2221 (insert ".")
2222 (insert " (unsigned)."))
2223 (when (and (package-desc-p desc)
2224 (not required-by)
2225 (member status '("unsigned" "installed")))
2226 (insert " ")
2227 (package-make-button "Delete"
2228 'action #'package-delete-button-action
2229 'package-desc desc)))
2230 (incompatible-reason
2231 (insert (propertize "Incompatible" 'font-lock-face font-lock-warning-face)
2232 " because it depends on ")
2233 (if (stringp incompatible-reason)
2234 (insert "Emacs " incompatible-reason ".")
2235 (insert "uninstallable packages.")))
2236 (installable
2237 (insert (capitalize status))
2238 (insert " from " (format "%s" archive))
2239 (insert " -- ")
2240 (package-make-button
2241 "Install"
2242 'action 'package-install-button-action
2243 'package-desc desc))
2244 (t (insert (capitalize status) ".")))
2245 (insert "\n")
2246 (unless (and pkg-dir (not archive)) ; Installed pkgs don't have archive.
2247 (package--print-help-section "Archive"
2248 (or archive "n/a") "\n"))
2249 (and version
2250 (package--print-help-section "Version"
2251 (package-version-join version)))
2252 (when desc
2253 (package--print-help-section "Summary"
2254 (package-desc-summary desc)))
2255
2256 (setq reqs (if desc (package-desc-reqs desc)))
2257 (when reqs
2258 (package--print-help-section "Requires")
2259 (let ((first t))
2260 (dolist (req reqs)
2261 (let* ((name (car req))
2262 (vers (cadr req))
2263 (text (format "%s-%s" (symbol-name name)
2264 (package-version-join vers)))
2265 (reason (if (and (listp incompatible-reason)
2266 (assq name incompatible-reason))
2267 " (not available)" "")))
2268 (cond (first (setq first nil))
2269 ((>= (+ 2 (current-column) (length text) (length reason))
2270 (window-width))
2271 (insert ",\n "))
2272 (t (insert ", ")))
2273 (help-insert-xref-button text 'help-package name)
2274 (insert reason)))
2275 (insert "\n")))
2276 (when required-by
2277 (package--print-help-section "Required by")
2278 (let ((first t))
2279 (dolist (pkg required-by)
2280 (let ((text (package-desc-full-name pkg)))
2281 (cond (first (setq first nil))
2282 ((>= (+ 2 (current-column) (length text))
2283 (window-width))
2284 (insert ",\n "))
2285 (t (insert ", ")))
2286 (help-insert-xref-button text 'help-package
2287 (package-desc-name pkg))))
2288 (insert "\n")))
2289 (when homepage
2290 (package--print-help-section "Homepage")
2291 (help-insert-xref-button homepage 'help-url homepage)
2292 (insert "\n"))
2293 (when keywords
2294 (package--print-help-section "Keywords")
2295 (dolist (k keywords)
2296 (package-make-button
2297 k
2298 'package-keyword k
2299 'action 'package-keyword-button-action)
2300 (insert " "))
2301 (insert "\n"))
2302 (let* ((all-pkgs (append (cdr (assq name package-alist))
2303 (cdr (assq name package-archive-contents))
2304 (let ((bi (assq name package--builtins)))
2305 (if bi (list (package--from-builtin bi))))))
2306 (other-pkgs (delete desc all-pkgs)))
2307 (when other-pkgs
2308 (package--print-help-section "Other versions"
2309 (mapconcat (lambda (opkg)
2310 (let* ((ov (package-desc-version opkg))
2311 (dir (package-desc-dir opkg))
2312 (from (or (package-desc-archive opkg)
2313 (if (stringp dir) "installed" dir))))
2314 (if (not ov) (format "%s" from)
2315 (format "%s (%s)"
2316 (make-text-button (package-version-join ov) nil
2317 'font-lock-face 'link
2318 'follow-link t
2319 'action
2320 (lambda (_button)
2321 (describe-package opkg)))
2322 from))))
2323 other-pkgs ", ")
2324 ".")))
2325
2326 (insert "\n")
2327
2328 (if built-in
2329 ;; For built-in packages, insert the commentary.
2330 (let ((fn (locate-file (format "%s.el" name) load-path
2331 load-file-rep-suffixes))
2332 (opoint (point)))
2333 (insert (or (lm-commentary fn) ""))
2334 (save-excursion
2335 (goto-char opoint)
2336 (when (re-search-forward "^;;; Commentary:\n" nil t)
2337 (replace-match ""))
2338 (while (re-search-forward "^\\(;+ ?\\)" nil t)
2339 (replace-match ""))))
2340 (let ((readme (expand-file-name (format "%s-readme.txt" name)
2341 package-user-dir))
2342 readme-string)
2343 ;; For elpa packages, try downloading the commentary. If that
2344 ;; fails, try an existing readme file in `package-user-dir'.
2345 (cond ((condition-case nil
2346 (save-excursion
2347 (package--with-work-buffer
2348 (package-archive-base desc)
2349 (format "%s-readme.txt" name)
2350 (save-excursion
2351 (goto-char (point-max))
2352 (unless (bolp)
2353 (insert ?\n)))
2354 (write-region nil nil
2355 (expand-file-name readme package-user-dir)
2356 nil 'silent)
2357 (setq readme-string (buffer-string))
2358 t))
2359 (error nil))
2360 (insert readme-string))
2361 ((file-readable-p readme)
2362 (insert-file-contents readme)
2363 (goto-char (point-max))))))))
2364
2365 (defun package-install-button-action (button)
2366 (let ((pkg-desc (button-get button 'package-desc)))
2367 (when (y-or-n-p (format "Install package ‘%s’? "
2368 (package-desc-full-name pkg-desc)))
2369 (package-install pkg-desc nil)
2370 (revert-buffer nil t)
2371 (goto-char (point-min)))))
2372
2373 (defun package-delete-button-action (button)
2374 (let ((pkg-desc (button-get button 'package-desc)))
2375 (when (y-or-n-p (format "Delete package ‘%s’? "
2376 (package-desc-full-name pkg-desc)))
2377 (package-delete pkg-desc)
2378 (revert-buffer nil t)
2379 (goto-char (point-min)))))
2380
2381 (defun package-keyword-button-action (button)
2382 (let ((pkg-keyword (button-get button 'package-keyword)))
2383 (package-show-package-list t (list pkg-keyword))))
2384
2385 (defun package-make-button (text &rest props)
2386 (let ((button-text (if (display-graphic-p) text (concat "[" text "]")))
2387 (button-face (if (display-graphic-p)
2388 '(:box (:line-width 2 :color "dark grey")
2389 :background "light grey"
2390 :foreground "black")
2391 'link)))
2392 (apply 'insert-text-button button-text 'face button-face 'follow-link t
2393 props)))
2394
2395 \f
2396 ;;;; Package menu mode.
2397
2398 (defvar package-menu-mode-map
2399 (let ((map (make-sparse-keymap)))
2400 (set-keymap-parent map tabulated-list-mode-map)
2401 (define-key map "\C-m" 'package-menu-describe-package)
2402 (define-key map "u" 'package-menu-mark-unmark)
2403 (define-key map "\177" 'package-menu-backup-unmark)
2404 (define-key map "d" 'package-menu-mark-delete)
2405 (define-key map "i" 'package-menu-mark-install)
2406 (define-key map "U" 'package-menu-mark-upgrades)
2407 (define-key map "r" 'package-menu-refresh)
2408 (define-key map "f" 'package-menu-filter)
2409 (define-key map "~" 'package-menu-mark-obsolete-for-deletion)
2410 (define-key map "x" 'package-menu-execute)
2411 (define-key map "h" 'package-menu-quick-help)
2412 (define-key map "H" #'package-menu-hide-package)
2413 (define-key map "?" 'package-menu-describe-package)
2414 (define-key map "(" #'package-menu-toggle-hiding)
2415 map)
2416 "Local keymap for `package-menu-mode' buffers.")
2417
2418 (easy-menu-define package-menu-mode-menu package-menu-mode-map
2419 "Menu for `package-menu-mode'."
2420 `("Package"
2421 ["Describe Package" package-menu-describe-package :help "Display information about this package"]
2422 ["Help" package-menu-quick-help :help "Show short key binding help for package-menu-mode"]
2423 "--"
2424 ["Refresh Package List" package-menu-refresh
2425 :help "Redownload the ELPA archive"
2426 :active (not package--downloads-in-progress)]
2427 ["Redisplay buffer" revert-buffer :help "Update the buffer with current list of packages"]
2428 ["Execute Marked Actions" package-menu-execute :help "Perform all the marked actions"]
2429
2430 "--"
2431 ["Mark All Available Upgrades" package-menu-mark-upgrades
2432 :help "Mark packages that have a newer version for upgrading"
2433 :active (not package--downloads-in-progress)]
2434 ["Mark All Obsolete for Deletion" package-menu-mark-obsolete-for-deletion :help "Mark all obsolete packages for deletion"]
2435 ["Mark for Install" package-menu-mark-install :help "Mark a package for installation and move to the next line"]
2436 ["Mark for Deletion" package-menu-mark-delete :help "Mark a package for deletion and move to the next line"]
2437 ["Unmark" package-menu-mark-unmark :help "Clear any marks on a package and move to the next line"]
2438
2439 "--"
2440 ["Filter Package List" package-menu-filter :help "Filter package selection (q to go back)"]
2441 ["Hide by Regexp" package-menu-hide-package :help "Permanently hide all packages matching a regexp"]
2442 ["Display Older Versions" package-menu-toggle-hiding
2443 :style toggle :selected (not package-menu--hide-packages)
2444 :help "Display package even if a newer version is already installed"]
2445
2446 "--"
2447 ["Quit" quit-window :help "Quit package selection"]
2448 ["Customize" (customize-group 'package)]))
2449
2450 (defvar package-menu--new-package-list nil
2451 "List of newly-available packages since `list-packages' was last called.")
2452
2453 (defvar package-menu--transaction-status nil
2454 "Mode-line status of ongoing package transaction.")
2455
2456 (define-derived-mode package-menu-mode tabulated-list-mode "Package Menu"
2457 "Major mode for browsing a list of packages.
2458 Letters do not insert themselves; instead, they are commands.
2459 \\<package-menu-mode-map>
2460 \\{package-menu-mode-map}"
2461 (setq mode-line-process '((package--downloads-in-progress ":Loading")
2462 (package-menu--transaction-status
2463 package-menu--transaction-status)))
2464 (setq tabulated-list-format
2465 `[("Package" 18 package-menu--name-predicate)
2466 ("Version" 13 nil)
2467 ("Status" 10 package-menu--status-predicate)
2468 ,@(if (cdr package-archives)
2469 '(("Archive" 10 package-menu--archive-predicate)))
2470 ("Description" 0 nil)])
2471 (setq tabulated-list-padding 2)
2472 (setq tabulated-list-sort-key (cons "Status" nil))
2473 (add-hook 'tabulated-list-revert-hook 'package-menu--refresh nil t)
2474 (tabulated-list-init-header))
2475
2476 (defmacro package--push (pkg-desc status listname)
2477 "Convenience macro for `package-menu--generate'.
2478 If the alist stored in the symbol LISTNAME lacks an entry for a
2479 package PKG-DESC, add one. The alist is keyed with PKG-DESC."
2480 `(unless (assoc ,pkg-desc ,listname)
2481 ;; FIXME: Should we move status into pkg-desc?
2482 (push (cons ,pkg-desc ,status) ,listname)))
2483
2484 (defvar package-list-unversioned nil
2485 "If non-nil include packages that don't have a version in `list-package'.")
2486
2487 (defvar package-list-unsigned nil
2488 "If non-nil, mention in the list which packages were installed w/o signature.")
2489
2490 (defvar package--emacs-version-list (version-to-list emacs-version)
2491 "`emacs-version', as a list.")
2492
2493 (defun package--incompatible-p (pkg &optional shallow)
2494 "Return non-nil if PKG has no chance of being installable.
2495 PKG is a package-desc object.
2496
2497 If SHALLOW is non-nil, this only checks if PKG depends on a
2498 higher `emacs-version' than the one being used. Otherwise, also
2499 checks the viability of dependencies, according to
2500 `package--compatibility-table'.
2501
2502 If PKG requires an incompatible Emacs version, the return value
2503 is this version (as a string).
2504 If PKG requires incompatible packages, the return value is a list
2505 of these dependencies, similar to the list returned by
2506 `package-desc-reqs'."
2507 (let* ((reqs (package-desc-reqs pkg))
2508 (version (cadr (assq 'emacs reqs))))
2509 (if (and version (version-list-< package--emacs-version-list version))
2510 (package-version-join version)
2511 (unless shallow
2512 (let (out)
2513 (dolist (dep (package-desc-reqs pkg) out)
2514 (let ((dep-name (car dep)))
2515 (unless (eq 'emacs dep-name)
2516 (let ((cv (gethash dep-name package--compatibility-table)))
2517 (when (version-list-< (or cv '(0)) (or (cadr dep) '(0)))
2518 (push dep out)))))))))))
2519
2520 (defun package-desc-status (pkg-desc)
2521 (let* ((name (package-desc-name pkg-desc))
2522 (dir (package-desc-dir pkg-desc))
2523 (lle (assq name package-load-list))
2524 (held (cadr lle))
2525 (version (package-desc-version pkg-desc))
2526 (signed (or (not package-list-unsigned)
2527 (package-desc-signed pkg-desc))))
2528 (cond
2529 ((eq dir 'builtin) "built-in")
2530 ((and lle (null held)) "disabled")
2531 ((stringp held)
2532 (let ((hv (if (stringp held) (version-to-list held))))
2533 (cond
2534 ((version-list-= version hv) "held")
2535 ((version-list-< version hv) "obsolete")
2536 (t "disabled"))))
2537 (dir ;One of the installed packages.
2538 (cond
2539 ((not (file-exists-p dir)) "deleted")
2540 ;; Not inside `package-user-dir'.
2541 ((not (file-in-directory-p dir package-user-dir)) "external")
2542 ((eq pkg-desc (cadr (assq name package-alist)))
2543 (if (not signed) "unsigned"
2544 (if (package--user-selected-p name)
2545 "installed" "dependency")))
2546 (t "obsolete")))
2547 ((package--incompatible-p pkg-desc) "incompat")
2548 (t
2549 (let* ((ins (cadr (assq name package-alist)))
2550 (ins-v (if ins (package-desc-version ins))))
2551 (cond
2552 ;; Installed obsolete packages are handled in the `dir'
2553 ;; clause above. Here we handle available obsolete, which
2554 ;; are displayed depending on `package-menu--hide-packages'.
2555 ((and ins (version-list-<= version ins-v)) "avail-obso")
2556 (t
2557 (if (memq name package-menu--new-package-list)
2558 "new" "available"))))))))
2559
2560 (defvar package-menu--hide-packages t
2561 "Whether available obsolete packages should be hidden.
2562 Can be toggled with \\<package-menu-mode-map> \\[package-menu-toggle-hiding].
2563 Installed obsolete packages are always displayed.")
2564
2565 (defun package-menu-toggle-hiding ()
2566 "Toggle visibility of obsolete available packages."
2567 (interactive)
2568 (unless (derived-mode-p 'package-menu-mode)
2569 (user-error "The current buffer is not a Package Menu"))
2570 (setq package-menu--hide-packages
2571 (not package-menu--hide-packages))
2572 (message "%s packages" (if package-menu--hide-packages
2573 "Hiding obsolete or unwanted"
2574 "Displaying all"))
2575 (revert-buffer nil 'no-confirm))
2576
2577 (defun package--remove-hidden (pkg-list)
2578 "Filter PKG-LIST according to `package-archive-priorities'.
2579 PKG-LIST must be a list of package-desc objects, all with the
2580 same name, sorted by decreasing `package-desc-priority-version'.
2581 Return a list of packages tied for the highest priority according
2582 to their archives."
2583 (when pkg-list
2584 ;; Variable toggled with `package-menu-toggle-hiding'.
2585 (if (not package-menu--hide-packages)
2586 pkg-list
2587 (let ((installed (cadr (assq (package-desc-name (car pkg-list))
2588 package-alist))))
2589 (when installed
2590 (setq pkg-list
2591 (let ((ins-version (package-desc-version installed)))
2592 (cl-remove-if (lambda (p) (version-list-< (package-desc-version p)
2593 ins-version))
2594 pkg-list))))
2595 (let ((filtered-by-priority
2596 (cond
2597 ((not package-menu-hide-low-priority)
2598 pkg-list)
2599 ((eq package-menu-hide-low-priority 'archive)
2600 (let* ((max-priority most-negative-fixnum)
2601 (out))
2602 (while pkg-list
2603 (let ((p (pop pkg-list)))
2604 (let ((priority (package-desc-priority p)))
2605 (if (< priority max-priority)
2606 (setq pkg-list nil)
2607 (push p out)
2608 (setq max-priority priority)))))
2609 (nreverse out)))
2610 (pkg-list
2611 (list (car pkg-list))))))
2612 (if (not installed)
2613 filtered-by-priority
2614 (let ((ins-version (package-desc-version installed)))
2615 (cl-remove-if (lambda (p) (version-list-= (package-desc-version p)
2616 ins-version))
2617 filtered-by-priority))))))))
2618
2619 (defcustom package-hidden-regexps nil
2620 "List of regexps matching the name of packages to hide.
2621 If the name of a package matches any of these regexps it is
2622 omitted from the package menu. To toggle this, type \\[package-menu-toggle-hiding].
2623
2624 Values can be interactively added to this list by typing
2625 \\[package-menu-hide-package] on a package"
2626 :type '(repeat (regexp :tag "Hide packages with name matching")))
2627
2628 (defun package-menu--refresh (&optional packages keywords)
2629 "Re-populate the `tabulated-list-entries'.
2630 PACKAGES should be nil or t, which means to display all known packages.
2631 KEYWORDS should be nil or a list of keywords."
2632 ;; Construct list of (PKG-DESC . STATUS).
2633 (unless packages (setq packages t))
2634 (let ((hidden-names (mapconcat #'identity package-hidden-regexps "\\|"))
2635 info-list)
2636 ;; Installed packages:
2637 (dolist (elt package-alist)
2638 (let ((name (car elt)))
2639 (when (or (eq packages t) (memq name packages))
2640 (dolist (pkg (cdr elt))
2641 (when (package--has-keyword-p pkg keywords)
2642 (push pkg info-list))))))
2643
2644 ;; Built-in packages:
2645 (dolist (elt package--builtins)
2646 (let ((pkg (package--from-builtin elt))
2647 (name (car elt)))
2648 (when (not (eq name 'emacs)) ; Hide the `emacs' package.
2649 (when (and (package--has-keyword-p pkg keywords)
2650 (or package-list-unversioned
2651 (package--bi-desc-version (cdr elt)))
2652 (or (eq packages t) (memq name packages)))
2653 (push pkg info-list)))))
2654
2655 ;; Available and disabled packages:
2656 (dolist (elt package-archive-contents)
2657 (let ((name (car elt)))
2658 ;; To be displayed it must be in PACKAGES;
2659 (when (and (or (eq packages t) (memq name packages))
2660 ;; and we must either not be hiding anything,
2661 (or (not package-menu--hide-packages)
2662 (not package-hidden-regexps)
2663 ;; or just not hiding this specific package.
2664 (not (string-match hidden-names (symbol-name name)))))
2665 ;; Hide available-obsolete or low-priority packages.
2666 (dolist (pkg (package--remove-hidden (cdr elt)))
2667 (when (package--has-keyword-p pkg keywords)
2668 (push pkg info-list))))))
2669
2670 ;; Print the result.
2671 (setq tabulated-list-entries
2672 (mapcar #'package-menu--print-info-simple info-list))))
2673
2674 (defun package-all-keywords ()
2675 "Collect all package keywords"
2676 (let ((key-list))
2677 (package--mapc (lambda (desc)
2678 (setq key-list (append (package-desc--keywords desc)
2679 key-list))))
2680 key-list))
2681
2682 (defun package--mapc (function &optional packages)
2683 "Call FUNCTION for all known PACKAGES.
2684 PACKAGES can be nil or t, which means to display all known
2685 packages, or a list of packages.
2686
2687 Built-in packages are converted with `package--from-builtin'."
2688 (unless packages (setq packages t))
2689 (let (name)
2690 ;; Installed packages:
2691 (dolist (elt package-alist)
2692 (setq name (car elt))
2693 (when (or (eq packages t) (memq name packages))
2694 (mapc function (cdr elt))))
2695
2696 ;; Built-in packages:
2697 (dolist (elt package--builtins)
2698 (setq name (car elt))
2699 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
2700 (or package-list-unversioned
2701 (package--bi-desc-version (cdr elt)))
2702 (or (eq packages t) (memq name packages)))
2703 (funcall function (package--from-builtin elt))))
2704
2705 ;; Available and disabled packages:
2706 (dolist (elt package-archive-contents)
2707 (setq name (car elt))
2708 (when (or (eq packages t) (memq name packages))
2709 (dolist (pkg (cdr elt))
2710 ;; Hide obsolete packages.
2711 (unless (package-installed-p (package-desc-name pkg)
2712 (package-desc-version pkg))
2713 (funcall function pkg)))))))
2714
2715 (defun package--has-keyword-p (desc &optional keywords)
2716 "Test if package DESC has any of the given KEYWORDS.
2717 When none are given, the package matches."
2718 (if keywords
2719 (let ((desc-keywords (and desc (package-desc--keywords desc)))
2720 found)
2721 (while (and (not found) keywords)
2722 (let ((k (pop keywords)))
2723 (setq found
2724 (or (string= k (concat "arc:" (package-desc-archive desc)))
2725 (string= k (concat "status:" (package-desc-status desc)))
2726 (member k desc-keywords)))))
2727 found)
2728 t))
2729
2730 (defun package-menu--generate (remember-pos packages &optional keywords)
2731 "Populate the Package Menu.
2732 If REMEMBER-POS is non-nil, keep point on the same entry.
2733 PACKAGES should be t, which means to display all known packages,
2734 or a list of package names (symbols) to display.
2735
2736 With KEYWORDS given, only packages with those keywords are
2737 shown."
2738 (package-menu--refresh packages keywords)
2739 (setf (car (aref tabulated-list-format 0))
2740 (if keywords
2741 (let ((filters (mapconcat 'identity keywords ",")))
2742 (concat "Package[" filters "]"))
2743 "Package"))
2744 (if keywords
2745 (define-key package-menu-mode-map "q" 'package-show-package-list)
2746 (define-key package-menu-mode-map "q" 'quit-window))
2747 (tabulated-list-init-header)
2748 (tabulated-list-print remember-pos))
2749
2750 (defun package-menu--print-info (pkg)
2751 "Return a package entry suitable for `tabulated-list-entries'.
2752 PKG has the form (PKG-DESC . STATUS).
2753 Return (PKG-DESC [NAME VERSION STATUS DOC])."
2754 (package-menu--print-info-simple (car pkg)))
2755 (make-obsolete 'package-menu--print-info
2756 'package-menu--print-info-simple "25.1")
2757
2758 \f
2759 ;;; Package menu faces
2760 (defface package-name-face
2761 '((t :inherit link))
2762 "Face used on package names in the package menu."
2763 :version "25.1")
2764
2765 (defface package-description-face
2766 '((t :inherit default))
2767 "Face used on package description summaries in the package menu."
2768 :version "25.1")
2769
2770 (defface package-status-built-in-face
2771 '((t :inherit font-lock-builtin-face))
2772 "Face used on the status and version of built-in packages."
2773 :version "25.1")
2774
2775 (defface package-status-external-face
2776 '((t :inherit package-status-builtin-face))
2777 "Face used on the status and version of external packages."
2778 :version "25.1")
2779
2780 (defface package-status-available-face
2781 '((t :inherit default))
2782 "Face used on the status and version of available packages."
2783 :version "25.1")
2784
2785 (defface package-status-new-face
2786 '((t :inherit (bold package-status-available-face)))
2787 "Face used on the status and version of new packages."
2788 :version "25.1")
2789
2790 (defface package-status-held-face
2791 '((t :inherit font-lock-constant-face))
2792 "Face used on the status and version of held packages."
2793 :version "25.1")
2794
2795 (defface package-status-disabled-face
2796 '((t :inherit font-lock-warning-face))
2797 "Face used on the status and version of disabled packages."
2798 :version "25.1")
2799
2800 (defface package-status-installed-face
2801 '((t :inherit font-lock-comment-face))
2802 "Face used on the status and version of installed packages."
2803 :version "25.1")
2804
2805 (defface package-status-dependency-face
2806 '((t :inherit package-status-installed-face))
2807 "Face used on the status and version of dependency packages."
2808 :version "25.1")
2809
2810 (defface package-status-unsigned-face
2811 '((t :inherit font-lock-warning-face))
2812 "Face used on the status and version of unsigned packages."
2813 :version "25.1")
2814
2815 (defface package-status-incompat-face
2816 '((t :inherit font-lock-comment-face))
2817 "Face used on the status and version of incompat packages."
2818 :version "25.1")
2819
2820 (defface package-status-avail-obso-face
2821 '((t :inherit package-status-incompat-face))
2822 "Face used on the status and version of avail-obso packages."
2823 :version "25.1")
2824
2825 \f
2826 ;;; Package menu printing
2827 (defun package-menu--print-info-simple (pkg)
2828 "Return a package entry suitable for `tabulated-list-entries'.
2829 PKG is a package-desc object.
2830 Return (PKG-DESC [NAME VERSION STATUS DOC])."
2831 (let* ((status (package-desc-status pkg))
2832 (face (pcase status
2833 (`"built-in" 'package-status-built-in-face)
2834 (`"external" 'package-status-external-face)
2835 (`"available" 'package-status-available-face)
2836 (`"avail-obso" 'package-status-avail-obso-face)
2837 (`"new" 'package-status-new-face)
2838 (`"held" 'package-status-held-face)
2839 (`"disabled" 'package-status-disabled-face)
2840 (`"installed" 'package-status-installed-face)
2841 (`"dependency" 'package-status-dependency-face)
2842 (`"unsigned" 'package-status-unsigned-face)
2843 (`"incompat" 'package-status-incompat-face)
2844 (_ 'font-lock-warning-face)))) ; obsolete.
2845 (list pkg
2846 `[(,(symbol-name (package-desc-name pkg))
2847 face package-name-face
2848 font-lock-face package-name-face
2849 follow-link t
2850 package-desc ,pkg
2851 action package-menu-describe-package)
2852 ,(propertize (package-version-join
2853 (package-desc-version pkg))
2854 'font-lock-face face)
2855 ,(propertize status 'font-lock-face face)
2856 ,@(if (cdr package-archives)
2857 (list (propertize (or (package-desc-archive pkg) "")
2858 'font-lock-face face)))
2859 ,(propertize (package-desc-summary pkg)
2860 'font-lock-face 'package-description-face)])))
2861
2862 (defvar package-menu--old-archive-contents nil
2863 "`package-archive-contents' before the latest refresh.")
2864
2865 (defun package-menu-refresh ()
2866 "Download the Emacs Lisp package archive.
2867 This fetches the contents of each archive specified in
2868 `package-archives', and then refreshes the package menu."
2869 (interactive)
2870 (unless (derived-mode-p 'package-menu-mode)
2871 (user-error "The current buffer is not a Package Menu"))
2872 (setq package-menu--old-archive-contents package-archive-contents)
2873 (setq package-menu--new-package-list nil)
2874 (package-refresh-contents package-menu-async))
2875
2876 (defun package-menu-hide-package ()
2877 "Hide a package under point.
2878 If optional arg BUTTON is non-nil, describe its associated package."
2879 (interactive)
2880 (declare (interactive-only "change `package-hidden-regexps' instead."))
2881 (let* ((name (when (derived-mode-p 'package-menu-mode)
2882 (concat "\\`" (regexp-quote (symbol-name (package-desc-name
2883 (tabulated-list-get-id)))))))
2884 (re (read-string "Hide packages matching regexp: " name)))
2885 ;; Test if it is valid.
2886 (string-match re "")
2887 (push re package-hidden-regexps)
2888 (customize-save-variable 'package-hidden-regexps package-hidden-regexps)
2889 (package-menu--post-refresh)
2890 (let ((hidden
2891 (cl-remove-if-not (lambda (e) (string-match re (symbol-name (car e))))
2892 package-archive-contents)))
2893 (message (substitute-command-keys
2894 (concat "Hiding %s packages, type ‘\\[package-menu-toggle-hiding]’"
2895 " to toggle or ‘\\[customize-variable] RET package-hidden-regexps’"
2896 " to customize it"))
2897 (length hidden)))))
2898
2899 (defun package-menu-describe-package (&optional button)
2900 "Describe the current package.
2901 If optional arg BUTTON is non-nil, describe its associated package."
2902 (interactive)
2903 (let ((pkg-desc (if button (button-get button 'package-desc)
2904 (tabulated-list-get-id))))
2905 (if pkg-desc
2906 (describe-package pkg-desc)
2907 (user-error "No package here"))))
2908
2909 ;; fixme numeric argument
2910 (defun package-menu-mark-delete (&optional _num)
2911 "Mark a package for deletion and move to the next line."
2912 (interactive "p")
2913 (if (member (package-menu-get-status)
2914 '("installed" "dependency" "obsolete" "unsigned"))
2915 (tabulated-list-put-tag "D" t)
2916 (forward-line)))
2917
2918 (defun package-menu-mark-install (&optional _num)
2919 "Mark a package for installation and move to the next line."
2920 (interactive "p")
2921 (if (member (package-menu-get-status) '("available" "avail-obso" "new" "dependency"))
2922 (tabulated-list-put-tag "I" t)
2923 (forward-line)))
2924
2925 (defun package-menu-mark-unmark (&optional _num)
2926 "Clear any marks on a package and move to the next line."
2927 (interactive "p")
2928 (tabulated-list-put-tag " " t))
2929
2930 (defun package-menu-backup-unmark ()
2931 "Back up one line and clear any marks on that package."
2932 (interactive)
2933 (forward-line -1)
2934 (tabulated-list-put-tag " "))
2935
2936 (defun package-menu-mark-obsolete-for-deletion ()
2937 "Mark all obsolete packages for deletion."
2938 (interactive)
2939 (save-excursion
2940 (goto-char (point-min))
2941 (while (not (eobp))
2942 (if (equal (package-menu-get-status) "obsolete")
2943 (tabulated-list-put-tag "D" t)
2944 (forward-line 1)))))
2945
2946 (defvar package--quick-help-keys
2947 '(("install," "delete," "unmark," ("execute" . 1))
2948 ("next," "previous")
2949 ("Hide-package," "(-toggle-hidden")
2950 ("refresh-contents," "g-redisplay," "filter," "help")))
2951
2952 (defun package--prettify-quick-help-key (desc)
2953 "Prettify DESC to be displayed as a help menu."
2954 (if (listp desc)
2955 (if (listp (cdr desc))
2956 (mapconcat #'package--prettify-quick-help-key desc " ")
2957 (let ((place (cdr desc))
2958 (out (car desc)))
2959 (add-text-properties place (1+ place)
2960 '(face (bold font-lock-warning-face))
2961 out)
2962 out))
2963 (package--prettify-quick-help-key (cons desc 0))))
2964
2965 (defun package-menu-quick-help ()
2966 "Show short key binding help for `package-menu-mode'.
2967 The full list of keys can be viewed with \\[describe-mode]."
2968 (interactive)
2969 (message (mapconcat #'package--prettify-quick-help-key
2970 package--quick-help-keys "\n")))
2971
2972 (define-obsolete-function-alias
2973 'package-menu-view-commentary 'package-menu-describe-package "24.1")
2974
2975 (defun package-menu-get-status ()
2976 (let* ((id (tabulated-list-get-id))
2977 (entry (and id (assoc id tabulated-list-entries))))
2978 (if entry
2979 (aref (cadr entry) 2)
2980 "")))
2981
2982 (defun package-archive-priority (archive)
2983 "Return the priority of ARCHIVE.
2984
2985 The archive priorities are specified in
2986 `package-archive-priorities'. If not given there, the priority
2987 defaults to 0."
2988 (or (cdr (assoc archive package-archive-priorities))
2989 0))
2990
2991 (defun package-desc-priority-version (pkg-desc)
2992 "Return the version PKG-DESC with the archive priority prepended.
2993
2994 This allows for easy comparison of package versions from
2995 different archives if archive priorities are meant to be taken in
2996 consideration."
2997 (cons (package-desc-priority pkg-desc)
2998 (package-desc-version pkg-desc)))
2999
3000 (defun package-menu--find-upgrades ()
3001 (let (installed available upgrades)
3002 ;; Build list of installed/available packages in this buffer.
3003 (dolist (entry tabulated-list-entries)
3004 ;; ENTRY is (PKG-DESC [NAME VERSION STATUS DOC])
3005 (let ((pkg-desc (car entry))
3006 (status (aref (cadr entry) 2)))
3007 (cond ((member status '("installed" "dependency" "unsigned"))
3008 (push pkg-desc installed))
3009 ((member status '("available" "new"))
3010 (setq available (package--append-to-alist pkg-desc available))))))
3011 ;; Loop through list of installed packages, finding upgrades.
3012 (dolist (pkg-desc installed)
3013 (let* ((name (package-desc-name pkg-desc))
3014 (avail-pkg (cadr (assq name available))))
3015 (and avail-pkg
3016 (version-list-< (package-desc-priority-version pkg-desc)
3017 (package-desc-priority-version avail-pkg))
3018 (push (cons name avail-pkg) upgrades))))
3019 upgrades))
3020
3021 (defvar package-menu--mark-upgrades-pending nil
3022 "Whether mark-upgrades is waiting for a refresh to finish.")
3023
3024 (defun package-menu--mark-upgrades-1 ()
3025 "Mark all upgradable packages in the Package Menu.
3026 Implementation of `package-menu-mark-upgrades'."
3027 (unless (derived-mode-p 'package-menu-mode)
3028 (error "The current buffer is not a Package Menu"))
3029 (setq package-menu--mark-upgrades-pending nil)
3030 (let ((upgrades (package-menu--find-upgrades)))
3031 (if (null upgrades)
3032 (message "No packages to upgrade.")
3033 (widen)
3034 (save-excursion
3035 (goto-char (point-min))
3036 (while (not (eobp))
3037 (let* ((pkg-desc (tabulated-list-get-id))
3038 (upgrade (cdr (assq (package-desc-name pkg-desc) upgrades))))
3039 (cond ((null upgrade)
3040 (forward-line 1))
3041 ((equal pkg-desc upgrade)
3042 (package-menu-mark-install))
3043 (t
3044 (package-menu-mark-delete))))))
3045 (message "%d package%s marked for upgrading."
3046 (length upgrades)
3047 (if (= (length upgrades) 1) "" "s")))))
3048
3049 (defun package-menu-mark-upgrades ()
3050 "Mark all upgradable packages in the Package Menu.
3051 For each installed package with a newer version available, place
3052 an (I)nstall flag on the available version and a (D)elete flag on
3053 the installed version. A subsequent \\[package-menu-execute]
3054 call will upgrade the package.
3055
3056 If there's an async refresh operation in progress, the flags will
3057 be placed as part of `package-menu--post-refresh' instead of
3058 immediately."
3059 (interactive)
3060 (if (not package--downloads-in-progress)
3061 (package-menu--mark-upgrades-1)
3062 (setq package-menu--mark-upgrades-pending t)
3063 (message "Waiting for refresh to finish...")))
3064
3065 (defun package-menu--list-to-prompt (packages)
3066 "Return a string listing PACKAGES that's usable in a prompt.
3067 PACKAGES is a list of `package-desc' objects.
3068 Formats the returned string to be usable in a minibuffer
3069 prompt (see `package-menu--prompt-transaction-p')."
3070 (cond
3071 ;; None
3072 ((not packages) "")
3073 ;; More than 1
3074 ((cdr packages)
3075 (format "these %d packages (%s)"
3076 (length packages)
3077 (mapconcat #'package-desc-full-name packages ", ")))
3078 ;; Exactly 1
3079 (t (format "package ‘%s’"
3080 (package-desc-full-name (car packages))))))
3081
3082 (defun package-menu--prompt-transaction-p (delete install upgrade)
3083 "Prompt the user about DELETE, INSTALL, and UPGRADE.
3084 DELETE, INSTALL, and UPGRADE are lists of `package-desc' objects.
3085 Either may be nil, but not all."
3086 (y-or-n-p
3087 (concat
3088 (when delete "Delete ")
3089 (package-menu--list-to-prompt delete)
3090 (when (and delete install)
3091 (if upgrade "; " "; and "))
3092 (when install "Install ")
3093 (package-menu--list-to-prompt install)
3094 (when (and upgrade (or install delete)) "; and ")
3095 (when upgrade "Upgrade ")
3096 (package-menu--list-to-prompt upgrade)
3097 "? ")))
3098
3099 (defun package-menu--partition-transaction (install delete)
3100 "Return an alist describing an INSTALL DELETE transaction.
3101 Alist contains three entries, upgrade, delete, and install, each
3102 with a list of package names.
3103
3104 The upgrade entry contains any `package-desc' objects in INSTALL
3105 whose name coincides with an object in DELETE. The delete and
3106 the install entries are the same as DELETE and INSTALL with such
3107 objects removed."
3108 (let* ((upg (cl-intersection install delete :key #'package-desc-name))
3109 (ins (cl-set-difference install upg :key #'package-desc-name))
3110 (del (cl-set-difference delete upg :key #'package-desc-name)))
3111 `((delete . ,del) (install . ,ins) (upgrade . ,upg))))
3112
3113 (defun package-menu--perform-transaction (install-list delete-list)
3114 "Install packages in INSTALL-LIST and delete DELETE-LIST."
3115 (if install-list
3116 (let ((status-format (format ":Installing %%d/%d"
3117 (length install-list)))
3118 (i 0)
3119 (package-menu--transaction-status))
3120 (dolist (pkg install-list)
3121 (setq package-menu--transaction-status
3122 (format status-format (cl-incf i)))
3123 (force-mode-line-update)
3124 (redisplay 'force)
3125 ;; Don't mark as selected, `package-menu-execute' already
3126 ;; does that.
3127 (package-install pkg 'dont-select))))
3128 (let ((package-menu--transaction-status ":Deleting"))
3129 (force-mode-line-update)
3130 (redisplay 'force)
3131 (dolist (elt (package--sort-by-dependence delete-list))
3132 (condition-case-unless-debug err
3133 (let ((inhibit-message package-menu-async))
3134 (package-delete elt nil 'nosave))
3135 (error (message "Error trying to delete ‘%s’: %S"
3136 (package-desc-full-name elt)
3137 err))))))
3138
3139 (defun package--update-selected-packages (add remove)
3140 "Update the `package-selected-packages' list according to ADD and REMOVE.
3141 ADD and REMOVE must be disjoint lists of package names (or
3142 `package-desc' objects) to be added and removed to the selected
3143 packages list, respectively."
3144 (dolist (p add)
3145 (cl-pushnew (if (package-desc-p p) (package-desc-name p) p)
3146 package-selected-packages))
3147 (dolist (p remove)
3148 (setq package-selected-packages
3149 (remove (if (package-desc-p p) (package-desc-name p) p)
3150 package-selected-packages)))
3151 (when (or add remove)
3152 (package--save-selected-packages package-selected-packages)))
3153
3154 (defun package-menu-execute (&optional noquery)
3155 "Perform marked Package Menu actions.
3156 Packages marked for installation are downloaded and installed;
3157 packages marked for deletion are removed.
3158 Optional argument NOQUERY non-nil means do not ask the user to confirm."
3159 (interactive)
3160 (unless (derived-mode-p 'package-menu-mode)
3161 (error "The current buffer is not in Package Menu mode"))
3162 (let (install-list delete-list cmd pkg-desc)
3163 (save-excursion
3164 (goto-char (point-min))
3165 (while (not (eobp))
3166 (setq cmd (char-after))
3167 (unless (eq cmd ?\s)
3168 ;; This is the key PKG-DESC.
3169 (setq pkg-desc (tabulated-list-get-id))
3170 (cond ((eq cmd ?D)
3171 (push pkg-desc delete-list))
3172 ((eq cmd ?I)
3173 (push pkg-desc install-list))))
3174 (forward-line)))
3175 (unless (or delete-list install-list)
3176 (user-error "No operations specified"))
3177 (let-alist (package-menu--partition-transaction install-list delete-list)
3178 (when (or noquery
3179 (package-menu--prompt-transaction-p .delete .install .upgrade))
3180 (let ((message-template
3181 (concat "Package menu: Operation %s ["
3182 (when .delete (format "Delet__ %s" (length .delete)))
3183 (when (and .delete .install) "; ")
3184 (when .install (format "Install__ %s" (length .install)))
3185 (when (and .upgrade (or .install .delete)) "; ")
3186 (when .upgrade (format "Upgrad__ %s" (length .upgrade)))
3187 "]")))
3188 (message (replace-regexp-in-string "__" "ing" message-template) "started")
3189 ;; Packages being upgraded are not marked as selected.
3190 (package--update-selected-packages .install .delete)
3191 (package-menu--perform-transaction install-list delete-list)
3192 (when package-selected-packages
3193 (if-let ((removable (package--removable-packages)))
3194 (message "Package menu: Operation finished. %d packages %s"
3195 (length removable)
3196 (substitute-command-keys
3197 "are no longer needed, type `\\[package-autoremove]' to remove them"))
3198 (message (replace-regexp-in-string "__" "ed" message-template)
3199 "finished"))))))))
3200
3201 (defun package-menu--version-predicate (A B)
3202 (let ((vA (or (aref (cadr A) 1) '(0)))
3203 (vB (or (aref (cadr B) 1) '(0))))
3204 (if (version-list-= vA vB)
3205 (package-menu--name-predicate A B)
3206 (version-list-< vA vB))))
3207
3208 (defun package-menu--status-predicate (A B)
3209 (let ((sA (aref (cadr A) 2))
3210 (sB (aref (cadr B) 2)))
3211 (cond ((string= sA sB)
3212 (package-menu--name-predicate A B))
3213 ((string= sA "new") t)
3214 ((string= sB "new") nil)
3215 ((string-prefix-p "avail" sA)
3216 (if (string-prefix-p "avail" sB)
3217 (package-menu--name-predicate A B)
3218 t))
3219 ((string-prefix-p "avail" sB) nil)
3220 ((string= sA "installed") t)
3221 ((string= sB "installed") nil)
3222 ((string= sA "dependency") t)
3223 ((string= sB "dependency") nil)
3224 ((string= sA "unsigned") t)
3225 ((string= sB "unsigned") nil)
3226 ((string= sA "held") t)
3227 ((string= sB "held") nil)
3228 ((string= sA "external") t)
3229 ((string= sB "external") nil)
3230 ((string= sA "built-in") t)
3231 ((string= sB "built-in") nil)
3232 ((string= sA "obsolete") t)
3233 ((string= sB "obsolete") nil)
3234 ((string= sA "incompat") t)
3235 ((string= sB "incompat") nil)
3236 (t (string< sA sB)))))
3237
3238 (defun package-menu--description-predicate (A B)
3239 (let ((dA (aref (cadr A) 3))
3240 (dB (aref (cadr B) 3)))
3241 (if (string= dA dB)
3242 (package-menu--name-predicate A B)
3243 (string< dA dB))))
3244
3245 (defun package-menu--name-predicate (A B)
3246 (string< (symbol-name (package-desc-name (car A)))
3247 (symbol-name (package-desc-name (car B)))))
3248
3249 (defun package-menu--archive-predicate (A B)
3250 (string< (or (package-desc-archive (car A)) "")
3251 (or (package-desc-archive (car B)) "")))
3252
3253 (defun package-menu--populate-new-package-list ()
3254 "Decide which packages are new in `package-archives-contents'.
3255 Store this list in `package-menu--new-package-list'."
3256 ;; Find which packages are new.
3257 (when package-menu--old-archive-contents
3258 (dolist (elt package-archive-contents)
3259 (unless (assq (car elt) package-menu--old-archive-contents)
3260 (push (car elt) package-menu--new-package-list)))
3261 (setq package-menu--old-archive-contents nil)))
3262
3263 (defun package-menu--find-and-notify-upgrades ()
3264 "Notify the user of upgradable packages."
3265 (when-let ((upgrades (package-menu--find-upgrades)))
3266 (message "%d package%s can be upgraded; type ‘%s’ to mark %s for upgrading."
3267 (length upgrades)
3268 (if (= (length upgrades) 1) "" "s")
3269 (substitute-command-keys "\\[package-menu-mark-upgrades]")
3270 (if (= (length upgrades) 1) "it" "them"))))
3271
3272 (defun package-menu--post-refresh ()
3273 "If there's a *Packages* buffer, revert it and check for new packages and upgrades.
3274 Do nothing if there's no *Packages* buffer.
3275
3276 This function is called after `package-refresh-contents' and it
3277 is added to `post-command-hook' by any function which alters the
3278 package database (`package-install' and `package-delete'). When
3279 run, it removes itself from `post-command-hook'."
3280 (remove-hook 'post-command-hook #'package-menu--post-refresh)
3281 (let ((buf (get-buffer "*Packages*")))
3282 (when (buffer-live-p buf)
3283 (with-current-buffer buf
3284 (package-menu--populate-new-package-list)
3285 (run-hooks 'tabulated-list-revert-hook)
3286 (tabulated-list-print 'remember 'update)))))
3287
3288 (defun package-menu--mark-or-notify-upgrades ()
3289 "If there's a *Packages* buffer, check for upgrades and possibly mark them.
3290 Do nothing if there's no *Packages* buffer. If there are
3291 upgrades, mark them if `package-menu--mark-upgrades-pending' is
3292 non-nil, otherwise just notify the user that there are upgrades.
3293 This function is called after `package-refresh-contents'."
3294 (let ((buf (get-buffer "*Packages*")))
3295 (when (buffer-live-p buf)
3296 (with-current-buffer buf
3297 (if package-menu--mark-upgrades-pending
3298 (package-menu--mark-upgrades-1)
3299 (package-menu--find-and-notify-upgrades))))))
3300
3301 ;;;###autoload
3302 (defun list-packages (&optional no-fetch)
3303 "Display a list of packages.
3304 This first fetches the updated list of packages before
3305 displaying, unless a prefix argument NO-FETCH is specified.
3306 The list is displayed in a buffer named `*Packages*'."
3307 (interactive "P")
3308 (require 'finder-inf nil t)
3309 ;; Initialize the package system if necessary.
3310 (unless package--initialized
3311 (package-initialize t))
3312 ;; Integrate the package-menu with updating the archives.
3313 (add-hook 'package--post-download-archives-hook
3314 #'package-menu--post-refresh)
3315 (add-hook 'package--post-download-archives-hook
3316 #'package-menu--mark-or-notify-upgrades 'append)
3317
3318 ;; Generate the Package Menu.
3319 (let ((buf (get-buffer-create "*Packages*")))
3320 (with-current-buffer buf
3321 (package-menu-mode)
3322
3323 ;; Fetch the remote list of packages.
3324 (unless no-fetch (package-menu-refresh))
3325
3326 ;; If we're not async, this would be redundant.
3327 (when package-menu-async
3328 (package-menu--generate nil t)))
3329 ;; The package menu buffer has keybindings. If the user types
3330 ;; `M-x list-packages', that suggests it should become current.
3331 (switch-to-buffer buf)))
3332
3333 ;;;###autoload
3334 (defalias 'package-list-packages 'list-packages)
3335
3336 ;; Used in finder.el
3337 (defun package-show-package-list (&optional packages keywords)
3338 "Display PACKAGES in a *Packages* buffer.
3339 This is similar to `list-packages', but it does not fetch the
3340 updated list of packages, and it only displays packages with
3341 names in PACKAGES (which should be a list of symbols).
3342
3343 When KEYWORDS are given, only packages with those KEYWORDS are
3344 shown."
3345 (interactive)
3346 (require 'finder-inf nil t)
3347 (let* ((buf (get-buffer-create "*Packages*"))
3348 (win (get-buffer-window buf)))
3349 (with-current-buffer buf
3350 (package-menu-mode)
3351 (package-menu--generate nil packages keywords))
3352 (if win
3353 (select-window win)
3354 (switch-to-buffer buf))))
3355
3356 ;; package-menu--generate rebinds "q" on the fly, so we have to
3357 ;; hard-code the binding in the doc-string here.
3358 (defun package-menu-filter (keyword)
3359 "Filter the *Packages* buffer.
3360 Show only those items that relate to the specified KEYWORD.
3361 KEYWORD can be a string or a list of strings. If it is a list, a
3362 package will be displayed if it matches any of the keywords.
3363 Interactively, it is a list of strings separated by commas.
3364
3365 To restore the full package list, type `q'."
3366 (interactive
3367 (list (completing-read-multiple
3368 "Keywords (comma separated): " (package-all-keywords))))
3369 (package-show-package-list t (if (stringp keyword)
3370 (list keyword)
3371 keyword)))
3372
3373 (defun package-list-packages-no-fetch ()
3374 "Display a list of packages.
3375 Does not fetch the updated list of packages before displaying.
3376 The list is displayed in a buffer named `*Packages*'."
3377 (interactive)
3378 (list-packages t))
3379
3380 (provide 'package)
3381
3382 ;;; package.el ends here