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