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