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