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