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