emacs-lisp/package.el (package-menu-execute): Add async support
[emacs.git] / lisp / emacs-lisp / package.el
blobacfab92e7eb0975214073ee48b02555e7391ae97
1 ;;; package.el --- Simple package system for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 2007-2015 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.0.1
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 ;;; Change Log:
29 ;; 2 Apr 2007 - now using ChangeLog file
30 ;; 15 Mar 2007 - updated documentation
31 ;; 14 Mar 2007 - Changed how obsolete packages are handled
32 ;; 13 Mar 2007 - Wrote package-install-from-buffer
33 ;; 12 Mar 2007 - Wrote package-menu mode
35 ;;; Commentary:
37 ;; The idea behind package.el is to be able to download packages and
38 ;; install them. Packages are versioned and have versioned
39 ;; dependencies. Furthermore, this supports built-in packages which
40 ;; may or may not be newer than user-specified packages. This makes
41 ;; it possible to upgrade Emacs and automatically disable packages
42 ;; which have moved from external to core. (Note though that we don't
43 ;; currently register any of these, so this feature does not actually
44 ;; work.)
46 ;; A package is described by its name and version. The distribution
47 ;; format is either a tar file or a single .el file.
49 ;; A tar file should be named "NAME-VERSION.tar". The tar file must
50 ;; unpack into a directory named after the package and version:
51 ;; "NAME-VERSION". It must contain a file named "PACKAGE-pkg.el"
52 ;; which consists of a call to define-package. It may also contain a
53 ;; "dir" file and the info files it references.
55 ;; A .el file is named "NAME-VERSION.el" in the remote archive, but is
56 ;; installed as simply "NAME.el" in a directory named "NAME-VERSION".
58 ;; The downloader downloads all dependent packages. By default,
59 ;; packages come from the official GNU sources, but others may be
60 ;; added by customizing the `package-archives' alist. Packages get
61 ;; byte-compiled at install time.
63 ;; At activation time we will set up the load-path and the info path,
64 ;; and we will load the package's autoloads. If a package's
65 ;; dependencies are not available, we will not activate that package.
67 ;; Conceptually a package has multiple state transitions:
69 ;; * Download. Fetching the package from ELPA.
70 ;; * Install. Untar the package, or write the .el file, into
71 ;; ~/.emacs.d/elpa/ directory.
72 ;; * Byte compile. Currently this phase is done during install,
73 ;; but we may change this.
74 ;; * Activate. Evaluate the autoloads for the package to make it
75 ;; available to the user.
76 ;; * Load. Actually load the package and run some code from it.
78 ;; Other external functions you may want to use:
80 ;; M-x list-packages
81 ;; Enters a mode similar to buffer-menu which lets you manage
82 ;; packages. You can choose packages for install (mark with "i",
83 ;; then "x" to execute) or deletion (not implemented yet), and you
84 ;; can see what packages are available. This will automatically
85 ;; fetch the latest list of packages from ELPA.
87 ;; M-x package-install-from-buffer
88 ;; Install a package consisting of a single .el file that appears
89 ;; in the current buffer. This only works for packages which
90 ;; define a Version header properly; package.el also supports the
91 ;; extension headers Package-Version (in case Version is an RCS id
92 ;; or similar), and Package-Requires (if the package requires other
93 ;; packages).
95 ;; M-x package-install-file
96 ;; Install a package from the indicated file. The package can be
97 ;; either a tar file or a .el file. A tar file must contain an
98 ;; appropriately-named "-pkg.el" file; a .el file must be properly
99 ;; formatted as with package-install-from-buffer.
101 ;;; Thanks:
102 ;;; (sorted by sort-lines):
104 ;; Jim Blandy <jimb@red-bean.com>
105 ;; Karl Fogel <kfogel@red-bean.com>
106 ;; Kevin Ryde <user42@zip.com.au>
107 ;; Lawrence Mitchell
108 ;; Michael Olson <mwolson@member.fsf.org>
109 ;; Sebastian Tennant <sebyte@smolny.plus.com>
110 ;; Stefan Monnier <monnier@iro.umontreal.ca>
111 ;; Vinicius Jose Latorre <viniciusjl@ig.com.br>
112 ;; Phil Hagelberg <phil@hagelb.org>
114 ;;; ToDo:
116 ;; - putting info dirs at the start of the info path means
117 ;; users see a weird ordering of categories. OTOH we want to
118 ;; override later entries. maybe emacs needs to enforce
119 ;; the standard layout?
120 ;; - put bytecode in a separate directory tree
121 ;; - perhaps give users a way to recompile their bytecode
122 ;; or do it automatically when emacs changes
123 ;; - give users a way to know whether a package is installed ok
124 ;; - give users a way to view a package's documentation when it
125 ;; only appears in the .el
126 ;; - use/extend checkdoc so people can tell if their package will work
127 ;; - "installed" instead of a blank in the status column
128 ;; - tramp needs its files to be compiled in a certain order.
129 ;; how to handle this? fix tramp?
130 ;; - on emacs 21 we don't kill the -autoloads.el buffer. what about 22?
131 ;; - maybe we need separate .elc directories for various emacs versions
132 ;; and also emacs-vs-xemacs. That way conditional compilation can
133 ;; work. But would this break anything?
134 ;; - should store the package's keywords in archive-contents, then
135 ;; let the users filter the package-menu by keyword. See
136 ;; finder-by-keyword. (We could also let people view the
137 ;; Commentary, but it isn't clear how useful this is.)
138 ;; - William Xu suggests being able to open a package file without
139 ;; installing it
140 ;; - Interface with desktop.el so that restarting after an install
141 ;; works properly
142 ;; - Use hierarchical layout. PKG/etc PKG/lisp PKG/info
143 ;; ... except maybe lisp?
144 ;; - It may be nice to have a macro that expands to the package's
145 ;; private data dir, aka ".../etc". Or, maybe data-directory
146 ;; needs to be a list (though this would be less nice)
147 ;; a few packages want this, eg sokoban
148 ;; - package menu needs:
149 ;; ability to know which packages are built-in & thus not deletable
150 ;; it can sometimes print odd results, like 0.3 available but 0.4 active
151 ;; why is that?
152 ;; - Allow multiple versions on the server...?
153 ;; [ why bother? ]
154 ;; - Don't install a package which will invalidate dependencies overall
155 ;; - Allow something like (or (>= emacs 21.0) (>= xemacs 21.5))
156 ;; [ currently thinking, why bother.. KISS ]
157 ;; - Allow optional package dependencies
158 ;; then if we require 'bbdb', bbdb-specific lisp in lisp/bbdb
159 ;; and just don't compile to add to load path ...?
160 ;; - Our treatment of the info path is somewhat bogus
162 ;;; Code:
164 (eval-when-compile (require 'subr-x))
165 (eval-when-compile (require 'cl-lib))
166 (eval-when-compile (require 'epg)) ;For setf accessors.
168 (require 'tabulated-list)
169 (require 'macroexp)
171 (defgroup package nil
172 "Manager for Emacs Lisp packages."
173 :group 'applications
174 :version "24.1")
177 ;;; Customization options
178 ;;;###autoload
179 (defcustom package-enable-at-startup t
180 "Whether to activate installed packages when Emacs starts.
181 If non-nil, packages are activated after reading the init file
182 and before `after-init-hook'. Activation is not done if
183 `user-init-file' is nil (e.g. Emacs was started with \"-q\").
185 Even if the value is nil, you can type \\[package-initialize] to
186 activate the package system at any time."
187 :type 'boolean
188 :group 'package
189 :version "24.1")
191 (defcustom package-load-list '(all)
192 "List of packages for `package-initialize' to load.
193 Each element in this list should be a list (NAME VERSION), or the
194 symbol `all'. The symbol `all' says to load the latest installed
195 versions of all packages not specified by other elements.
197 For an element (NAME VERSION), NAME is a package name (a symbol).
198 VERSION should be t, a string, or nil.
199 If VERSION is t, the most recent version is activated.
200 If VERSION is a string, only that version is ever loaded.
201 Any other version, even if newer, is silently ignored.
202 Hence, the package is \"held\" at that version.
203 If VERSION is nil, the package is not loaded (it is \"disabled\")."
204 :type '(repeat symbol)
205 :risky t
206 :group 'package
207 :version "24.1")
209 (defcustom package-archives '(("gnu" . "http://elpa.gnu.org/packages/"))
210 "An alist of archives from which to fetch.
211 The default value points to the GNU Emacs package repository.
213 Each element has the form (ID . LOCATION).
214 ID is an archive name, as a string.
215 LOCATION specifies the base location for the archive.
216 If it starts with \"http:\", it is treated as a HTTP URL;
217 otherwise it should be an absolute directory name.
218 (Other types of URL are currently not supported.)
220 Only add locations that you trust, since fetching and installing
221 a package can run arbitrary code."
222 :type '(alist :key-type (string :tag "Archive name")
223 :value-type (string :tag "URL or directory name"))
224 :risky t
225 :group 'package
226 :version "24.1")
228 (defcustom package-archive-priorities nil
229 "An alist of priorities for packages.
231 Each element has the form (ARCHIVE-ID . PRIORITY).
233 When installing packages, the package with the highest version
234 number from the archive with the highest priority is
235 selected. When higher versions are available from archives with
236 lower priorities, the user has to select those manually.
238 Archives not in this list have the priority 0."
239 :type '(alist :key-type (string :tag "Archive name")
240 :value-type (integer :tag "Priority (default is 0)"))
241 :risky t
242 :group 'package
243 :version "25.1")
245 (defcustom package-pinned-packages nil
246 "An alist of packages that are pinned to specific archives.
247 This can be useful if you have multiple package archives enabled,
248 and want to control which archive a given package gets installed from.
250 Each element of the alist has the form (PACKAGE . ARCHIVE), where:
251 PACKAGE is a symbol representing a package
252 ARCHIVE is a string representing an archive (it should be the car of
253 an element in `package-archives', e.g. \"gnu\").
255 Adding an entry to this variable means that only ARCHIVE will be
256 considered as a source for PACKAGE. If other archives provide PACKAGE,
257 they are ignored (for this package). If ARCHIVE does not contain PACKAGE,
258 the package will be unavailable."
259 :type '(alist :key-type (symbol :tag "Package")
260 :value-type (string :tag "Archive name"))
261 ;; I don't really see why this is risky...
262 ;; I suppose it could prevent you receiving updates for a package,
263 ;; via an entry (PACKAGE . NON-EXISTING). Which could be an issue
264 ;; if PACKAGE has a known vulnerability that is fixed in newer versions.
265 :risky t
266 :group 'package
267 :version "24.4")
269 (defcustom package-user-dir (locate-user-emacs-file "elpa")
270 "Directory containing the user's Emacs Lisp packages.
271 The directory name should be absolute.
272 Apart from this directory, Emacs also looks for system-wide
273 packages in `package-directory-list'."
274 :type 'directory
275 :risky t
276 :group 'package
277 :version "24.1")
279 (defcustom package-directory-list
280 ;; Defaults are subdirs named "elpa" in the site-lisp dirs.
281 (let (result)
282 (dolist (f load-path)
283 (and (stringp f)
284 (equal (file-name-nondirectory f) "site-lisp")
285 (push (expand-file-name "elpa" f) result)))
286 (nreverse result))
287 "List of additional directories containing Emacs Lisp packages.
288 Each directory name should be absolute.
290 These directories contain packages intended for system-wide; in
291 contrast, `package-user-dir' contains packages for personal use."
292 :type '(repeat directory)
293 :risky t
294 :group 'package
295 :version "24.1")
297 (defvar epg-gpg-program)
299 (defcustom package-check-signature
300 (if (progn (require 'epg-config) (executable-find epg-gpg-program))
301 'allow-unsigned)
302 "Non-nil means to check package signatures when installing.
303 The value `allow-unsigned' means to still install a package even if
304 it is unsigned.
306 This also applies to the \"archive-contents\" file that lists the
307 contents of the archive."
308 :type '(choice (const nil :tag "Never")
309 (const allow-unsigned :tag "Allow unsigned")
310 (const t :tag "Check always"))
311 :risky t
312 :group 'package
313 :version "24.4")
315 (defcustom package-unsigned-archives nil
316 "List of archives where we do not check for package signatures."
317 :type '(repeat (string :tag "Archive name"))
318 :risky t
319 :group 'package
320 :version "24.4")
322 (defcustom package-selected-packages nil
323 "Store here packages installed explicitly by user.
324 This variable is fed automatically by Emacs when installing a new package.
325 This variable is used by `package-autoremove' to decide
326 which packages are no longer needed.
327 You can use it to (re)install packages on other machines
328 by running `package-user-selected-packages-install'.
330 To check if a package is contained in this list here, use
331 `package--user-selected-p', as it may populate the variable with
332 a sane initial value."
333 :group 'package
334 :type '(repeat symbol))
337 ;;; `package-desc' object definition
338 ;; This is the struct used internally to represent packages.
339 ;; Functions that deal with packages should generally take this object
340 ;; as an argument. In some situations (e.g. commands that query the
341 ;; user) it makes sense to take the package name as a symbol instead,
342 ;; but keep in mind there could be multiple `package-desc's with the
343 ;; same name.
344 (defvar package--default-summary "No description available.")
346 (cl-defstruct (package-desc
347 ;; Rename the default constructor from `make-package-desc'.
348 (:constructor package-desc-create)
349 ;; Has the same interface as the old `define-package',
350 ;; which is still used in the "foo-pkg.el" files. Extra
351 ;; options can be supported by adding additional keys.
352 (:constructor
353 package-desc-from-define
354 (name-string version-string &optional summary requirements
355 &rest rest-plist
356 &aux
357 (name (intern name-string))
358 (version (version-to-list version-string))
359 (reqs (mapcar #'(lambda (elt)
360 (list (car elt)
361 (version-to-list (cadr elt))))
362 (if (eq 'quote (car requirements))
363 (nth 1 requirements)
364 requirements)))
365 (kind (plist-get rest-plist :kind))
366 (archive (plist-get rest-plist :archive))
367 (extras (let (alist)
368 (while rest-plist
369 (unless (memq (car rest-plist) '(:kind :archive))
370 (let ((value (cadr rest-plist)))
371 (when value
372 (push (cons (car rest-plist)
373 (if (eq (car-safe value) 'quote)
374 (cadr value)
375 value))
376 alist))))
377 (setq rest-plist (cddr rest-plist)))
378 alist)))))
379 "Structure containing information about an individual package.
380 Slots:
382 `name' Name of the package, as a symbol.
384 `version' Version of the package, as a version list.
386 `summary' Short description of the package, typically taken from
387 the first line of the file.
389 `reqs' Requirements of the package. A list of (PACKAGE
390 VERSION-LIST) naming the dependent package and the minimum
391 required version.
393 `kind' The distribution format of the package. Currently, it is
394 either `single' or `tar'.
396 `archive' The name of the archive (as a string) whence this
397 package came.
399 `dir' The directory where the package is installed (if installed),
400 `builtin' if it is built-in, or nil otherwise.
402 `extras' Optional alist of additional keyword-value pairs.
404 `signed' Flag to indicate that the package is signed by provider."
405 name
406 version
407 (summary package--default-summary)
408 reqs
409 kind
410 archive
412 extras
413 signed)
415 (defun package--from-builtin (bi-desc)
416 (package-desc-create :name (pop bi-desc)
417 :version (package--bi-desc-version bi-desc)
418 :summary (package--bi-desc-summary bi-desc)
419 :dir 'builtin))
421 ;; Pseudo fields.
422 (defun package-version-join (vlist)
423 "Return the version string corresponding to the list VLIST.
424 This is, approximately, the inverse of `version-to-list'.
425 \(Actually, it returns only one of the possible inverses, since
426 `version-to-list' is a many-to-one operation.)"
427 (if (null vlist)
429 (let ((str-list (list "." (int-to-string (car vlist)))))
430 (dolist (num (cdr vlist))
431 (cond
432 ((>= num 0)
433 (push (int-to-string num) str-list)
434 (push "." str-list))
435 ((< num -4)
436 (error "Invalid version list `%s'" vlist))
438 ;; pre, or beta, or alpha
439 (cond ((equal "." (car str-list))
440 (pop str-list))
441 ((not (string-match "[0-9]+" (car str-list)))
442 (error "Invalid version list `%s'" vlist)))
443 (push (cond ((= num -1) "pre")
444 ((= num -2) "beta")
445 ((= num -3) "alpha")
446 ((= num -4) "snapshot"))
447 str-list))))
448 (if (equal "." (car str-list))
449 (pop str-list))
450 (apply 'concat (nreverse str-list)))))
452 (defun package-desc-full-name (pkg-desc)
453 (format "%s-%s"
454 (package-desc-name pkg-desc)
455 (package-version-join (package-desc-version pkg-desc))))
457 (defun package-desc-suffix (pkg-desc)
458 (pcase (package-desc-kind pkg-desc)
459 (`single ".el")
460 (`tar ".tar")
461 (`dir "")
462 (kind (error "Unknown package kind: %s" kind))))
464 (defun package-desc--keywords (pkg-desc)
465 (let ((keywords (cdr (assoc :keywords (package-desc-extras pkg-desc)))))
466 (if (eq (car-safe keywords) 'quote)
467 (nth 1 keywords)
468 keywords)))
470 ;; Package descriptor format used in finder-inf.el and package--builtins.
471 (cl-defstruct (package--bi-desc
472 (:constructor package-make-builtin (version summary))
473 (:type vector))
474 version
475 reqs
476 summary)
479 ;;; Installed packages
480 ;; The following variables store information about packages present in
481 ;; the system. The most important of these is `package-alist'. The
482 ;; command `package-initialize' is also closely related to this
483 ;; section, but it is left for a later section because it also affects
484 ;; other stuff.
485 (defvar package--builtins nil
486 "Alist of built-in packages.
487 The actual value is initialized by loading the library
488 `finder-inf'; this is not done until it is needed, e.g. by the
489 function `package-built-in-p'.
491 Each element has the form (PKG . PACKAGE-BI-DESC), where PKG is a package
492 name (a symbol) and DESC is a `package--bi-desc' structure.")
493 (put 'package--builtins 'risky-local-variable t)
495 (defvar package-alist nil
496 "Alist of all packages available for activation.
497 Each element has the form (PKG . DESCS), where PKG is a package
498 name (a symbol) and DESCS is a non-empty list of `package-desc' structure,
499 sorted by decreasing versions.
501 This variable is set automatically by `package-load-descriptor',
502 called via `package-initialize'. To change which packages are
503 loaded and/or activated, customize `package-load-list'.")
504 (put 'package-alist 'risky-local-variable t)
506 (defvar package-activated-list nil
507 ;; FIXME: This should implicitly include all builtin packages.
508 "List of the names of currently activated packages.")
509 (put 'package-activated-list 'risky-local-variable t)
511 ;;;; Populating `package-alist'.
512 ;; The following functions are called on each installed package by
513 ;; `package-load-all-descriptors', which ultimately populates the
514 ;; `package-alist' variable.
515 (defun package-process-define-package (exp)
516 (when (eq (car-safe exp) 'define-package)
517 (let* ((new-pkg-desc (apply #'package-desc-from-define (cdr exp)))
518 (name (package-desc-name new-pkg-desc))
519 (version (package-desc-version new-pkg-desc))
520 (old-pkgs (assq name package-alist)))
521 (if (null old-pkgs)
522 ;; If there's no old package, just add this to `package-alist'.
523 (push (list name new-pkg-desc) package-alist)
524 ;; If there is, insert the new package at the right place in the list.
525 (while
526 (if (and (cdr old-pkgs)
527 (version-list-< version
528 (package-desc-version (cadr old-pkgs))))
529 (setq old-pkgs (cdr old-pkgs))
530 (push new-pkg-desc (cdr old-pkgs))
531 nil)))
532 new-pkg-desc)))
534 (defun package-load-descriptor (pkg-dir)
535 "Load the description file in directory PKG-DIR."
536 (let ((pkg-file (expand-file-name (package--description-file pkg-dir)
537 pkg-dir))
538 (signed-file (concat pkg-dir ".signed")))
539 (when (file-exists-p pkg-file)
540 (with-temp-buffer
541 (insert-file-contents pkg-file)
542 (goto-char (point-min))
543 (let ((pkg-desc (or (package-process-define-package
544 (read (current-buffer)))
545 (error "Can't find define-package in %s" pkg-file))))
546 (setf (package-desc-dir pkg-desc) pkg-dir)
547 (if (file-exists-p signed-file)
548 (setf (package-desc-signed pkg-desc) t))
549 pkg-desc)))))
551 (defun package-load-all-descriptors ()
552 "Load descriptors for installed Emacs Lisp packages.
553 This looks for package subdirectories in `package-user-dir' and
554 `package-directory-list'. The variable `package-load-list'
555 controls which package subdirectories may be loaded.
557 In each valid package subdirectory, this function loads the
558 description file containing a call to `define-package', which
559 updates `package-alist'."
560 (dolist (dir (cons package-user-dir package-directory-list))
561 (when (file-directory-p dir)
562 (dolist (subdir (directory-files dir))
563 (let ((pkg-dir (expand-file-name subdir dir)))
564 (when (file-directory-p pkg-dir)
565 (package-load-descriptor pkg-dir)))))))
567 (defun define-package (_name-string _version-string
568 &optional _docstring _requirements
569 &rest _extra-properties)
570 "Define a new package.
571 NAME-STRING is the name of the package, as a string.
572 VERSION-STRING is the version of the package, as a string.
573 DOCSTRING is a short description of the package, a string.
574 REQUIREMENTS is a list of dependencies on other packages.
575 Each requirement is of the form (OTHER-PACKAGE OTHER-VERSION),
576 where OTHER-VERSION is a string.
578 EXTRA-PROPERTIES is currently unused."
579 ;; FIXME: Placeholder! Should we keep it?
580 (error "Don't call me!"))
583 ;;; Package activation
584 ;; Section for functions used by `package-activate', which see.
585 (defun package-disabled-p (pkg-name version)
586 "Return whether PKG-NAME at VERSION can be activated.
587 The decision is made according to `package-load-list'.
588 Return nil if the package can be activated.
589 Return t if the package is completely disabled.
590 Return the max version (as a string) if the package is held at a lower version."
591 (let ((force (assq pkg-name package-load-list)))
592 (cond ((null force) (not (memq 'all package-load-list)))
593 ((null (setq force (cadr force))) t) ; disabled
594 ((eq force t) nil)
595 ((stringp force) ; held
596 (unless (version-list-= version (version-to-list force))
597 force))
598 (t (error "Invalid element in `package-load-list'")))))
600 (defun package-built-in-p (package &optional min-version)
601 "Return true if PACKAGE is built-in to Emacs.
602 Optional arg MIN-VERSION, if non-nil, should be a version list
603 specifying the minimum acceptable version."
604 (if (package-desc-p package) ;; was built-in and then was converted
605 (eq 'builtin (package-desc-dir package))
606 (let ((bi (assq package package--builtin-versions)))
607 (cond
608 (bi (version-list-<= min-version (cdr bi)))
609 ((remove 0 min-version) nil)
611 (require 'finder-inf nil t) ; For `package--builtins'.
612 (assq package package--builtins))))))
614 (defvar Info-directory-list)
615 (declare-function info-initialize "info" ())
617 (defun package-activate-1 (pkg-desc &optional reload)
618 "Activate package given by PKG-DESC, even if it was already active.
619 If RELOAD is non-nil, also `load' any files inside the package which
620 correspond to previously loaded files (those returned by
621 `package--list-loaded-files')."
622 (let* ((name (package-desc-name pkg-desc))
623 (pkg-dir (package-desc-dir pkg-desc))
624 (pkg-dir-dir (file-name-as-directory pkg-dir)))
625 (unless pkg-dir
626 (error "Internal error: unable to find directory for `%s'"
627 (package-desc-full-name pkg-desc)))
628 ;; Add to load path, add autoloads, and activate the package.
629 (let* ((old-lp load-path)
630 (autoloads-file (expand-file-name
631 (format "%s-autoloads" name) pkg-dir))
632 (loaded-files-list (and reload (package--list-loaded-files pkg-dir))))
633 (with-demoted-errors "Error in package-activate-1: %s"
634 (load autoloads-file nil t))
635 (when (and (eq old-lp load-path)
636 (not (or (member pkg-dir load-path)
637 (member pkg-dir-dir load-path))))
638 ;; Old packages don't add themselves to the `load-path', so we have to
639 ;; do it ourselves.
640 (push pkg-dir load-path))
641 ;; Call `load' on all files in `pkg-dir' already present in
642 ;; `load-history'. This is done so that macros in these files are updated
643 ;; to their new definitions. If another package is being installed which
644 ;; depends on this new definition, not doing this update would cause
645 ;; compilation errors and break the installation.
646 (with-demoted-errors "Error in package-activate-1: %s"
647 (mapc (lambda (feature) (load feature nil t))
648 ;; Skip autoloads file since we already evaluated it above.
649 (remove (file-truename autoloads-file) loaded-files-list))))
650 ;; Add info node.
651 (when (file-exists-p (expand-file-name "dir" pkg-dir))
652 ;; FIXME: not the friendliest, but simple.
653 (require 'info)
654 (info-initialize)
655 (push pkg-dir Info-directory-list))
656 (push name package-activated-list)
657 ;; Don't return nil.
660 (declare-function find-library-name "find-func" (library))
662 (defun package--list-loaded-files (dir)
663 "Recursively list all files in DIR which correspond to loaded features.
664 Returns the `file-name-sans-extension' of each file, relative to
665 DIR, sorted by most recently loaded last."
666 (let* ((history (delq nil
667 (mapcar (lambda (x)
668 (let ((f (car x)))
669 (and f (file-name-sans-extension f))))
670 load-history)))
671 (dir (file-truename dir))
672 ;; List all files that have already been loaded.
673 (list-of-conflicts
674 (delq
676 (mapcar
677 (lambda (x) (let* ((file (file-relative-name x dir))
678 ;; Previously loaded file, if any.
679 (previous
680 (ignore-errors
681 (file-name-sans-extension
682 (file-truename (find-library-name file)))))
683 (pos (when previous (member previous history))))
684 ;; Return (RELATIVE-FILENAME . HISTORY-POSITION)
685 (when pos
686 (cons (file-name-sans-extension file) (length pos)))))
687 (directory-files-recursively dir "\\`[^\\.].*\\.el\\'")))))
688 ;; Turn the list of (FILENAME . POS) back into a list of features. Files in
689 ;; subdirectories are returned relative to DIR (so not actually features).
690 (let ((default-directory (file-name-as-directory dir)))
691 (mapcar (lambda (x) (file-truename (car x)))
692 (sort list-of-conflicts
693 ;; Sort the files by ascending HISTORY-POSITION.
694 (lambda (x y) (< (cdr x) (cdr y))))))))
696 ;;;; `package-activate'
697 ;; This function activates a newer version of a package if an older
698 ;; one was already activated. It also loads a features of this
699 ;; package which were already loaded.
700 (defun package-activate (package &optional force)
701 "Activate package PACKAGE.
702 If FORCE is true, (re-)activate it if it's already activated.
703 Newer versions are always activated, regardless of FORCE."
704 (let ((pkg-descs (cdr (assq package package-alist))))
705 ;; Check if PACKAGE is available in `package-alist'.
706 (while
707 (when pkg-descs
708 (let ((available-version (package-desc-version (car pkg-descs))))
709 (or (package-disabled-p package available-version)
710 ;; Prefer a builtin package.
711 (package-built-in-p package available-version))))
712 (setq pkg-descs (cdr pkg-descs)))
713 (cond
714 ;; If no such package is found, maybe it's built-in.
715 ((null pkg-descs)
716 (package-built-in-p package))
717 ;; If the package is already activated, just return t.
718 ((and (memq package package-activated-list) (not force))
720 ;; Otherwise, proceed with activation.
722 (let* ((pkg-vec (car pkg-descs))
723 (fail (catch 'dep-failure
724 ;; Activate its dependencies recursively.
725 (dolist (req (package-desc-reqs pkg-vec))
726 (unless (package-activate (car req))
727 (throw 'dep-failure req))))))
728 (if fail
729 (warn "Unable to activate package `%s'.
730 Required package `%s-%s' is unavailable"
731 package (car fail) (package-version-join (cadr fail)))
732 ;; If all goes well, activate the package itself.
733 (package-activate-1 pkg-vec force)))))))
736 ;;; Installation -- Local operations
737 ;; This section contains a variety of features regarding installing a
738 ;; package to/from disk. This includes autoload generation,
739 ;; unpacking, compiling, as well as defining a package from the
740 ;; current buffer.
742 ;;;; Unpacking
743 (defvar tar-parse-info)
744 (declare-function tar-untar-buffer "tar-mode" ())
745 (declare-function tar-header-name "tar-mode" (tar-header) t)
746 (declare-function tar-header-link-type "tar-mode" (tar-header) t)
748 (defun package-untar-buffer (dir)
749 "Untar the current buffer.
750 This uses `tar-untar-buffer' from Tar mode. All files should
751 untar into a directory named DIR; otherwise, signal an error."
752 (require 'tar-mode)
753 (tar-mode)
754 ;; Make sure everything extracts into DIR.
755 (let ((regexp (concat "\\`" (regexp-quote (expand-file-name dir)) "/"))
756 (case-fold-search (memq system-type '(windows-nt ms-dos cygwin))))
757 (dolist (tar-data tar-parse-info)
758 (let ((name (expand-file-name (tar-header-name tar-data))))
759 (or (string-match regexp name)
760 ;; Tarballs created by some utilities don't list
761 ;; directories with a trailing slash (Bug#13136).
762 (and (string-equal dir name)
763 (eq (tar-header-link-type tar-data) 5))
764 (error "Package does not untar cleanly into directory %s/" dir)))))
765 (tar-untar-buffer))
767 (defun package--alist-to-plist-args (alist)
768 (mapcar 'macroexp-quote
769 (apply #'nconc
770 (mapcar (lambda (pair) (list (car pair) (cdr pair))) alist))))
771 (defun package-unpack (pkg-desc)
772 "Install the contents of the current buffer as a package."
773 (let* ((name (package-desc-name pkg-desc))
774 (dirname (package-desc-full-name pkg-desc))
775 (pkg-dir (expand-file-name dirname package-user-dir)))
776 (pcase (package-desc-kind pkg-desc)
777 (`dir
778 (make-directory pkg-dir t)
779 (let ((file-list
780 (directory-files
781 default-directory 'full "\\`[^.].*\\.el\\'" 'nosort)))
782 (dolist (source-file file-list)
783 (let ((target-el-file
784 (expand-file-name (file-name-nondirectory source-file) pkg-dir)))
785 (copy-file source-file target-el-file t)))
786 ;; Now that the files have been installed, this package is
787 ;; indistinguishable from a `tar' or a `single'. Let's make
788 ;; things simple by ensuring we're one of them.
789 (setf (package-desc-kind pkg-desc)
790 (if (> (length file-list) 1) 'tar 'single))))
791 (`tar
792 (make-directory package-user-dir t)
793 ;; FIXME: should we delete PKG-DIR if it exists?
794 (let* ((default-directory (file-name-as-directory package-user-dir)))
795 (package-untar-buffer dirname)))
796 (`single
797 (let ((el-file (expand-file-name (format "%s.el" name) pkg-dir)))
798 (make-directory pkg-dir t)
799 (package--write-file-no-coding el-file)))
800 (kind (error "Unknown package kind: %S" kind)))
801 (package--make-autoloads-and-stuff pkg-desc pkg-dir)
802 ;; Update package-alist.
803 (let ((new-desc (package-load-descriptor pkg-dir)))
804 ;; FIXME: Check that `new-desc' matches `desc'!
805 ;; FIXME: Compilation should be done as a separate, optional, step.
806 ;; E.g. for multi-package installs, we should first install all packages
807 ;; and then compile them.
808 (package--compile new-desc))
809 ;; Try to activate it.
810 (package-activate name 'force)
811 pkg-dir))
813 (defun package-generate-description-file (pkg-desc pkg-file)
814 "Create the foo-pkg.el file for single-file packages."
815 (let* ((name (package-desc-name pkg-desc)))
816 (let ((print-level nil)
817 (print-quoted t)
818 (print-length nil))
819 (write-region
820 (concat
821 ";;; -*- no-byte-compile: t -*-\n"
822 (prin1-to-string
823 (nconc
824 (list 'define-package
825 (symbol-name name)
826 (package-version-join (package-desc-version pkg-desc))
827 (package-desc-summary pkg-desc)
828 (let ((requires (package-desc-reqs pkg-desc)))
829 (list 'quote
830 ;; Turn version lists into string form.
831 (mapcar
832 (lambda (elt)
833 (list (car elt)
834 (package-version-join (cadr elt))))
835 requires))))
836 (package--alist-to-plist-args
837 (package-desc-extras pkg-desc))))
838 "\n")
839 nil pkg-file nil 'silent))))
841 ;;;; Autoload
842 ;; From Emacs 22, but changed so it adds to load-path.
843 (defun package-autoload-ensure-default-file (file)
844 "Make sure that the autoload file FILE exists and if not create it."
845 (unless (file-exists-p file)
846 (write-region
847 (concat ";;; " (file-name-nondirectory file)
848 " --- automatically extracted autoloads\n"
849 ";;\n"
850 ";;; Code:\n"
851 "(add-to-list 'load-path (or (file-name-directory #$) (car load-path)))\n"
852 "\f\n;; Local Variables:\n"
853 ";; version-control: never\n"
854 ";; no-byte-compile: t\n"
855 ";; no-update-autoloads: t\n"
856 ";; End:\n"
857 ";;; " (file-name-nondirectory file)
858 " ends here\n")
859 nil file nil 'silent))
860 file)
862 (defvar generated-autoload-file)
863 (defvar version-control)
865 (defun package-generate-autoloads (name pkg-dir)
866 (let* ((auto-name (format "%s-autoloads.el" name))
867 ;;(ignore-name (concat name "-pkg.el"))
868 (generated-autoload-file (expand-file-name auto-name pkg-dir))
869 (backup-inhibited t)
870 (version-control 'never))
871 (package-autoload-ensure-default-file generated-autoload-file)
872 (update-directory-autoloads pkg-dir)
873 (let ((buf (find-buffer-visiting generated-autoload-file)))
874 (when buf (kill-buffer buf)))
875 auto-name))
877 (defun package--make-autoloads-and-stuff (pkg-desc pkg-dir)
878 "Generate autoloads, description file, etc.. for PKG-DESC installed at PKG-DIR."
879 (package-generate-autoloads (package-desc-name pkg-desc) pkg-dir)
880 (let ((desc-file (expand-file-name (package--description-file pkg-dir)
881 pkg-dir)))
882 (unless (file-exists-p desc-file)
883 (package-generate-description-file pkg-desc desc-file)))
884 ;; FIXME: Create foo.info and dir file from foo.texi?
887 ;;;; Compilation
888 (defun package--compile (pkg-desc)
889 "Byte-compile installed package PKG-DESC."
890 (package-activate-1 pkg-desc)
891 (byte-recompile-directory (package-desc-dir pkg-desc) 0 t))
893 ;;;; Inferring package from current buffer
894 (defun package-read-from-string (str)
895 "Read a Lisp expression from STR.
896 Signal an error if the entire string was not used."
897 (let* ((read-data (read-from-string str))
898 (more-left
899 (condition-case nil
900 ;; The call to `ignore' suppresses a compiler warning.
901 (progn (ignore (read-from-string
902 (substring str (cdr read-data))))
904 (end-of-file nil))))
905 (if more-left
906 (error "Can't read whole string")
907 (car read-data))))
909 (defun package--prepare-dependencies (deps)
910 "Turn DEPS into an acceptable list of dependencies.
912 Any parts missing a version string get a default version string
913 of \"0\" (meaning any version) and an appropriate level of lists
914 is wrapped around any parts requiring it."
915 (cond
916 ((not (listp deps))
917 (error "Invalid requirement specifier: %S" deps))
918 (t (mapcar (lambda (dep)
919 (cond
920 ((symbolp dep) `(,dep "0"))
921 ((stringp dep)
922 (error "Invalid requirement specifier: %S" dep))
923 ((and (listp dep) (null (cdr dep)))
924 (list (car dep) "0"))
925 (t dep)))
926 deps))))
928 (declare-function lm-header "lisp-mnt" (header))
929 (declare-function lm-homepage "lisp-mnt" ())
931 (defun package-buffer-info ()
932 "Return a `package-desc' describing the package in the current buffer.
934 If the buffer does not contain a conforming package, signal an
935 error. If there is a package, narrow the buffer to the file's
936 boundaries."
937 (goto-char (point-min))
938 (unless (re-search-forward "^;;; \\([^ ]*\\)\\.el ---[ \t]*\\(.*?\\)[ \t]*\\(-\\*-.*-\\*-[ \t]*\\)?$" nil t)
939 (error "Package lacks a file header"))
940 (let ((file-name (match-string-no-properties 1))
941 (desc (match-string-no-properties 2))
942 (start (line-beginning-position)))
943 (unless (search-forward (concat ";;; " file-name ".el ends here"))
944 (error "Package lacks a terminating comment"))
945 ;; Try to include a trailing newline.
946 (forward-line)
947 (narrow-to-region start (point))
948 (require 'lisp-mnt)
949 ;; Use some headers we've invented to drive the process.
950 (let* ((requires-str (lm-header "package-requires"))
951 ;; Prefer Package-Version; if defined, the package author
952 ;; probably wants us to use it. Otherwise try Version.
953 (pkg-version
954 (or (package-strip-rcs-id (lm-header "package-version"))
955 (package-strip-rcs-id (lm-header "version"))))
956 (homepage (lm-homepage)))
957 (unless pkg-version
958 (error
959 "Package lacks a \"Version\" or \"Package-Version\" header"))
960 (package-desc-from-define
961 file-name pkg-version desc
962 (if requires-str
963 (package--prepare-dependencies
964 (package-read-from-string requires-str)))
965 :kind 'single
966 :url homepage))))
968 (defun package--read-pkg-desc (kind)
969 "Read a `define-package' form in current buffer.
970 Return the pkg-desc, with desc-kind set to KIND."
971 (goto-char (point-min))
972 (unwind-protect
973 (let* ((pkg-def-parsed (read (current-buffer)))
974 (pkg-desc
975 (when (eq (car pkg-def-parsed) 'define-package)
976 (apply #'package-desc-from-define
977 (append (cdr pkg-def-parsed))))))
978 (when pkg-desc
979 (setf (package-desc-kind pkg-desc) kind)
980 pkg-desc))))
982 (declare-function tar-get-file-descriptor "tar-mode" (file))
983 (declare-function tar--extract "tar-mode" (descriptor))
985 (defun package-tar-file-info ()
986 "Find package information for a tar file.
987 The return result is a `package-desc'."
988 (cl-assert (derived-mode-p 'tar-mode))
989 (let* ((dir-name (file-name-directory
990 (tar-header-name (car tar-parse-info))))
991 (desc-file (package--description-file dir-name))
992 (tar-desc (tar-get-file-descriptor (concat dir-name desc-file))))
993 (unless tar-desc
994 (error "No package descriptor file found"))
995 (with-current-buffer (tar--extract tar-desc)
996 (unwind-protect
997 (or (package--read-pkg-desc 'tar)
998 (error "Can't find define-package in %s"
999 (tar-header-name tar-desc)))
1000 (kill-buffer (current-buffer))))))
1002 (defun package-dir-info ()
1003 "Find package information for a directory.
1004 The return result is a `package-desc'."
1005 (cl-assert (derived-mode-p 'dired-mode))
1006 (let* ((desc-file (package--description-file default-directory)))
1007 (if (file-readable-p desc-file)
1008 (with-temp-buffer
1009 (insert-file-contents desc-file)
1010 (package--read-pkg-desc 'dir))
1011 (let ((files (directory-files default-directory t "\\.el\\'" t))
1012 info)
1013 (while files
1014 (with-temp-buffer
1015 (insert-file-contents (pop files))
1016 ;; When we find the file with the data,
1017 (when (setq info (ignore-errors (package-buffer-info)))
1018 ;; stop looping,
1019 (setq files nil)
1020 ;; set the 'dir kind,
1021 (setf (package-desc-kind info) 'dir))))
1022 ;; and return the info.
1023 info))))
1026 ;;; Communicating with Archives
1027 ;; Set of low-level functions for communicating with archives and
1028 ;; signature checking.
1029 (defun package--write-file-no-coding (file-name)
1030 (let ((buffer-file-coding-system 'no-conversion))
1031 (write-region (point-min) (point-max) file-name nil 'silent)))
1033 (declare-function url-http-file-exists-p "url-http" (url))
1035 (defun package--archive-file-exists-p (location file)
1036 (let ((http (string-match "\\`https?:" location)))
1037 (if http
1038 (progn
1039 (require 'url-http)
1040 (url-http-file-exists-p (concat location file)))
1041 (file-exists-p (expand-file-name file location)))))
1043 (declare-function epg-make-context "epg"
1044 (&optional protocol armor textmode include-certs
1045 cipher-algorithm
1046 digest-algorithm
1047 compress-algorithm))
1048 (declare-function epg-verify-string "epg" (context signature
1049 &optional signed-text))
1050 (declare-function epg-context-result-for "epg" (context name))
1051 (declare-function epg-signature-status "epg" (signature))
1052 (declare-function epg-signature-to-string "epg" (signature))
1054 (defun package--display-verify-error (context sig-file)
1055 (unless (equal (epg-context-error-output context) "")
1056 (with-output-to-temp-buffer "*Error*"
1057 (with-current-buffer standard-output
1058 (if (epg-context-result-for context 'verify)
1059 (insert (format "Failed to verify signature %s:\n" sig-file)
1060 (mapconcat #'epg-signature-to-string
1061 (epg-context-result-for context 'verify)
1062 "\n"))
1063 (insert (format "Error while verifying signature %s:\n" sig-file)))
1064 (insert "\nCommand output:\n" (epg-context-error-output context))))))
1066 (defmacro package--with-work-buffer (location file &rest body)
1067 "Run BODY in a buffer containing the contents of FILE at LOCATION.
1068 LOCATION is the base location of a package archive, and should be
1069 one of the URLs (or file names) specified in `package-archives'.
1070 FILE is the name of a file relative to that base location.
1072 This macro retrieves FILE from LOCATION into a temporary buffer,
1073 and evaluates BODY while that buffer is current. This work
1074 buffer is killed afterwards. Return the last value in BODY."
1075 (declare (indent 2) (debug t))
1076 `(with-temp-buffer
1077 (if (string-match-p "\\`https?:" ,location)
1078 (url-insert-file-contents (concat ,location ,file))
1079 (unless (file-name-absolute-p ,location)
1080 (error "Archive location %s is not an absolute file name"
1081 ,location))
1082 (insert-file-contents (expand-file-name ,file ,location)))
1083 ,@body))
1085 (defmacro package--with-work-buffer-async (location file async &rest body)
1086 "Run BODY in a buffer containing the contents of FILE at LOCATION.
1087 If ASYNC is non-nil, and if it is possible, run BODY
1088 asynchronously. If an error is encountered and ASYNC is a
1089 function, call it with no arguments (instead of executing BODY),
1090 otherwise propagate the error. For description of the other
1091 arguments see `package--with-work-buffer'."
1092 (declare (indent 3) (debug t))
1093 (macroexp-let2* macroexp-copyable-p
1094 ((async-1 async)
1095 (file-1 file)
1096 (location-1 location))
1097 `(if (or (not ,async-1)
1098 (not (string-match-p "\\`https?:" ,location-1)))
1099 (package--with-work-buffer ,location-1 ,file-1 ,@body)
1100 (url-retrieve (concat ,location-1 ,file-1)
1101 (lambda (status)
1102 (if (eq (car status) :error)
1103 (if (functionp ,async-1)
1104 (funcall ,async-1)
1105 (signal (cdar status) (cddr status)))
1106 (goto-char (point-min))
1107 (unless (search-forward "\n\n" nil 'noerror)
1108 (error "Invalid url response"))
1109 (delete-region (point-min) (point))
1110 ,@body)
1111 (kill-buffer (current-buffer)))
1113 'silent))))
1115 (defun package--check-signature-content (content string &optional sig-file)
1116 "Check signature CONTENT against STRING.
1117 SIG-FILE is the name of the signature file, used when signaling
1118 errors."
1119 (let* ((context (epg-make-context 'OpenPGP))
1120 (homedir (expand-file-name "gnupg" package-user-dir)))
1121 (setf (epg-context-home-directory context) homedir)
1122 (condition-case error
1123 (epg-verify-string context content string)
1124 (error (package--display-verify-error context sig-file)
1125 (signal (car error) (cdr error))))
1126 (let (good-signatures had-fatal-error)
1127 ;; The .sig file may contain multiple signatures. Success if one
1128 ;; of the signatures is good.
1129 (dolist (sig (epg-context-result-for context 'verify))
1130 (if (eq (epg-signature-status sig) 'good)
1131 (push sig good-signatures)
1132 ;; If package-check-signature is allow-unsigned, don't
1133 ;; signal error when we can't verify signature because of
1134 ;; missing public key. Other errors are still treated as
1135 ;; fatal (bug#17625).
1136 (unless (and (eq package-check-signature 'allow-unsigned)
1137 (eq (epg-signature-status sig) 'no-pubkey))
1138 (setq had-fatal-error t))))
1139 (when (and (null good-signatures) had-fatal-error)
1140 (package--display-verify-error context sig-file)
1141 (error "Failed to verify signature %s" sig-file))
1142 good-signatures)))
1144 (defun package--check-signature (location file &optional string async callback)
1145 "Check signature of the current buffer.
1146 Download the signature file from LOCATION by appending \".sig\"
1147 to FILE.
1148 GnuPG keyring is located under \"gnupg\" in `package-user-dir'.
1149 STRING is the string to verify, it defaults to `buffer-string'.
1150 If ASYNC is non-nil, the download of the signature file is
1151 done asynchronously.
1153 If the signature is verified and CALLBACK was provided, CALLBACK
1154 is `funcall'ed with the list of good signatures as argument (the
1155 list can be empty). If the signatures file is not found,
1156 CALLBACK is called with no arguments."
1157 (let ((sig-file (concat file ".sig"))
1158 (string (or string (buffer-string))))
1159 (condition-case nil
1160 (package--with-work-buffer-async
1161 location sig-file (when async (or callback t))
1162 (let ((sig (package--check-signature-content
1163 (buffer-string) string sig-file)))
1164 (when callback (funcall callback sig))
1165 sig))
1166 (file-error (funcall callback)))))
1169 ;;; Packages on Archives
1170 ;; The following variables store information about packages available
1171 ;; from archives. The most important of these is
1172 ;; `package-archive-contents' which is initially populated by the
1173 ;; function `package-read-all-archive-contents' from a cache on disk.
1174 ;; The `package-initialize' command is also closely related to this
1175 ;; section, but it has its own section.
1176 (defconst package-archive-version 1
1177 "Version number of the package archive understood by this file.
1178 Lower version numbers than this will probably be understood as well.")
1180 ;; We don't prime the cache since it tends to get out of date.
1181 (defvar package-archive-contents nil
1182 "Cache of the contents of the Emacs Lisp Package Archive.
1183 This is an alist mapping package names (symbols) to
1184 non-empty lists of `package-desc' structures.")
1185 (put 'package-archive-contents 'risky-local-variable t)
1187 (defvar package--compatibility-table nil
1188 "Hash table connecting package names to their compatibility.
1189 Each key is a symbol, the name of a package.
1191 The value is either nil, representing an incompatible package, or
1192 a version list, representing the highest compatible version of
1193 that package which is available.
1195 A package is considered incompatible if it requires an Emacs
1196 version higher than the one being used. To check for package
1197 \(in)compatibility, don't read this table directly, use
1198 `package--incompatible-p' which also checks dependencies.")
1200 (defun package--build-compatibility-table ()
1201 "Build `package--compatibility-table' with `package--mapc'."
1202 ;; Build compat table.
1203 (setq package--compatibility-table (make-hash-table :test 'eq))
1204 (package--mapc #'package--add-to-compatibility-table))
1206 (defun package--add-to-compatibility-table (pkg)
1207 "If PKG is compatible (without dependencies), add to the compatibility table.
1208 PKG is a package-desc object.
1209 Only adds if its version is higher than what's already stored in
1210 the table."
1211 (unless (package--incompatible-p pkg 'shallow)
1212 (let* ((name (package-desc-name pkg))
1213 (version (or (package-desc-version pkg) '(0)))
1214 (table-version (gethash name package--compatibility-table)))
1215 (when (or (not table-version)
1216 (version-list-< table-version version))
1217 (puthash name version package--compatibility-table)))))
1219 ;; Package descriptor objects used inside the "archive-contents" file.
1220 ;; Changing this defstruct implies changing the format of the
1221 ;; "archive-contents" files.
1222 (cl-defstruct (package--ac-desc
1223 (:constructor package-make-ac-desc (version reqs summary kind extras))
1224 (:copier nil)
1225 (:type vector))
1226 version reqs summary kind extras)
1228 (defun package--append-to-alist (pkg-desc alist)
1229 "Append an entry for PKG-DESC to the start of ALIST and return it.
1230 This entry takes the form (`package-desc-name' PKG-DESC).
1232 If ALIST already has an entry with this name, destructively add
1233 PKG-DESC to the cdr of this entry instead, sorted by version
1234 number."
1235 (let* ((name (package-desc-name pkg-desc))
1236 (priority-version (package-desc-priority-version pkg-desc))
1237 (existing-packages (assq name alist)))
1238 (if (not existing-packages)
1239 (cons (list name pkg-desc)
1240 alist)
1241 (while (if (and (cdr existing-packages)
1242 (version-list-< priority-version
1243 (package-desc-priority-version
1244 (cadr existing-packages))))
1245 (setq existing-packages (cdr existing-packages))
1246 (push pkg-desc (cdr existing-packages))
1247 nil))
1248 alist)))
1250 (defun package--add-to-archive-contents (package archive)
1251 "Add the PACKAGE from the given ARCHIVE if necessary.
1252 PACKAGE should have the form (NAME . PACKAGE--AC-DESC).
1253 Also, add the originating archive to the `package-desc' structure."
1254 (let* ((name (car package))
1255 (version (package--ac-desc-version (cdr package)))
1256 (pkg-desc
1257 (package-desc-create
1258 :name name
1259 :version version
1260 :reqs (package--ac-desc-reqs (cdr package))
1261 :summary (package--ac-desc-summary (cdr package))
1262 :kind (package--ac-desc-kind (cdr package))
1263 :archive archive
1264 :extras (and (> (length (cdr package)) 4)
1265 ;; Older archive-contents files have only 4
1266 ;; elements here.
1267 (package--ac-desc-extras (cdr package)))))
1268 (pinned-to-archive (assoc name package-pinned-packages)))
1269 ;; Skip entirely if pinned to another archive.
1270 (when (not (and pinned-to-archive
1271 (not (equal (cdr pinned-to-archive) archive))))
1272 (setq package-archive-contents
1273 (package--append-to-alist pkg-desc package-archive-contents)))))
1275 (defun package--read-archive-file (file)
1276 "Re-read archive file FILE, if it exists.
1277 Will return the data from the file, or nil if the file does not exist.
1278 Will throw an error if the archive version is too new."
1279 (let ((filename (expand-file-name file package-user-dir)))
1280 (when (file-exists-p filename)
1281 (with-temp-buffer
1282 (insert-file-contents-literally filename)
1283 (let ((contents (read (current-buffer))))
1284 (if (> (car contents) package-archive-version)
1285 (error "Package archive version %d is higher than %d"
1286 (car contents) package-archive-version))
1287 (cdr contents))))))
1289 (defun package-read-archive-contents (archive)
1290 "Re-read archive contents for ARCHIVE.
1291 If successful, set the variable `package-archive-contents'.
1292 If the archive version is too new, signal an error."
1293 ;; Version 1 of 'archive-contents' is identical to our internal
1294 ;; representation.
1295 (let* ((contents-file (format "archives/%s/archive-contents" archive))
1296 (contents (package--read-archive-file contents-file)))
1297 (when contents
1298 (dolist (package contents)
1299 (package--add-to-archive-contents package archive)))))
1301 (defun package-read-all-archive-contents ()
1302 "Re-read `archive-contents', if it exists.
1303 If successful, set `package-archive-contents'."
1304 (setq package-archive-contents nil)
1305 (dolist (archive package-archives)
1306 (package-read-archive-contents (car archive))))
1308 ;;;; Package Initialize
1309 ;; A bit of a milestone. This brings together some of the above
1310 ;; sections and populates all relevant lists of packages from contents
1311 ;; available on disk.
1312 (defvar package--initialized nil)
1314 ;;;###autoload
1315 (defun package-initialize (&optional no-activate)
1316 "Load Emacs Lisp packages, and activate them.
1317 The variable `package-load-list' controls which packages to load.
1318 If optional arg NO-ACTIVATE is non-nil, don't activate packages."
1319 (interactive)
1320 (setq package-alist nil)
1321 (package-load-all-descriptors)
1322 (package-read-all-archive-contents)
1323 (unless no-activate
1324 (dolist (elt package-alist)
1325 (package-activate (car elt))))
1326 (setq package--initialized t)
1327 ;; This uses `package--mapc' so it must be called after
1328 ;; `package--initialized' is t.
1329 (package--build-compatibility-table))
1332 ;;;; Populating `package-archive-contents' from archives
1333 ;; This subsection populates the variables listed above from the
1334 ;; actual archives, instead of from a local cache.
1335 (defvar package--downloads-in-progress nil
1336 "List of in-progress asynchronous downloads.")
1338 (declare-function epg-check-configuration "epg-config"
1339 (config &optional minimum-version))
1340 (declare-function epg-configuration "epg-config" ())
1341 (declare-function epg-import-keys-from-file "epg" (context keys))
1343 ;;;###autoload
1344 (defun package-import-keyring (&optional file)
1345 "Import keys from FILE."
1346 (interactive "fFile: ")
1347 (setq file (expand-file-name file))
1348 (let ((context (epg-make-context 'OpenPGP))
1349 (homedir (expand-file-name "gnupg" package-user-dir)))
1350 (with-file-modes 448
1351 (make-directory homedir t))
1352 (setf (epg-context-home-directory context) homedir)
1353 (message "Importing %s..." (file-name-nondirectory file))
1354 (epg-import-keys-from-file context file)
1355 (message "Importing %s...done" (file-name-nondirectory file))))
1357 (defvar package--post-download-archives-hook nil
1358 "Hook run after the archive contents are downloaded.
1359 Don't run this hook directly. It is meant to be run as part of
1360 `package--update-downloads-in-progress'.")
1361 (put 'package--post-download-archives-hook 'risky-local-variable t)
1363 (defun package--update-downloads-in-progress (entry)
1364 "Remove ENTRY from `package--downloads-in-progress'.
1365 Once it's empty, run `package--post-download-archives-hook'."
1366 ;; Keep track of the downloading progress.
1367 (setq package--downloads-in-progress
1368 (remove entry package--downloads-in-progress))
1369 ;; If this was the last download, run the hook.
1370 (unless package--downloads-in-progress
1371 (package-read-all-archive-contents)
1372 (package--build-compatibility-table)
1373 ;; We message before running the hook, so the hook can give
1374 ;; messages as well.
1375 (message "Package refresh done")
1376 (run-hooks 'package--post-download-archives-hook)))
1378 (defun package--download-one-archive (archive file &optional async)
1379 "Retrieve an archive file FILE from ARCHIVE, and cache it.
1380 ARCHIVE should be a cons cell of the form (NAME . LOCATION),
1381 similar to an entry in `package-alist'. Save the cached copy to
1382 \"archives/NAME/FILE\" in `package-user-dir'."
1383 (package--with-work-buffer-async (cdr archive) file async
1384 (let* ((location (cdr archive))
1385 (name (car archive))
1386 (content (buffer-string))
1387 (dir (expand-file-name (format "archives/%s" name) package-user-dir))
1388 (local-file (expand-file-name file dir)))
1389 (when (listp (read-from-string content))
1390 (make-directory dir t)
1391 (if (or (not package-check-signature)
1392 (member archive package-unsigned-archives))
1393 ;; If we don't care about the signature, save the file and
1394 ;; we're done.
1395 (progn (write-region content nil local-file nil 'silent)
1396 (package--update-downloads-in-progress archive))
1397 ;; If we care, check it (perhaps async) and *then* write the file.
1398 (package--check-signature
1399 location file content async
1400 ;; This function will be called after signature checking.
1401 (lambda (&optional good-sigs)
1402 (unless (or good-sigs (eq package-check-signature 'allow-unsigned))
1403 ;; Even if the sig fails, this download is done, so
1404 ;; remove it from the in-progress list.
1405 (package--update-downloads-in-progress archive)
1406 (error "Unsigned archive `%s'" name))
1407 ;; Write out the archives file.
1408 (write-region content nil local-file nil 'silent)
1409 ;; Write out good signatures into archive-contents.signed file.
1410 (when good-sigs
1411 (write-region (mapconcat #'epg-signature-to-string good-sigs "\n")
1412 nil (concat local-file ".signed") nil 'silent))
1413 (package--update-downloads-in-progress archive))))))))
1415 (defun package--download-and-read-archives (&optional async)
1416 "Download descriptions of all `package-archives' and read them.
1417 This populates `package-archive-contents'. If ASYNC is non-nil,
1418 perform the downloads asynchronously."
1419 ;; The downloaded archive contents will be read as part of
1420 ;; `package--update-downloads-in-progress'.
1421 (setq package--downloads-in-progress
1422 (append package-archives
1423 package--downloads-in-progress))
1424 (dolist (archive package-archives)
1425 (condition-case-unless-debug nil
1426 (package--download-one-archive
1427 archive "archive-contents"
1428 ;; Called if the async download fails
1429 (when async
1430 (lambda () (package--update-downloads-in-progress archive))))
1431 (error (message "Failed to download `%s' archive."
1432 (car archive))))))
1434 ;;;###autoload
1435 (defun package-refresh-contents (&optional async)
1436 "Download descriptions of all configured ELPA packages.
1437 For each archive configured in the variable `package-archives',
1438 inform Emacs about the latest versions of all packages it offers,
1439 and make them available for download.
1440 Optional argument ASYNC specifies whether to perform the
1441 downloads in the background."
1442 (interactive)
1443 ;; FIXME: Do it asynchronously.
1444 (unless (file-exists-p package-user-dir)
1445 (make-directory package-user-dir t))
1446 (let ((default-keyring (expand-file-name "package-keyring.gpg"
1447 data-directory)))
1448 (when (and package-check-signature (file-exists-p default-keyring))
1449 (condition-case-unless-debug error
1450 (progn
1451 (epg-check-configuration (epg-configuration))
1452 (package-import-keyring default-keyring))
1453 (error (message "Cannot import default keyring: %S" (cdr error))))))
1454 (package--download-and-read-archives async))
1457 ;;; Dependency Management
1458 ;; Calculating the full transaction necessary for an installation,
1459 ;; keeping track of which packages were installed strictly as
1460 ;; dependencies, and determining which packages cannot be removed
1461 ;; because they are dependencies.
1462 (defun package-compute-transaction (packages requirements &optional seen)
1463 "Return a list of packages to be installed, including PACKAGES.
1464 PACKAGES should be a list of `package-desc'.
1466 REQUIREMENTS should be a list of additional requirements; each
1467 element in this list should have the form (PACKAGE VERSION-LIST),
1468 where PACKAGE is a package name and VERSION-LIST is the required
1469 version of that package.
1471 This function recursively computes the requirements of the
1472 packages in REQUIREMENTS, and returns a list of all the packages
1473 that must be installed. Packages that are already installed are
1474 not included in this list.
1476 SEEN is used internally to detect infinite recursion."
1477 ;; FIXME: We really should use backtracking to explore the whole
1478 ;; search space (e.g. if foo require bar-1.3, and bar-1.4 requires toto-1.1
1479 ;; whereas bar-1.3 requires toto-1.0 and the user has put a hold on toto-1.0:
1480 ;; the current code might fail to see that it could install foo by using the
1481 ;; older bar-1.3).
1482 (dolist (elt requirements)
1483 (let* ((next-pkg (car elt))
1484 (next-version (cadr elt))
1485 (already ()))
1486 (dolist (pkg packages)
1487 (if (eq next-pkg (package-desc-name pkg))
1488 (setq already pkg)))
1489 (when already
1490 (if (version-list-<= next-version (package-desc-version already))
1491 ;; `next-pkg' is already in `packages', but its position there
1492 ;; means it might be installed too late: remove it from there, so
1493 ;; we re-add it (along with its dependencies) at an earlier place
1494 ;; below (bug#16994).
1495 (if (memq already seen) ;Avoid inf-loop on dependency cycles.
1496 (message "Dependency cycle going through %S"
1497 (package-desc-full-name already))
1498 (setq packages (delq already packages))
1499 (setq already nil))
1500 (error "Need package `%s-%s', but only %s is being installed"
1501 next-pkg (package-version-join next-version)
1502 (package-version-join (package-desc-version already)))))
1503 (cond
1504 (already nil)
1505 ((package-installed-p next-pkg next-version) nil)
1508 ;; A package is required, but not installed. It might also be
1509 ;; blocked via `package-load-list'.
1510 (let ((pkg-descs (cdr (assq next-pkg package-archive-contents)))
1511 (found nil)
1512 (problem nil))
1513 (while (and pkg-descs (not found))
1514 (let* ((pkg-desc (pop pkg-descs))
1515 (version (package-desc-version pkg-desc))
1516 (disabled (package-disabled-p next-pkg version)))
1517 (cond
1518 ((version-list-< version next-version)
1519 (error
1520 "Need package `%s-%s', but only %s is available"
1521 next-pkg (package-version-join next-version)
1522 (package-version-join version)))
1523 (disabled
1524 (unless problem
1525 (setq problem
1526 (if (stringp disabled)
1527 (format "Package `%s' held at version %s, \
1528 but version %s required"
1529 next-pkg disabled
1530 (package-version-join next-version))
1531 (format "Required package '%s' is disabled"
1532 next-pkg)))))
1533 (t (setq found pkg-desc)))))
1534 (unless found
1535 (if problem
1536 (error "%s" problem)
1537 (error "Package `%s-%s' is unavailable"
1538 next-pkg (package-version-join next-version))))
1539 (setq packages
1540 (package-compute-transaction (cons found packages)
1541 (package-desc-reqs found)
1542 (cons found seen))))))))
1543 packages)
1545 (defun package--find-non-dependencies ()
1546 "Return a list of installed packages which are not dependencies.
1547 Finds all packages in `package-alist' which are not dependencies
1548 of any other packages.
1549 Used to populate `package-selected-packages'."
1550 (let ((dep-list
1551 (delete-dups
1552 (apply #'append
1553 (mapcar (lambda (p) (mapcar #'car (package-desc-reqs (cadr p))))
1554 package-alist)))))
1555 (cl-loop for p in package-alist
1556 for name = (car p)
1557 unless (memq name dep-list)
1558 collect name)))
1560 (defun package--user-selected-p (pkg)
1561 "Return non-nil if PKG is a package was installed by the user.
1562 PKG is a package name.
1563 This looks into `package-selected-packages', populating it first
1564 if it is still empty."
1565 (unless (consp package-selected-packages)
1566 (customize-save-variable
1567 'package-selected-packages
1568 (setq package-selected-packages (package--find-non-dependencies))))
1569 (memq pkg package-selected-packages))
1571 (defun package--get-deps (pkg &optional only)
1572 (let* ((pkg-desc (cadr (assq pkg package-alist)))
1573 (direct-deps (cl-loop for p in (package-desc-reqs pkg-desc)
1574 for name = (car p)
1575 when (assq name package-alist)
1576 collect name))
1577 (indirect-deps (unless (eq only 'direct)
1578 (delete-dups
1579 (cl-loop for p in direct-deps
1580 append (package--get-deps p))))))
1581 (cl-case only
1582 (direct direct-deps)
1583 (separate (list direct-deps indirect-deps))
1584 (indirect indirect-deps)
1585 (t (delete-dups (append direct-deps indirect-deps))))))
1587 (defun package--removable-packages ()
1588 "Return a list of names of packages no longer needed.
1589 These are packages which are neither contained in
1590 `package-selected-packages' nor a dependency of one that is."
1591 (let ((needed (cl-loop for p in package-selected-packages
1592 if (assq p package-alist)
1593 ;; `p' and its dependencies are needed.
1594 append (cons p (package--get-deps p)))))
1595 (cl-loop for p in (mapcar #'car package-alist)
1596 unless (memq p needed)
1597 collect p)))
1599 (defun package--used-elsewhere-p (pkg-desc &optional pkg-list)
1600 "Non-nil if PKG-DESC is a dependency of a package in PKG-LIST.
1601 Return the first package found in PKG-LIST of which PKG is a
1602 dependency.
1604 When not specified, PKG-LIST defaults to `package-alist'
1605 with PKG-DESC entry removed."
1606 (unless (string= (package-desc-status pkg-desc) "obsolete")
1607 (let ((pkg (package-desc-name pkg-desc)))
1608 (cl-loop with alist = (or pkg-list
1609 (remove (assq pkg package-alist)
1610 package-alist))
1611 for p in alist thereis
1612 (and (memq pkg (mapcar #'car (package-desc-reqs (cadr p))))
1613 (car p))))))
1615 (defun package--sort-deps-in-alist (package only)
1616 "Return a list of dependencies for PACKAGE sorted by dependency.
1617 PACKAGE is included as the first element of the returned list.
1618 ONLY is an alist associating package names to package objects.
1619 Only these packages will be in the return value an their cdrs are
1620 destructively set to nil in ONLY."
1621 (let ((out))
1622 (dolist (dep (package-desc-reqs package))
1623 (when-let ((cell (assq (car dep) only))
1624 (dep-package (cdr-safe cell)))
1625 (setcdr cell nil)
1626 (setq out (append (package--sort-deps-in-alist dep-package only)
1627 out))))
1628 (cons package out)))
1630 (defun package--sort-by-dependence (package-list)
1631 "Return PACKAGE-LIST sorted by dependence.
1632 That is, any element of the returned list is guaranteed to not
1633 directly depend on any elements that come before it.
1635 PACKAGE-LIST is a list of package-desc objects.
1636 Indirect dependencies are guaranteed to be returned in order only
1637 if all the in-between dependencies are also in PACKAGE-LIST."
1638 (let ((alist (mapcar (lambda (p) (cons (package-desc-name p) p)) package-list))
1639 out-list)
1640 (dolist (cell alist out-list)
1641 ;; `package--sort-deps-in-alist' destructively changes alist, so
1642 ;; some cells might already be empty. We check this here.
1643 (when-let ((pkg-desc (cdr cell)))
1644 (setcdr cell nil)
1645 (setq out-list
1646 (append (package--sort-deps-in-alist pkg-desc alist)
1647 out-list))))))
1650 ;;; Installation Functions
1651 ;; As opposed to the previous section (which listed some underlying
1652 ;; functions necessary for installation), this one contains the actual
1653 ;; functions that install packages. The package itself can be
1654 ;; installed in a variety of ways (archives, buffer, file), but
1655 ;; requirements (dependencies) are always satisfied by looking in
1656 ;; `package-archive-contents'.
1657 (defun package-archive-base (desc)
1658 "Return the archive containing the package NAME."
1659 (cdr (assoc (package-desc-archive desc) package-archives)))
1661 (defun package-install-from-archive (pkg-desc &optional async callback)
1662 "Download and install a tar package.
1663 If ASYNC is non-nil, perform the download asynchronously.
1664 If CALLBACK is non-nil, call it with no arguments once the
1665 operation is done."
1666 ;; This won't happen, unless the archive is doing something wrong.
1667 (when (eq (package-desc-kind pkg-desc) 'dir)
1668 (error "Can't install directory package from archive"))
1669 (let* ((location (package-archive-base pkg-desc))
1670 (file (concat (package-desc-full-name pkg-desc)
1671 (package-desc-suffix pkg-desc))))
1672 (package--with-work-buffer-async location file async
1673 (if (or (not package-check-signature)
1674 (member (package-desc-archive pkg-desc)
1675 package-unsigned-archives))
1676 ;; If we don't care about the signature, unpack and we're
1677 ;; done.
1678 (progn (package-unpack pkg-desc)
1679 (funcall callback))
1680 ;; If we care, check it and *then* write the file.
1681 (let ((content (buffer-string)))
1682 (package--check-signature
1683 location file content async
1684 ;; This function will be called after signature checking.
1685 (lambda (&optional good-sigs)
1686 (unless (or good-sigs (eq package-check-signature 'allow-unsigned))
1687 ;; Even if the sig fails, this download is done, so
1688 ;; remove it from the in-progress list.
1689 (error "Unsigned package: `%s'"
1690 (package-desc-name pkg-desc)))
1691 ;; Signature checked, unpack now.
1692 (with-temp-buffer (insert content)
1693 (package-unpack pkg-desc))
1694 ;; Here the package has been installed successfully, mark it as
1695 ;; signed if appropriate.
1696 (when good-sigs
1697 ;; Write out good signatures into NAME-VERSION.signed file.
1698 (write-region (mapconcat #'epg-signature-to-string good-sigs "\n")
1700 (expand-file-name
1701 (concat (package-desc-full-name pkg-desc) ".signed")
1702 package-user-dir)
1703 nil 'silent)
1704 ;; Update the old pkg-desc which will be shown on the description buffer.
1705 (setf (package-desc-signed pkg-desc) t)
1706 ;; Update the new (activated) pkg-desc as well.
1707 (when-let ((pkg-descs (cdr (assq (package-desc-name pkg-desc) package-alist))))
1708 (setf (package-desc-signed (car pkg-descs)) t)))
1709 (when (functionp callback)
1710 (funcall callback)))))))))
1712 (defun package-installed-p (package &optional min-version)
1713 "Return true if PACKAGE, of MIN-VERSION or newer, is installed.
1714 If PACKAGE is a symbol, it is the package name and MIN-VERSION
1715 should be a version list.
1717 If PACKAGE is a package-desc object, MIN-VERSION is ignored."
1718 (unless package--initialized (error "package.el is not yet initialized!"))
1719 (if (package-desc-p package)
1720 (let ((dir (package-desc-dir package)))
1721 (and (stringp dir)
1722 (file-exists-p dir)))
1724 (let ((pkg-descs (cdr (assq package package-alist))))
1725 (and pkg-descs
1726 (version-list-<= min-version
1727 (package-desc-version (car pkg-descs)))))
1728 ;; Also check built-in packages.
1729 (package-built-in-p package min-version))))
1731 (defun package-download-transaction (packages &optional async callback)
1732 "Download and install all the packages in PACKAGES.
1733 PACKAGES should be a list of package-desc.
1734 If ASYNC is non-nil, perform the downloads asynchronously.
1735 If CALLBACK is non-nil, call it with no arguments once the
1736 entire operation is done.
1738 This function assumes that all package requirements in
1739 PACKAGES are satisfied, i.e. that PACKAGES is computed
1740 using `package-compute-transaction'."
1741 (cond
1742 (packages (package-install-from-archive
1743 (car packages)
1744 async
1745 (lambda ()
1746 (package-download-transaction (cdr packages))
1747 (when (functionp callback)
1748 (funcall callback)))))
1749 (callback (funcall callback))))
1751 (defun package--ensure-init-file ()
1752 "Ensure that the user's init file calls `package-initialize'."
1753 ;; Don't mess with the init-file from "emacs -Q".
1754 (when user-init-file
1755 (let ((buffer (find-buffer-visiting user-init-file)))
1756 (with-current-buffer (or buffer (find-file-noselect user-init-file))
1757 (save-excursion
1758 (save-restriction
1759 (widen)
1760 (goto-char (point-min))
1761 (unless (search-forward "(package-initialize)" nil 'noerror)
1762 (goto-char (point-min))
1763 (insert
1764 ";; Added by Package.el. This must come before configurations of\n"
1765 ";; installed packages. Don't delete this line. If you don't want it,\n"
1766 ";; just comment it out by adding a semicolon to the start of the line.\n"
1767 "(package-initialize)\n")
1768 (unless (looking-at-p "$")
1769 (insert "\n"))
1770 (let ((file-precious-flag t))
1771 (save-buffer)))
1772 (unless buffer
1773 (kill-buffer (current-buffer)))))))))
1775 ;;;###autoload
1776 (defun package-install (pkg &optional dont-select async callback)
1777 "Install the package PKG.
1778 PKG can be a package-desc or the package name of one the available packages
1779 in an archive in `package-archives'. Interactively, prompt for its name.
1781 If called interactively or if DONT-SELECT nil, add PKG to
1782 `package-selected-packages'.
1783 If ASYNC is non-nil, perform the downloads asynchronously.
1784 If CALLBACK is non-nil, call it with no arguments once the
1785 entire operation is done.
1787 If PKG is a package-desc and it is already installed, don't try
1788 to install it but still mark it as selected."
1789 (interactive
1790 (progn
1791 ;; Initialize the package system to get the list of package
1792 ;; symbols for completion.
1793 (unless package--initialized
1794 (package-initialize t))
1795 (unless package-archive-contents
1796 (package-refresh-contents))
1797 (list (intern (completing-read
1798 "Install package: "
1799 (delq nil
1800 (mapcar (lambda (elt)
1801 (unless (package-installed-p (car elt))
1802 (symbol-name (car elt))))
1803 package-archive-contents))
1804 nil t))
1805 nil)))
1806 (package--ensure-init-file)
1807 (let ((name (if (package-desc-p pkg)
1808 (package-desc-name pkg)
1809 pkg)))
1810 (unless (or dont-select (package--user-selected-p name))
1811 (customize-save-variable 'package-selected-packages
1812 (cons name package-selected-packages))))
1813 (if-let ((transaction
1814 (if (package-desc-p pkg)
1815 (unless (package-installed-p pkg)
1816 (package-compute-transaction (list pkg)
1817 (package-desc-reqs pkg)))
1818 (package-compute-transaction () (list (list pkg))))))
1819 (package-download-transaction transaction async callback)
1820 (message "`%s' is already installed" (package-desc-full-name pkg))))
1822 (defun package-strip-rcs-id (str)
1823 "Strip RCS version ID from the version string STR.
1824 If the result looks like a dotted numeric version, return it.
1825 Otherwise return nil."
1826 (when str
1827 (when (string-match "\\`[ \t]*[$]Revision:[ \t]+" str)
1828 (setq str (substring str (match-end 0))))
1829 (condition-case nil
1830 (if (version-to-list str)
1831 str)
1832 (error nil))))
1834 (declare-function lm-homepage "lisp-mnt" (&optional file))
1836 ;;;###autoload
1837 (defun package-install-from-buffer ()
1838 "Install a package from the current buffer.
1839 The current buffer is assumed to be a single .el or .tar file or
1840 a directory. These must follow the packaging guidelines (see
1841 info node `(elisp)Packaging').
1843 Specially, if current buffer is a directory, the -pkg.el
1844 description file is not mandatory, in which case the information
1845 is derived from the main .el file in the directory.
1847 Downloads and installs required packages as needed."
1848 (interactive)
1849 (package--ensure-init-file)
1850 (let* ((pkg-desc
1851 (cond
1852 ((derived-mode-p 'dired-mode)
1853 ;; This is the only way a package-desc object with a `dir'
1854 ;; desc-kind can be created. Such packages can't be
1855 ;; uploaded or installed from archives, they can only be
1856 ;; installed from local buffers or directories.
1857 (package-dir-info))
1858 ((derived-mode-p 'tar-mode)
1859 (package-tar-file-info))
1861 (package-buffer-info))))
1862 (name (package-desc-name pkg-desc)))
1863 ;; Download and install the dependencies.
1864 (let* ((requires (package-desc-reqs pkg-desc))
1865 (transaction (package-compute-transaction nil requires)))
1866 (package-download-transaction transaction))
1867 ;; Install the package itself.
1868 (package-unpack pkg-desc)
1869 (unless (package--user-selected-p name)
1870 (customize-save-variable 'package-selected-packages
1871 (cons name package-selected-packages)))
1872 pkg-desc))
1874 ;;;###autoload
1875 (defun package-install-file (file)
1876 "Install a package from a file.
1877 The file can either be a tar file or an Emacs Lisp file."
1878 (interactive "fPackage file name: ")
1879 (with-temp-buffer
1880 (if (file-directory-p file)
1881 (progn
1882 (setq default-directory file)
1883 (dired-mode))
1884 (insert-file-contents-literally file)
1885 (when (string-match "\\.tar\\'" file) (tar-mode)))
1886 (package-install-from-buffer)))
1888 ;;;###autoload
1889 (defun package-install-user-selected-packages ()
1890 "Ensure packages in `package-selected-packages' are installed.
1891 If some packages are not installed propose to install them."
1892 (interactive)
1893 ;; We don't need to populate `package-selected-packages' before
1894 ;; using here, because the outcome is the same either way (nothing
1895 ;; gets installed).
1896 (if (not package-selected-packages)
1897 (message "`package-selected-packages' is empty, nothing to install")
1898 (cl-loop for p in package-selected-packages
1899 unless (package-installed-p p)
1900 collect p into lst
1901 finally
1902 (if lst
1903 (when (y-or-n-p
1904 (format "%s packages will be installed:\n%s, proceed?"
1905 (length lst)
1906 (mapconcat #'symbol-name lst ", ")))
1907 (mapc #'package-install lst))
1908 (message "All your packages are already installed")))))
1911 ;;; Package Deletion
1912 (defun package--newest-p (pkg)
1913 "Return t if PKG is the newest package with its name."
1914 (equal (cadr (assq (package-desc-name pkg) package-alist))
1915 pkg))
1917 (defun package-delete (pkg-desc &optional force nosave)
1918 "Delete package PKG-DESC.
1920 Argument PKG-DESC is a full description of package as vector.
1921 When package is used elsewhere as dependency of another package,
1922 refuse deleting it and return an error.
1923 If FORCE is non-nil package will be deleted even if it is used
1924 elsewhere.
1925 If NOSAVE is non-nil, the package is not removed from
1926 `package-selected-packages'."
1927 (let ((dir (package-desc-dir pkg-desc))
1928 (name (package-desc-name pkg-desc))
1929 pkg-used-elsewhere-by)
1930 ;; If the user is trying to delete this package, they definitely
1931 ;; don't want it marked as selected, so we remove it from
1932 ;; `package-selected-packages' even if it can't be deleted.
1933 (when (and (null nosave)
1934 (package--user-selected-p name)
1935 ;; Don't deselect if this is an older version of an
1936 ;; upgraded package.
1937 (package--newest-p pkg-desc))
1938 (customize-save-variable
1939 'package-selected-packages (remove name package-selected-packages)))
1940 (cond ((not (string-prefix-p (file-name-as-directory
1941 (expand-file-name package-user-dir))
1942 (expand-file-name dir)))
1943 ;; Don't delete "system" packages.
1944 (error "Package `%s' is a system package, not deleting"
1945 (package-desc-full-name pkg-desc)))
1946 ((and (null force)
1947 (setq pkg-used-elsewhere-by
1948 (package--used-elsewhere-p pkg-desc)))
1949 ;; Don't delete packages used as dependency elsewhere.
1950 (error "Package `%s' is used by `%s' as dependency, not deleting"
1951 (package-desc-full-name pkg-desc)
1952 pkg-used-elsewhere-by))
1954 (delete-directory dir t t)
1955 ;; Remove NAME-VERSION.signed file.
1956 (let ((signed-file (concat dir ".signed")))
1957 (if (file-exists-p signed-file)
1958 (delete-file signed-file)))
1959 ;; Update package-alist.
1960 (let ((pkgs (assq name package-alist)))
1961 (delete pkg-desc pkgs)
1962 (unless (cdr pkgs)
1963 (setq package-alist (delq pkgs package-alist))))
1964 (message "Package `%s' deleted." (package-desc-full-name pkg-desc))))))
1966 ;;;###autoload
1967 (defun package-reinstall (pkg)
1968 "Reinstall package PKG.
1969 PKG should be either a symbol, the package name, or a package-desc
1970 object."
1971 (interactive (list (intern (completing-read
1972 "Reinstall package: "
1973 (mapcar #'symbol-name
1974 (mapcar #'car package-alist))))))
1975 (package-delete
1976 (if (package-desc-p pkg) pkg (cadr (assq pkg package-alist)))
1977 'force 'nosave)
1978 (package-install pkg 'dont-select))
1980 ;;;###autoload
1981 (defun package-autoremove ()
1982 "Remove packages that are no more needed.
1984 Packages that are no more needed by other packages in
1985 `package-selected-packages' and their dependencies
1986 will be deleted."
1987 (interactive)
1988 ;; If `package-selected-packages' is nil, it would make no sense to
1989 ;; try to populate it here, because then `package-autoremove' will
1990 ;; do absolutely nothing.
1991 (when (or package-selected-packages
1992 (yes-or-no-p
1993 "`package-selected-packages' is empty! Really remove ALL packages? "))
1994 (let ((removable (package--removable-packages)))
1995 (if removable
1996 (when (y-or-n-p
1997 (format "%s packages will be deleted:\n%s, proceed? "
1998 (length removable)
1999 (mapconcat #'symbol-name removable ", ")))
2000 (mapc (lambda (p)
2001 (package-delete (cadr (assq p package-alist)) t))
2002 removable))
2003 (message "Nothing to autoremove")))))
2006 ;;;; Package description buffer.
2008 ;;;###autoload
2009 (defun describe-package (package)
2010 "Display the full documentation of PACKAGE (a symbol)."
2011 (interactive
2012 (let* ((guess (function-called-at-point)))
2013 (require 'finder-inf nil t)
2014 ;; Load the package list if necessary (but don't activate them).
2015 (unless package--initialized
2016 (package-initialize t))
2017 (let ((packages (append (mapcar 'car package-alist)
2018 (mapcar 'car package-archive-contents)
2019 (mapcar 'car package--builtins))))
2020 (unless (memq guess packages)
2021 (setq guess nil))
2022 (setq packages (mapcar 'symbol-name packages))
2023 (let ((val
2024 (completing-read (if guess
2025 (format "Describe package (default %s): "
2026 guess)
2027 "Describe package: ")
2028 packages nil t nil nil guess)))
2029 (list (intern val))))))
2030 (if (not (or (package-desc-p package) (and package (symbolp package))))
2031 (message "No package specified")
2032 (help-setup-xref (list #'describe-package package)
2033 (called-interactively-p 'interactive))
2034 (with-help-window (help-buffer)
2035 (with-current-buffer standard-output
2036 (describe-package-1 package)))))
2038 (declare-function lm-commentary "lisp-mnt" (&optional file))
2040 (defun describe-package-1 (pkg)
2041 (require 'lisp-mnt)
2042 (let* ((desc (or
2043 (if (package-desc-p pkg) pkg)
2044 (cadr (assq pkg package-alist))
2045 (let ((built-in (assq pkg package--builtins)))
2046 (if built-in
2047 (package--from-builtin built-in)
2048 (cadr (assq pkg package-archive-contents))))))
2049 (name (if desc (package-desc-name desc) pkg))
2050 (pkg-dir (if desc (package-desc-dir desc)))
2051 (reqs (if desc (package-desc-reqs desc)))
2052 (version (if desc (package-desc-version desc)))
2053 (archive (if desc (package-desc-archive desc)))
2054 (extras (and desc (package-desc-extras desc)))
2055 (homepage (cdr (assoc :url extras)))
2056 (keywords (if desc (package-desc--keywords desc)))
2057 (built-in (eq pkg-dir 'builtin))
2058 (installable (and archive (not built-in)))
2059 (status (if desc (package-desc-status desc) "orphan"))
2060 (incompatible-reason (package--incompatible-p desc))
2061 (signed (if desc (package-desc-signed desc))))
2062 (when incompatible-reason
2063 (setq status "incompatible"))
2064 (prin1 name)
2065 (princ " is ")
2066 (princ (if (memq (aref status 0) '(?a ?e ?i ?o ?u)) "an " "a "))
2067 (princ status)
2068 (princ " package.\n\n")
2070 (insert " " (propertize "Status" 'font-lock-face 'bold) ": ")
2071 (cond (built-in
2072 (insert (propertize (capitalize status)
2073 'font-lock-face 'font-lock-builtin-face)
2074 "."))
2075 (pkg-dir
2076 (insert (propertize (if (member status '("unsigned" "dependency"))
2077 "Installed"
2078 (capitalize status)) ;FIXME: Why comment-face?
2079 'font-lock-face 'font-lock-comment-face))
2080 (insert " in `")
2081 ;; Todo: Add button for uninstalling.
2082 (help-insert-xref-button (abbreviate-file-name
2083 (file-name-as-directory pkg-dir))
2084 'help-package-def pkg-dir)
2085 (if (and (package-built-in-p name)
2086 (not (package-built-in-p name version)))
2087 (insert "',\n shadowing a "
2088 (propertize "built-in package"
2089 'font-lock-face 'font-lock-builtin-face))
2090 (insert "'"))
2091 (if signed
2092 (insert ".")
2093 (insert " (unsigned).")))
2094 (incompatible-reason
2095 (insert (propertize "Incompatible" 'face font-lock-warning-face)
2096 " because it depends on ")
2097 (if (stringp incompatible-reason)
2098 (insert "Emacs " incompatible-reason ".")
2099 (insert "uninstallable packages.")))
2100 (installable
2101 (insert (capitalize status))
2102 (insert " from " (format "%s" archive))
2103 (insert " -- ")
2104 (package-make-button
2105 "Install"
2106 'action 'package-install-button-action
2107 'package-desc desc))
2108 (t (insert (capitalize status) ".")))
2109 (insert "\n")
2110 (insert " " (propertize "Archive" 'font-lock-face 'bold)
2111 ": " (or archive "n/a") "\n")
2112 (and version
2113 (insert " "
2114 (propertize "Version" 'font-lock-face 'bold) ": "
2115 (package-version-join version) "\n"))
2117 (setq reqs (if desc (package-desc-reqs desc)))
2118 (when reqs
2119 (insert " " (propertize "Requires" 'font-lock-face 'bold) ": ")
2120 (let ((first t))
2121 (dolist (req reqs)
2122 (let* ((name (car req))
2123 (vers (cadr req))
2124 (text (format "%s-%s" (symbol-name name)
2125 (package-version-join vers)))
2126 (reason (if (and (listp incompatible-reason)
2127 (assq name incompatible-reason))
2128 " (not available)" "")))
2129 (cond (first (setq first nil))
2130 ((>= (+ 2 (current-column) (length text) (length reason))
2131 (window-width))
2132 (insert ",\n "))
2133 (t (insert ", ")))
2134 (help-insert-xref-button text 'help-package name)
2135 (insert reason)))
2136 (insert "\n")))
2137 (insert " " (propertize "Summary" 'font-lock-face 'bold)
2138 ": " (if desc (package-desc-summary desc)) "\n")
2139 (when homepage
2140 (insert " " (propertize "Homepage" 'font-lock-face 'bold) ": ")
2141 (help-insert-xref-button homepage 'help-url homepage)
2142 (insert "\n"))
2143 (when keywords
2144 (insert " " (propertize "Keywords" 'font-lock-face 'bold) ": ")
2145 (dolist (k keywords)
2146 (package-make-button
2148 'package-keyword k
2149 'action 'package-keyword-button-action)
2150 (insert " "))
2151 (insert "\n"))
2152 (let* ((all-pkgs (append (cdr (assq name package-alist))
2153 (cdr (assq name package-archive-contents))
2154 (let ((bi (assq name package--builtins)))
2155 (if bi (list (package--from-builtin bi))))))
2156 (other-pkgs (delete desc all-pkgs)))
2157 (when other-pkgs
2158 (insert " " (propertize "Other versions" 'font-lock-face 'bold) ": "
2159 (mapconcat
2160 (lambda (opkg)
2161 (let* ((ov (package-desc-version opkg))
2162 (dir (package-desc-dir opkg))
2163 (from (or (package-desc-archive opkg)
2164 (if (stringp dir) "installed" dir))))
2165 (if (not ov) (format "%s" from)
2166 (format "%s (%s)"
2167 (make-text-button (package-version-join ov) nil
2168 'face 'link
2169 'follow-link t
2170 'action
2171 (lambda (_button)
2172 (describe-package opkg)))
2173 from))))
2174 other-pkgs ", ")
2175 ".\n")))
2177 (insert "\n")
2179 (if built-in
2180 ;; For built-in packages, insert the commentary.
2181 (let ((fn (locate-file (format "%s.el" name) load-path
2182 load-file-rep-suffixes))
2183 (opoint (point)))
2184 (insert (or (lm-commentary fn) ""))
2185 (save-excursion
2186 (goto-char opoint)
2187 (when (re-search-forward "^;;; Commentary:\n" nil t)
2188 (replace-match ""))
2189 (while (re-search-forward "^\\(;+ ?\\)" nil t)
2190 (replace-match ""))))
2191 (let ((readme (expand-file-name (format "%s-readme.txt" name)
2192 package-user-dir))
2193 readme-string)
2194 ;; For elpa packages, try downloading the commentary. If that
2195 ;; fails, try an existing readme file in `package-user-dir'.
2196 (cond ((condition-case nil
2197 (save-excursion
2198 (package--with-work-buffer
2199 (package-archive-base desc)
2200 (format "%s-readme.txt" name)
2201 (save-excursion
2202 (goto-char (point-max))
2203 (unless (bolp)
2204 (insert ?\n)))
2205 (write-region nil nil
2206 (expand-file-name readme package-user-dir)
2207 nil 'silent)
2208 (setq readme-string (buffer-string))
2210 (error nil))
2211 (insert readme-string))
2212 ((file-readable-p readme)
2213 (insert-file-contents readme)
2214 (goto-char (point-max))))))))
2216 (defun package-install-button-action (button)
2217 (let ((pkg-desc (button-get button 'package-desc)))
2218 (when (y-or-n-p (format "Install package `%s'? "
2219 (package-desc-full-name pkg-desc)))
2220 (package-install pkg-desc nil)
2221 (revert-buffer nil t)
2222 (goto-char (point-min)))))
2224 (defun package-keyword-button-action (button)
2225 (let ((pkg-keyword (button-get button 'package-keyword)))
2226 (package-show-package-list t (list pkg-keyword))))
2228 (defun package-make-button (text &rest props)
2229 (let ((button-text (if (display-graphic-p) text (concat "[" text "]")))
2230 (button-face (if (display-graphic-p)
2231 '(:box (:line-width 2 :color "dark grey")
2232 :background "light grey"
2233 :foreground "black")
2234 'link)))
2235 (apply 'insert-text-button button-text 'face button-face 'follow-link t
2236 props)))
2239 ;;;; Package menu mode.
2241 (defvar package-menu-mode-map
2242 (let ((map (make-sparse-keymap))
2243 (menu-map (make-sparse-keymap "Package")))
2244 (set-keymap-parent map tabulated-list-mode-map)
2245 (define-key map "\C-m" 'package-menu-describe-package)
2246 (define-key map "u" 'package-menu-mark-unmark)
2247 (define-key map "\177" 'package-menu-backup-unmark)
2248 (define-key map "d" 'package-menu-mark-delete)
2249 (define-key map "i" 'package-menu-mark-install)
2250 (define-key map "U" 'package-menu-mark-upgrades)
2251 (define-key map "r" 'package-menu-refresh)
2252 (define-key map "f" 'package-menu-filter)
2253 (define-key map "~" 'package-menu-mark-obsolete-for-deletion)
2254 (define-key map "x" 'package-menu-execute)
2255 (define-key map "h" 'package-menu-quick-help)
2256 (define-key map "?" 'package-menu-describe-package)
2257 (define-key map [menu-bar package-menu] (cons "Package" menu-map))
2258 (define-key menu-map [mq]
2259 '(menu-item "Quit" quit-window
2260 :help "Quit package selection"))
2261 (define-key menu-map [s1] '("--"))
2262 (define-key menu-map [mn]
2263 '(menu-item "Next" next-line
2264 :help "Next Line"))
2265 (define-key menu-map [mp]
2266 '(menu-item "Previous" previous-line
2267 :help "Previous Line"))
2268 (define-key menu-map [s2] '("--"))
2269 (define-key menu-map [mu]
2270 '(menu-item "Unmark" package-menu-mark-unmark
2271 :help "Clear any marks on a package and move to the next line"))
2272 (define-key menu-map [munm]
2273 '(menu-item "Unmark Backwards" package-menu-backup-unmark
2274 :help "Back up one line and clear any marks on that package"))
2275 (define-key menu-map [md]
2276 '(menu-item "Mark for Deletion" package-menu-mark-delete
2277 :help "Mark a package for deletion and move to the next line"))
2278 (define-key menu-map [mi]
2279 '(menu-item "Mark for Install" package-menu-mark-install
2280 :help "Mark a package for installation and move to the next line"))
2281 (define-key menu-map [mupgrades]
2282 '(menu-item "Mark Upgradable Packages" package-menu-mark-upgrades
2283 :help "Mark packages that have a newer version for upgrading"))
2284 (define-key menu-map [s3] '("--"))
2285 (define-key menu-map [mf]
2286 '(menu-item "Filter Package List..." package-menu-filter
2287 :help "Filter package selection (q to go back)"))
2288 (define-key menu-map [mg]
2289 '(menu-item "Update Package List" revert-buffer
2290 :help "Update the list of packages"))
2291 (define-key menu-map [mr]
2292 '(menu-item "Refresh Package List" package-menu-refresh
2293 :help "Download the ELPA archive"))
2294 (define-key menu-map [s4] '("--"))
2295 (define-key menu-map [mt]
2296 '(menu-item "Mark Obsolete Packages" package-menu-mark-obsolete-for-deletion
2297 :help "Mark all obsolete packages for deletion"))
2298 (define-key menu-map [mx]
2299 '(menu-item "Execute Actions" package-menu-execute
2300 :help "Perform all the marked actions"))
2301 (define-key menu-map [s5] '("--"))
2302 (define-key menu-map [mh]
2303 '(menu-item "Help" package-menu-quick-help
2304 :help "Show short key binding help for package-menu-mode"))
2305 (define-key menu-map [mc]
2306 '(menu-item "Describe Package" package-menu-describe-package
2307 :help "Display information about this package"))
2308 map)
2309 "Local keymap for `package-menu-mode' buffers.")
2311 (defvar-local package-menu--new-package-list nil
2312 "List of newly-available packages since `list-packages' was last called.")
2314 (define-derived-mode package-menu-mode tabulated-list-mode "Package Menu"
2315 "Major mode for browsing a list of packages.
2316 Letters do not insert themselves; instead, they are commands.
2317 \\<package-menu-mode-map>
2318 \\{package-menu-mode-map}"
2319 (setq tabulated-list-format
2320 `[("Package" 18 package-menu--name-predicate)
2321 ("Version" 13 nil)
2322 ("Status" 10 package-menu--status-predicate)
2323 ,@(if (cdr package-archives)
2324 '(("Archive" 10 package-menu--archive-predicate)))
2325 ("Description" 0 nil)])
2326 (setq tabulated-list-padding 2)
2327 (setq tabulated-list-sort-key (cons "Status" nil))
2328 (add-hook 'tabulated-list-revert-hook 'package-menu--refresh nil t)
2329 (tabulated-list-init-header))
2331 (defmacro package--push (pkg-desc status listname)
2332 "Convenience macro for `package-menu--generate'.
2333 If the alist stored in the symbol LISTNAME lacks an entry for a
2334 package PKG-DESC, add one. The alist is keyed with PKG-DESC."
2335 `(unless (assoc ,pkg-desc ,listname)
2336 ;; FIXME: Should we move status into pkg-desc?
2337 (push (cons ,pkg-desc ,status) ,listname)))
2339 (defvar package-list-unversioned nil
2340 "If non-nil include packages that don't have a version in `list-package'.")
2342 (defvar package-list-unsigned nil
2343 "If non-nil, mention in the list which packages were installed w/o signature.")
2345 (defvar package--emacs-version-list (version-to-list emacs-version)
2346 "`emacs-version', as a list.")
2348 (defun package--incompatible-p (pkg &optional shallow)
2349 "Return non-nil if PKG has no chance of being installable.
2350 PKG is a package-desc object.
2352 If SHALLOW is non-nil, this only checks if PKG depends on a
2353 higher `emacs-version' than the one being used. Otherwise, also
2354 checks the viability of dependencies, according to
2355 `package--compatibility-table'.
2357 If PKG requires an incompatible Emacs version, the return value
2358 is this version (as a string).
2359 If PKG requires incompatible packages, the return value is a list
2360 of these dependencies, similar to the list returned by
2361 `package-desc-reqs'."
2362 (let* ((reqs (package-desc-reqs pkg))
2363 (version (cadr (assq 'emacs reqs))))
2364 (if (and version (version-list-< package--emacs-version-list version))
2365 (package-version-join version)
2366 (unless shallow
2367 (let (out)
2368 (dolist (dep (package-desc-reqs pkg) out)
2369 (let ((dep-name (car dep)))
2370 (unless (eq 'emacs dep-name)
2371 (let ((cv (gethash dep-name package--compatibility-table)))
2372 (when (version-list-< (or cv '(0)) (or (cadr dep) '(0)))
2373 (push dep out)))))))))))
2375 (defun package-desc-status (pkg-desc)
2376 (let* ((name (package-desc-name pkg-desc))
2377 (dir (package-desc-dir pkg-desc))
2378 (lle (assq name package-load-list))
2379 (held (cadr lle))
2380 (version (package-desc-version pkg-desc))
2381 (signed (or (not package-list-unsigned)
2382 (package-desc-signed pkg-desc))))
2383 (cond
2384 ((eq dir 'builtin) "built-in")
2385 ((and lle (null held)) "disabled")
2386 ((stringp held)
2387 (let ((hv (if (stringp held) (version-to-list held))))
2388 (cond
2389 ((version-list-= version hv) "held")
2390 ((version-list-< version hv) "obsolete")
2391 (t "disabled"))))
2392 ((package-built-in-p name version) "obsolete")
2393 ((package--incompatible-p pkg-desc) "incompat")
2394 (dir ;One of the installed packages.
2395 (cond
2396 ((not (file-exists-p (package-desc-dir pkg-desc))) "deleted")
2397 ((eq pkg-desc (cadr (assq name package-alist)))
2398 (if (not signed) "unsigned"
2399 (if (package--user-selected-p name)
2400 "installed" "dependency")))
2401 (t "obsolete")))
2403 (let* ((ins (cadr (assq name package-alist)))
2404 (ins-v (if ins (package-desc-version ins))))
2405 (cond
2406 ((or (null ins) (version-list-< ins-v version))
2407 (if (memq name package-menu--new-package-list)
2408 "new" "available"))
2409 ((version-list-< version ins-v) "obsolete")
2410 ((version-list-= version ins-v)
2411 (if (not signed) "unsigned"
2412 (if (package--user-selected-p name)
2413 "installed" "dependency")))))))))
2415 (defun package-menu--refresh (&optional packages keywords)
2416 "Re-populate the `tabulated-list-entries'.
2417 PACKAGES should be nil or t, which means to display all known packages.
2418 KEYWORDS should be nil or a list of keywords."
2419 ;; Construct list of (PKG-DESC . STATUS).
2420 (unless packages (setq packages t))
2421 (let (info-list name)
2422 ;; Installed packages:
2423 (dolist (elt package-alist)
2424 (setq name (car elt))
2425 (when (or (eq packages t) (memq name packages))
2426 (dolist (pkg (cdr elt))
2427 (when (package--has-keyword-p pkg keywords)
2428 (package--push pkg (package-desc-status pkg) info-list)))))
2430 ;; Built-in packages:
2431 (dolist (elt package--builtins)
2432 (setq name (car elt))
2433 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
2434 (package--has-keyword-p (package--from-builtin elt) keywords)
2435 (or package-list-unversioned
2436 (package--bi-desc-version (cdr elt)))
2437 (or (eq packages t) (memq name packages)))
2438 (package--push (package--from-builtin elt) "built-in" info-list)))
2440 ;; Available and disabled packages:
2441 (dolist (elt package-archive-contents)
2442 (setq name (car elt))
2443 (when (or (eq packages t) (memq name packages))
2444 (dolist (pkg (cdr elt))
2445 ;; Hide obsolete packages.
2446 (when (and (not (package-installed-p (package-desc-name pkg)
2447 (package-desc-version pkg)))
2448 (package--has-keyword-p pkg keywords))
2449 (package--push pkg (package-desc-status pkg) info-list)))))
2451 ;; Print the result.
2452 (setq tabulated-list-entries
2453 (mapcar #'package-menu--print-info info-list))))
2455 (defun package-all-keywords ()
2456 "Collect all package keywords"
2457 (let (keywords)
2458 (package--mapc (lambda (desc)
2459 (let* ((desc-keywords (and desc (package-desc--keywords desc))))
2460 (setq keywords (append keywords desc-keywords)))))
2461 keywords))
2463 (defun package--mapc (function &optional packages)
2464 "Call FUNCTION for all known PACKAGES.
2465 PACKAGES can be nil or t, which means to display all known
2466 packages, or a list of packages.
2468 Built-in packages are converted with `package--from-builtin'."
2469 (unless packages (setq packages t))
2470 (let (name)
2471 ;; Installed packages:
2472 (dolist (elt package-alist)
2473 (setq name (car elt))
2474 (when (or (eq packages t) (memq name packages))
2475 (mapc function (cdr elt))))
2477 ;; Built-in packages:
2478 (dolist (elt package--builtins)
2479 (setq name (car elt))
2480 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
2481 (or package-list-unversioned
2482 (package--bi-desc-version (cdr elt)))
2483 (or (eq packages t) (memq name packages)))
2484 (funcall function (package--from-builtin elt))))
2486 ;; Available and disabled packages:
2487 (dolist (elt package-archive-contents)
2488 (setq name (car elt))
2489 (when (or (eq packages t) (memq name packages))
2490 (dolist (pkg (cdr elt))
2491 ;; Hide obsolete packages.
2492 (unless (package-installed-p (package-desc-name pkg)
2493 (package-desc-version pkg))
2494 (funcall function pkg)))))))
2496 (defun package--has-keyword-p (desc &optional keywords)
2497 "Test if package DESC has any of the given KEYWORDS.
2498 When none are given, the package matches."
2499 (if keywords
2500 (let* ((desc-keywords (and desc (package-desc--keywords desc)))
2501 found)
2502 (dolist (k keywords)
2503 (when (and (not found)
2504 (member k desc-keywords))
2505 (setq found t)))
2506 found)
2509 (defun package-menu--generate (remember-pos packages &optional keywords)
2510 "Populate the Package Menu.
2511 If REMEMBER-POS is non-nil, keep point on the same entry.
2512 PACKAGES should be t, which means to display all known packages,
2513 or a list of package names (symbols) to display.
2515 With KEYWORDS given, only packages with those keywords are
2516 shown."
2517 (package-menu--refresh packages keywords)
2518 (setf (car (aref tabulated-list-format 0))
2519 (if keywords
2520 (let ((filters (mapconcat 'identity keywords ",")))
2521 (concat "Package[" filters "]"))
2522 "Package"))
2523 (if keywords
2524 (define-key package-menu-mode-map "q" 'package-show-package-list)
2525 (define-key package-menu-mode-map "q" 'quit-window))
2526 (tabulated-list-init-header)
2527 (tabulated-list-print remember-pos))
2529 (defun package-menu--print-info (pkg)
2530 "Return a package entry suitable for `tabulated-list-entries'.
2531 PKG has the form (PKG-DESC . STATUS).
2532 Return (PKG-DESC [NAME VERSION STATUS DOC])."
2533 (let* ((pkg-desc (car pkg))
2534 (status (cdr pkg))
2535 (face (pcase status
2536 (`"built-in" 'font-lock-builtin-face)
2537 (`"available" 'default)
2538 (`"new" 'bold)
2539 (`"held" 'font-lock-constant-face)
2540 (`"disabled" 'font-lock-warning-face)
2541 (`"installed" 'font-lock-comment-face)
2542 (`"dependency" 'font-lock-comment-face)
2543 (`"unsigned" 'font-lock-warning-face)
2544 (`"incompat" 'font-lock-comment-face)
2545 (_ 'font-lock-warning-face)))) ; obsolete.
2546 (list pkg-desc
2547 `[,(list (symbol-name (package-desc-name pkg-desc))
2548 'face 'link
2549 'follow-link t
2550 'package-desc pkg-desc
2551 'action 'package-menu-describe-package)
2552 ,(propertize (package-version-join
2553 (package-desc-version pkg-desc))
2554 'font-lock-face face)
2555 ,(propertize status 'font-lock-face face)
2556 ,@(if (cdr package-archives)
2557 (list (propertize (or (package-desc-archive pkg-desc) "")
2558 'font-lock-face face)))
2559 ,(propertize (package-desc-summary pkg-desc)
2560 'font-lock-face face)])))
2562 (defun package-menu-refresh ()
2563 "Download the Emacs Lisp package archive.
2564 This fetches the contents of each archive specified in
2565 `package-archives', and then refreshes the package menu."
2566 (interactive)
2567 (unless (derived-mode-p 'package-menu-mode)
2568 (user-error "The current buffer is not a Package Menu"))
2569 (package-refresh-contents)
2570 (package-menu--generate t t))
2572 (defun package-menu-describe-package (&optional button)
2573 "Describe the current package.
2574 If optional arg BUTTON is non-nil, describe its associated package."
2575 (interactive)
2576 (let ((pkg-desc (if button (button-get button 'package-desc)
2577 (tabulated-list-get-id))))
2578 (if pkg-desc
2579 (describe-package pkg-desc)
2580 (user-error "No package here"))))
2582 ;; fixme numeric argument
2583 (defun package-menu-mark-delete (&optional _num)
2584 "Mark a package for deletion and move to the next line."
2585 (interactive "p")
2586 (if (member (package-menu-get-status)
2587 '("installed" "dependency" "obsolete" "unsigned"))
2588 (tabulated-list-put-tag "D" t)
2589 (forward-line)))
2591 (defun package-menu-mark-install (&optional _num)
2592 "Mark a package for installation and move to the next line."
2593 (interactive "p")
2594 (if (member (package-menu-get-status) '("available" "new" "dependency"))
2595 (tabulated-list-put-tag "I" t)
2596 (forward-line)))
2598 (defun package-menu-mark-unmark (&optional _num)
2599 "Clear any marks on a package and move to the next line."
2600 (interactive "p")
2601 (tabulated-list-put-tag " " t))
2603 (defun package-menu-backup-unmark ()
2604 "Back up one line and clear any marks on that package."
2605 (interactive)
2606 (forward-line -1)
2607 (tabulated-list-put-tag " "))
2609 (defun package-menu-mark-obsolete-for-deletion ()
2610 "Mark all obsolete packages for deletion."
2611 (interactive)
2612 (save-excursion
2613 (goto-char (point-min))
2614 (while (not (eobp))
2615 (if (equal (package-menu-get-status) "obsolete")
2616 (tabulated-list-put-tag "D" t)
2617 (forward-line 1)))))
2619 (defun package-menu-quick-help ()
2620 "Show short key binding help for package-menu-mode."
2621 (interactive)
2622 (message "n-ext, i-nstall, d-elete, u-nmark, x-ecute, r-efresh, h-elp"))
2624 (define-obsolete-function-alias
2625 'package-menu-view-commentary 'package-menu-describe-package "24.1")
2627 (defun package-menu-get-status ()
2628 (let* ((id (tabulated-list-get-id))
2629 (entry (and id (assq id tabulated-list-entries))))
2630 (if entry
2631 (aref (cadr entry) 2)
2632 "")))
2634 (defun package-archive-priority (archive)
2635 "Return the priority of ARCHIVE.
2637 The archive priorities are specified in
2638 `package-archive-priorities'. If not given there, the priority
2639 defaults to 0."
2640 (or (cdr (assoc archive package-archive-priorities))
2643 (defun package-desc-priority-version (pkg-desc)
2644 "Return the version PKG-DESC with the archive priority prepended.
2646 This allows for easy comparison of package versions from
2647 different archives if archive priorities are meant to be taken in
2648 consideration."
2649 (cons (package-archive-priority
2650 (package-desc-archive pkg-desc))
2651 (package-desc-version pkg-desc)))
2653 (defun package-menu--find-upgrades ()
2654 (let (installed available upgrades)
2655 ;; Build list of installed/available packages in this buffer.
2656 (dolist (entry tabulated-list-entries)
2657 ;; ENTRY is (PKG-DESC [NAME VERSION STATUS DOC])
2658 (let ((pkg-desc (car entry))
2659 (status (aref (cadr entry) 2)))
2660 (cond ((member status '("installed" "dependency" "unsigned"))
2661 (push pkg-desc installed))
2662 ((member status '("available" "new"))
2663 (setq available (package--append-to-alist pkg-desc available))))))
2664 ;; Loop through list of installed packages, finding upgrades.
2665 (dolist (pkg-desc installed)
2666 (let* ((name (package-desc-name pkg-desc))
2667 (avail-pkg (cadr (assq name available))))
2668 (and avail-pkg
2669 (version-list-< (package-desc-priority-version pkg-desc)
2670 (package-desc-priority-version avail-pkg))
2671 (push (cons name avail-pkg) upgrades))))
2672 upgrades))
2674 (defun package-menu-mark-upgrades ()
2675 "Mark all upgradable packages in the Package Menu.
2676 For each installed package with a newer version available, place
2677 an (I)nstall flag on the available version and a (D)elete flag on
2678 the installed version. A subsequent \\[package-menu-execute]
2679 call will upgrade the package."
2680 (interactive)
2681 (unless (derived-mode-p 'package-menu-mode)
2682 (error "The current buffer is not a Package Menu"))
2683 (let ((upgrades (package-menu--find-upgrades)))
2684 (if (null upgrades)
2685 (message "No packages to upgrade.")
2686 (widen)
2687 (save-excursion
2688 (goto-char (point-min))
2689 (while (not (eobp))
2690 (let* ((pkg-desc (tabulated-list-get-id))
2691 (upgrade (cdr (assq (package-desc-name pkg-desc) upgrades))))
2692 (cond ((null upgrade)
2693 (forward-line 1))
2694 ((equal pkg-desc upgrade)
2695 (package-menu-mark-install))
2697 (package-menu-mark-delete))))))
2698 (message "%d package%s marked for upgrading."
2699 (length upgrades)
2700 (if (= (length upgrades) 1) "" "s")))))
2702 (defun package-menu--prompt-transaction-p (ins del)
2703 "Prompt the user about installing INS and deleting DEL.
2704 INS and DEL are lists of `package-desc'. Either may be nil, but
2705 not both."
2706 (y-or-n-p
2707 (concat
2708 (when ins
2709 (let ((lins (length ins)))
2710 (if (= lins 1)
2711 (format "INSTALL package `%s'"
2712 (package-desc-full-name (car ins)))
2713 (format "INSTALL these %d packages (%s)"
2714 lins
2715 (mapconcat #'package-desc-full-name ins ", ")))))
2716 (when (and del ins) " and ")
2717 (when del
2718 (let ((ldel (length del)))
2719 (if (= ldel 1)
2720 (format "DELETE package `%s'"
2721 (package-desc-full-name (car del)))
2722 (format "DELETE these %d packages (%s)"
2723 ldel
2724 (mapconcat #'package-desc-full-name del ", ")))))
2725 "? ")))
2727 (defun package-menu--perform-transaction (install-list delete-list &optional async)
2728 "Install packages in INSTALL-LIST and delete DELETE-LIST.
2729 If ASYNC is non-nil, perform the installation downloads
2730 asynchronously."
2731 ;; While there are packages to install, call `package-install' on
2732 ;; the next one and defer deletion to the callback function.
2733 (if install-list
2734 (let* ((pkg (car install-list))
2735 (rest (cdr install-list))
2736 ;; Don't mark as selected if it's a new version of an
2737 ;; installed package.
2738 (dont-mark (and (not (package-installed-p pkg))
2739 (package-installed-p
2740 (package-desc-name pkg)))))
2741 (package-install
2742 pkg dont-mark async
2743 (lambda () (package-menu--perform-transaction rest delete-list async))))
2744 ;; Once there are no more packages to install, proceed to
2745 ;; deletion.
2746 (dolist (elt (package--sort-by-dependence delete-list))
2747 (condition-case-unless-debug err
2748 (package-delete elt)
2749 (error (message (cadr err)))))
2750 (when package-selected-packages
2751 (when-let ((removable (package--removable-packages)))
2752 (message "These %d packages are no longer needed, type `M-x package-autoremove' to remove them (%s)"
2753 (length removable)
2754 (mapconcat #'symbol-name removable ", "))))
2755 (package-menu--post-refresh)))
2757 (defun package-menu-execute (&optional noquery)
2758 "Perform marked Package Menu actions.
2759 Packages marked for installation are downloaded and installed;
2760 packages marked for deletion are removed.
2761 Optional argument NOQUERY non-nil means do not ask the user to confirm."
2762 (interactive)
2763 (unless (derived-mode-p 'package-menu-mode)
2764 (error "The current buffer is not in Package Menu mode"))
2765 (let (install-list delete-list cmd pkg-desc)
2766 (save-excursion
2767 (goto-char (point-min))
2768 (while (not (eobp))
2769 (setq cmd (char-after))
2770 (unless (eq cmd ?\s)
2771 ;; This is the key PKG-DESC.
2772 (setq pkg-desc (tabulated-list-get-id))
2773 (cond ((eq cmd ?D)
2774 (push pkg-desc delete-list))
2775 ((eq cmd ?I)
2776 (push pkg-desc install-list))))
2777 (forward-line)))
2778 (unless (or delete-list install-list)
2779 (user-error "No operations specified"))
2780 (when (or noquery
2781 (package-menu--prompt-transaction-p install-list delete-list))
2782 ;; This calls `package-menu--generate' after everything's done.
2783 (package-menu--perform-transaction
2784 install-list delete-list package-menu-async))))
2786 (defun package-menu--version-predicate (A B)
2787 (let ((vA (or (aref (cadr A) 1) '(0)))
2788 (vB (or (aref (cadr B) 1) '(0))))
2789 (if (version-list-= vA vB)
2790 (package-menu--name-predicate A B)
2791 (version-list-< vA vB))))
2793 (defun package-menu--status-predicate (A B)
2794 (let ((sA (aref (cadr A) 2))
2795 (sB (aref (cadr B) 2)))
2796 (cond ((string= sA sB)
2797 (package-menu--name-predicate A B))
2798 ((string= sA "new") t)
2799 ((string= sB "new") nil)
2800 ((string= sA "available") t)
2801 ((string= sB "available") nil)
2802 ((string= sA "installed") t)
2803 ((string= sB "installed") nil)
2804 ((string= sA "dependency") t)
2805 ((string= sB "dependency") nil)
2806 ((string= sA "unsigned") t)
2807 ((string= sB "unsigned") nil)
2808 ((string= sA "held") t)
2809 ((string= sB "held") nil)
2810 ((string= sA "built-in") t)
2811 ((string= sB "built-in") nil)
2812 ((string= sA "obsolete") t)
2813 ((string= sB "obsolete") nil)
2814 ((string= sA "incompat") t)
2815 ((string= sB "incompat") nil)
2816 (t (string< sA sB)))))
2818 (defun package-menu--description-predicate (A B)
2819 (let ((dA (aref (cadr A) 3))
2820 (dB (aref (cadr B) 3)))
2821 (if (string= dA dB)
2822 (package-menu--name-predicate A B)
2823 (string< dA dB))))
2825 (defun package-menu--name-predicate (A B)
2826 (string< (symbol-name (package-desc-name (car A)))
2827 (symbol-name (package-desc-name (car B)))))
2829 (defun package-menu--archive-predicate (A B)
2830 (string< (or (package-desc-archive (car A)) "")
2831 (or (package-desc-archive (car B)) "")))
2833 (defvar-local package-menu--old-archive-contents nil
2834 "`package-archive-contents' before the latest refresh.")
2836 (defun package-menu--populate-new-package-list ()
2837 "Decide which packages are new in `package-archives-contents'.
2838 Store this list in `package-menu--new-package-list'."
2839 ;; Find which packages are new.
2840 (when package-menu--old-archive-contents
2841 (dolist (elt package-archive-contents)
2842 (unless (assq (car elt) package-menu--old-archive-contents)
2843 (push (car elt) package-menu--new-package-list)))
2844 (setq package-menu--old-archive-contents nil)))
2846 (defun package-menu--find-and-notify-upgrades ()
2847 "Notify the user of upgradable packages."
2848 (when-let ((upgrades (package-menu--find-upgrades)))
2849 (message "%d package%s can be upgraded; type `%s' to mark %s for upgrading."
2850 (length upgrades)
2851 (if (= (length upgrades) 1) "" "s")
2852 (substitute-command-keys "\\[package-menu-mark-upgrades]")
2853 (if (= (length upgrades) 1) "it" "them"))))
2855 (defun package-menu--post-refresh ()
2856 "Check for new packages, revert the *Packages* buffer, and check for upgrades.
2857 This function is called after `package-refresh-contents' and
2858 after `package-menu--perform-transaction'."
2859 (package-menu--populate-new-package-list)
2860 (let ((buf (get-buffer "*Packages*")))
2861 (when (buffer-live-p buf)
2862 (with-current-buffer buf
2863 (revert-buffer nil 'noconfirm))))
2864 (package-menu--find-and-notify-upgrades))
2866 (defcustom package-menu-async t
2867 "If non-nil, package-menu will use async operations when possible.
2868 This includes refreshing archive contents as well as installing
2869 packages."
2870 :type 'boolean
2871 :group 'package)
2873 ;;;###autoload
2874 (defun list-packages (&optional no-fetch)
2875 "Display a list of packages.
2876 This first fetches the updated list of packages before
2877 displaying, unless a prefix argument NO-FETCH is specified.
2878 The list is displayed in a buffer named `*Packages*'."
2879 (interactive "P")
2880 (require 'finder-inf nil t)
2881 ;; Initialize the package system if necessary.
2882 (unless package--initialized
2883 (package-initialize t))
2884 ;; Integrate the package-menu with updating the archives.
2885 (add-hook 'package--post-download-archives-hook
2886 #'package-menu--post-refresh)
2888 (unless no-fetch
2889 (setq package-menu--old-archive-contents package-archive-contents)
2890 (setq package-menu--new-package-list nil)
2891 ;; Fetch the remote list of packages.
2892 (package-refresh-contents package-menu-async))
2894 ;; Generate the Package Menu.
2895 (let ((buf (get-buffer-create "*Packages*")))
2896 (with-current-buffer buf
2897 (package-menu-mode)
2898 (package-menu--generate nil t))
2899 ;; The package menu buffer has keybindings. If the user types
2900 ;; `M-x list-packages', that suggests it should become current.
2901 (switch-to-buffer buf)))
2903 ;;;###autoload
2904 (defalias 'package-list-packages 'list-packages)
2906 ;; Used in finder.el
2907 (defun package-show-package-list (&optional packages keywords)
2908 "Display PACKAGES in a *Packages* buffer.
2909 This is similar to `list-packages', but it does not fetch the
2910 updated list of packages, and it only displays packages with
2911 names in PACKAGES (which should be a list of symbols).
2913 When KEYWORDS are given, only packages with those KEYWORDS are
2914 shown."
2915 (interactive)
2916 (require 'finder-inf nil t)
2917 (let* ((buf (get-buffer-create "*Packages*"))
2918 (win (get-buffer-window buf)))
2919 (with-current-buffer buf
2920 (package-menu-mode)
2921 (package-menu--generate nil packages keywords))
2922 (if win
2923 (select-window win)
2924 (switch-to-buffer buf))))
2926 ;; package-menu--generate rebinds "q" on the fly, so we have to
2927 ;; hard-code the binding in the doc-string here.
2928 (defun package-menu-filter (keyword)
2929 "Filter the *Packages* buffer.
2930 Show only those items that relate to the specified KEYWORD.
2931 To restore the full package list, type `q'."
2932 (interactive (list (completing-read "Keyword: " (package-all-keywords))))
2933 (package-show-package-list t (list keyword)))
2935 (defun package-list-packages-no-fetch ()
2936 "Display a list of packages.
2937 Does not fetch the updated list of packages before displaying.
2938 The list is displayed in a buffer named `*Packages*'."
2939 (interactive)
2940 (list-packages t))
2942 (provide 'package)
2944 ;;; package.el ends here