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