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