* emacs-lisp/package.el: Make package-menu asynchronous.
[emacs.git] / lisp / emacs-lisp / package.el
blob490fb45a98ff2709bc2cb04a3ca3743d04dca5b2
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, the operation is run
1088 asynchronously. If an error is encountered and ASYNC is a
1089 function, it is called with no arguments (instead of executing
1090 body), otherwise the error is propagated. For description on the
1091 other arguments see `package--with-work-buffer'."
1092 (declare (indent 3) (debug t))
1093 `(if (or (not ,async)
1094 (not (string-match-p "\\`https?:" ,location)))
1095 (package--with-work-buffer ,location ,file ,@body)
1096 (url-retrieve (concat ,location ,file)
1097 (lambda (status)
1098 (if (eq (car status) :error)
1099 (if (functionp ,async)
1100 (funcall ,async)
1101 (signal (cdar status) (cddr status)))
1102 (goto-char (point-min))
1103 (unless (search-forward "\n\n" nil 'noerror)
1104 (error "Invalid url response"))
1105 (delete-region (point-min) (point))
1106 ,@body)
1107 (kill-buffer (current-buffer)))
1109 'silent)))
1111 (defun package--check-signature-content (content string &optional sig-file)
1112 "Check signature CONTENT against STRING.
1113 SIG-FILE is the name of the signature file, used when signaling
1114 errors."
1115 (let* ((context (epg-make-context 'OpenPGP))
1116 (homedir (expand-file-name "gnupg" package-user-dir)))
1117 (setf (epg-context-home-directory context) homedir)
1118 (condition-case error
1119 (epg-verify-string context content string)
1120 (error (package--display-verify-error context sig-file)
1121 (signal (car error) (cdr error))))
1122 (let (good-signatures had-fatal-error)
1123 ;; The .sig file may contain multiple signatures. Success if one
1124 ;; of the signatures is good.
1125 (dolist (sig (epg-context-result-for context 'verify))
1126 (if (eq (epg-signature-status sig) 'good)
1127 (push sig good-signatures)
1128 ;; If package-check-signature is allow-unsigned, don't
1129 ;; signal error when we can't verify signature because of
1130 ;; missing public key. Other errors are still treated as
1131 ;; fatal (bug#17625).
1132 (unless (and (eq package-check-signature 'allow-unsigned)
1133 (eq (epg-signature-status sig) 'no-pubkey))
1134 (setq had-fatal-error t))))
1135 (when (and (null good-signatures) had-fatal-error)
1136 (package--display-verify-error context sig-file)
1137 (error "Failed to verify signature %s" sig-file))
1138 good-signatures)))
1140 (defun package--check-signature (location file &optional string async callback)
1141 "Check signature of the current buffer.
1142 Signature file is downloaded from LOCATION by appending \".sig\"
1143 to FILE.
1144 GnuPG keyring is located under \"gnupg\" in `package-user-dir'.
1145 STRING is the string to verify, it defaults to `buffer-string'.
1146 If ASYNC is non-nil, the download of the signature file is
1147 done asynchronously.
1149 If the signature is verified and CALLBACK was provided, CALLBACK
1150 is `funcall'ed with the list of good signatures as argument (the
1151 list can be empty). If the signatures file is not found,
1152 CALLBACK is called with no arguments."
1153 (let ((sig-file (concat file ".sig"))
1154 (string (or string (buffer-string))))
1155 (condition-case nil
1156 (package--with-work-buffer-async
1157 location sig-file (when async (or callback t))
1158 (let ((sig (package--check-signature-content
1159 (buffer-string) string sig-file)))
1160 (when callback (funcall callback sig))
1161 sig))
1162 (file-error (funcall callback)))))
1165 ;;; Packages on Archives
1166 ;; The following variables store information about packages available
1167 ;; from archives. The most important of these is
1168 ;; `package-archive-contents' which is initially populated by the
1169 ;; function `package-read-all-archive-contents' from a cache on disk.
1170 ;; The `package-initialize' command is also closely related to this
1171 ;; section, but it has its own section.
1172 (defconst package-archive-version 1
1173 "Version number of the package archive understood by this file.
1174 Lower version numbers than this will probably be understood as well.")
1176 ;; We don't prime the cache since it tends to get out of date.
1177 (defvar package-archive-contents nil
1178 "Cache of the contents of the Emacs Lisp Package Archive.
1179 This is an alist mapping package names (symbols) to
1180 non-empty lists of `package-desc' structures.")
1181 (put 'package-archive-contents 'risky-local-variable t)
1183 (defvar package--compatibility-table nil
1184 "Hash table connecting package names to their compatibility.
1185 Each key is a symbol, the name of a package.
1187 The value is either nil, representing an incompatible package, or
1188 a version list, representing the highest compatible version of
1189 that package which is available.
1191 A package is considered incompatible if it requires an Emacs
1192 version higher than the one being used. To check for package
1193 \(in)compatibility, don't read this table directly, use
1194 `package--incompatible-p' which also checks dependencies.")
1196 (defun package--build-compatibility-table ()
1197 "Build `package--compatibility-table' with `package--mapc'."
1198 ;; Build compat table.
1199 (setq package--compatibility-table (make-hash-table :test 'eq))
1200 (package--mapc #'package--add-to-compatibility-table))
1202 (defun package--add-to-compatibility-table (pkg)
1203 "If PKG is compatible (without dependencies), add to the compatibility table.
1204 PKG is a package-desc object.
1205 Only adds if its version is higher than what's already stored in
1206 the table."
1207 (unless (package--incompatible-p pkg 'shallow)
1208 (let* ((name (package-desc-name pkg))
1209 (version (or (package-desc-version pkg) '(0)))
1210 (table-version (gethash name package--compatibility-table)))
1211 (when (or (not table-version)
1212 (version-list-< table-version version))
1213 (puthash name version package--compatibility-table)))))
1215 ;; Package descriptor objects used inside the "archive-contents" file.
1216 ;; Changing this defstruct implies changing the format of the
1217 ;; "archive-contents" files.
1218 (cl-defstruct (package--ac-desc
1219 (:constructor package-make-ac-desc (version reqs summary kind extras))
1220 (:copier nil)
1221 (:type vector))
1222 version reqs summary kind extras)
1224 (defun package--append-to-alist (pkg-desc alist)
1225 "Append an entry for PKG-DESC to the start of ALIST and return it.
1226 This entry takes the form (`package-desc-name' PKG-DESC).
1228 If ALIST already has an entry with this name, destructively add
1229 PKG-DESC to the cdr of this entry instead, sorted by version
1230 number."
1231 (let* ((name (package-desc-name pkg-desc))
1232 (priority-version (package-desc-priority-version pkg-desc))
1233 (existing-packages (assq name alist)))
1234 (if (not existing-packages)
1235 (cons (list name pkg-desc)
1236 alist)
1237 (while (if (and (cdr existing-packages)
1238 (version-list-< priority-version
1239 (package-desc-priority-version
1240 (cadr existing-packages))))
1241 (setq existing-packages (cdr existing-packages))
1242 (push pkg-desc (cdr existing-packages))
1243 nil))
1244 alist)))
1246 (defun package--add-to-archive-contents (package archive)
1247 "Add the PACKAGE from the given ARCHIVE if necessary.
1248 PACKAGE should have the form (NAME . PACKAGE--AC-DESC).
1249 Also, add the originating archive to the `package-desc' structure."
1250 (let* ((name (car package))
1251 (version (package--ac-desc-version (cdr package)))
1252 (pkg-desc
1253 (package-desc-create
1254 :name name
1255 :version version
1256 :reqs (package--ac-desc-reqs (cdr package))
1257 :summary (package--ac-desc-summary (cdr package))
1258 :kind (package--ac-desc-kind (cdr package))
1259 :archive archive
1260 :extras (and (> (length (cdr package)) 4)
1261 ;; Older archive-contents files have only 4
1262 ;; elements here.
1263 (package--ac-desc-extras (cdr package)))))
1264 (pinned-to-archive (assoc name package-pinned-packages)))
1265 ;; Skip entirely if pinned to another archive.
1266 (when (not (and pinned-to-archive
1267 (not (equal (cdr pinned-to-archive) archive))))
1268 (setq package-archive-contents
1269 (package--append-to-alist pkg-desc package-archive-contents)))))
1271 (defun package--read-archive-file (file)
1272 "Re-read archive file FILE, if it exists.
1273 Will return the data from the file, or nil if the file does not exist.
1274 Will throw an error if the archive version is too new."
1275 (let ((filename (expand-file-name file package-user-dir)))
1276 (when (file-exists-p filename)
1277 (with-temp-buffer
1278 (insert-file-contents-literally filename)
1279 (let ((contents (read (current-buffer))))
1280 (if (> (car contents) package-archive-version)
1281 (error "Package archive version %d is higher than %d"
1282 (car contents) package-archive-version))
1283 (cdr contents))))))
1285 (defun package-read-archive-contents (archive)
1286 "Re-read archive contents for ARCHIVE.
1287 If successful, set the variable `package-archive-contents'.
1288 If the archive version is too new, signal an error."
1289 ;; Version 1 of 'archive-contents' is identical to our internal
1290 ;; representation.
1291 (let* ((contents-file (format "archives/%s/archive-contents" archive))
1292 (contents (package--read-archive-file contents-file)))
1293 (when contents
1294 (dolist (package contents)
1295 (package--add-to-archive-contents package archive)))))
1297 (defun package-read-all-archive-contents ()
1298 "Re-read `archive-contents', if it exists.
1299 If successful, set `package-archive-contents'."
1300 (setq package-archive-contents nil)
1301 (dolist (archive package-archives)
1302 (package-read-archive-contents (car archive))))
1304 ;;;; Package Initialize
1305 ;; A bit of a milestone. This brings together some of the above
1306 ;; sections and populates all relevant lists of packages from contents
1307 ;; available on disk.
1308 (defvar package--initialized nil)
1310 ;;;###autoload
1311 (defun package-initialize (&optional no-activate)
1312 "Load Emacs Lisp packages, and activate them.
1313 The variable `package-load-list' controls which packages to load.
1314 If optional arg NO-ACTIVATE is non-nil, don't activate packages."
1315 (interactive)
1316 (setq package-alist nil)
1317 (package-load-all-descriptors)
1318 (package-read-all-archive-contents)
1319 (unless no-activate
1320 (dolist (elt package-alist)
1321 (package-activate (car elt))))
1322 (setq package--initialized t)
1323 ;; This uses `package--mapc' so it must be called after
1324 ;; `package--initialized' is t.
1325 (package--build-compatibility-table))
1328 ;;;; Populating `package-archive-contents' from archives
1329 ;; This subsection populates the variables listed above from the
1330 ;; actual archives, instead of from a local cache.
1331 (defvar package--downloads-in-progress nil
1332 "List of in-progress asynchronous downloads.")
1334 (declare-function epg-check-configuration "epg-config"
1335 (config &optional minimum-version))
1336 (declare-function epg-configuration "epg-config" ())
1337 (declare-function epg-import-keys-from-file "epg" (context keys))
1339 ;;;###autoload
1340 (defun package-import-keyring (&optional file)
1341 "Import keys from FILE."
1342 (interactive "fFile: ")
1343 (setq file (expand-file-name file))
1344 (let ((context (epg-make-context 'OpenPGP))
1345 (homedir (expand-file-name "gnupg" package-user-dir)))
1346 (with-file-modes 448
1347 (make-directory homedir t))
1348 (setf (epg-context-home-directory context) homedir)
1349 (message "Importing %s..." (file-name-nondirectory file))
1350 (epg-import-keys-from-file context file)
1351 (message "Importing %s...done" (file-name-nondirectory file))))
1353 (defvar package--post-download-archives-hook nil
1354 "Hook run after the archive contents are downloaded.
1355 Don't run this hook directly. It is meant to be run as part of
1356 `package--update-downloads-in-progress'.")
1357 (put 'package--post-download-archives-hook 'risky-local-variable t)
1359 (defun package--update-downloads-in-progress (entry)
1360 "Remove ENTRY from `package--downloads-in-progress'.
1361 Once it's empty, run `package--post-download-archives-hook'."
1362 ;; Keep track of the downloading progress.
1363 (setq package--downloads-in-progress
1364 (remove entry package--downloads-in-progress))
1365 ;; If this was the last download, run the hook.
1366 (unless package--downloads-in-progress
1367 (package--build-compatibility-table)
1368 (package-read-all-archive-contents)
1369 ;; We message before running the hook, so the hook can give
1370 ;; messages as well.
1371 (message "Package refresh done")
1372 (run-hooks 'package--post-download-archives-hook)))
1374 (defun package--download-one-archive (archive file &optional async)
1375 "Retrieve an archive file FILE from ARCHIVE, and cache it.
1376 ARCHIVE should be a cons cell of the form (NAME . LOCATION),
1377 similar to an entry in `package-alist'. Save the cached copy to
1378 \"archives/NAME/FILE\" in `package-user-dir'."
1379 (package--with-work-buffer-async (cdr archive) file async
1380 (let* ((location (cdr archive))
1381 (name (car archive))
1382 (content (buffer-string))
1383 (dir (expand-file-name (format "archives/%s" name) package-user-dir))
1384 (local-file (expand-file-name file dir)))
1385 (when (listp (read-from-string content))
1386 (make-directory dir t)
1387 (if (or (not package-check-signature)
1388 (member archive package-unsigned-archives))
1389 ;; If we don't care about the signature, save the file and
1390 ;; we're done.
1391 (progn (write-region content nil local-file nil 'silent)
1392 (package--update-downloads-in-progress archive))
1393 ;; If we care, check it (perhaps async) and *then* write the file.
1394 (package--check-signature
1395 location file content async
1396 (lambda (&optional good-sigs)
1397 (unless (or good-sigs (eq package-check-signature 'allow-unsigned))
1398 (error "Unsigned archive `%s'" name))
1399 ;; Write out the archives file.
1400 (write-region content nil local-file nil 'silent)
1401 ;; Write out good signatures into archive-contents.signed file.
1402 (when good-sigs
1403 (write-region (mapconcat #'epg-signature-to-string good-sigs "\n")
1404 nil (concat local-file ".signed") nil 'silent))
1405 (package--update-downloads-in-progress archive))))))))
1407 (defun package--download-and-read-archives (&optional async)
1408 "Download descriptions of all `package-archives' and read them.
1409 This populates `package-archive-contents'. If ASYNC is non-nil,
1410 the downloads are performed asynchronously."
1411 ;; The dowloaded archive contents will be read as part of
1412 ;; `package--update-downloads-in-progress'.
1413 (setq package--downloads-in-progress package-archives)
1414 (dolist (archive package-archives)
1415 (condition-case-unless-debug nil
1416 (package--download-one-archive archive "archive-contents" async)
1417 (error (message "Failed to download `%s' archive."
1418 (car archive))))))
1420 ;;;###autoload
1421 (defun package-refresh-contents (&optional async)
1422 "Download descriptions of all configured ELPA packages.
1423 For each archive configured in the variable `package-archives',
1424 inform Emacs about the latest versions of all packages it offers,
1425 and make them available for download.
1426 Optional argument, ASYNC, specifies whether the downloads should
1427 be performed in the background."
1428 (interactive)
1429 ;; FIXME: Do it asynchronously.
1430 (unless (file-exists-p package-user-dir)
1431 (make-directory package-user-dir t))
1432 (let ((default-keyring (expand-file-name "package-keyring.gpg"
1433 data-directory)))
1434 (when (and package-check-signature (file-exists-p default-keyring))
1435 (condition-case-unless-debug error
1436 (progn
1437 (epg-check-configuration (epg-configuration))
1438 (package-import-keyring default-keyring))
1439 (error (message "Cannot import default keyring: %S" (cdr error))))))
1440 (package--download-and-read-archives async))
1443 ;;; Dependency Management
1444 ;; Calculating the full transaction necessary for an installation,
1445 ;; keeping track of which packages were installed strictly as
1446 ;; dependencies, and determining which packages cannot be removed
1447 ;; because they are dependencies.
1448 (defun package-compute-transaction (packages requirements &optional seen)
1449 "Return a list of packages to be installed, including PACKAGES.
1450 PACKAGES should be a list of `package-desc'.
1452 REQUIREMENTS should be a list of additional requirements; each
1453 element in this list should have the form (PACKAGE VERSION-LIST),
1454 where PACKAGE is a package name and VERSION-LIST is the required
1455 version of that package.
1457 This function recursively computes the requirements of the
1458 packages in REQUIREMENTS, and returns a list of all the packages
1459 that must be installed. Packages that are already installed are
1460 not included in this list.
1462 SEEN is used internally to detect infinite recursion."
1463 ;; FIXME: We really should use backtracking to explore the whole
1464 ;; search space (e.g. if foo require bar-1.3, and bar-1.4 requires toto-1.1
1465 ;; whereas bar-1.3 requires toto-1.0 and the user has put a hold on toto-1.0:
1466 ;; the current code might fail to see that it could install foo by using the
1467 ;; older bar-1.3).
1468 (dolist (elt requirements)
1469 (let* ((next-pkg (car elt))
1470 (next-version (cadr elt))
1471 (already ()))
1472 (dolist (pkg packages)
1473 (if (eq next-pkg (package-desc-name pkg))
1474 (setq already pkg)))
1475 (when already
1476 (if (version-list-<= next-version (package-desc-version already))
1477 ;; `next-pkg' is already in `packages', but its position there
1478 ;; means it might be installed too late: remove it from there, so
1479 ;; we re-add it (along with its dependencies) at an earlier place
1480 ;; below (bug#16994).
1481 (if (memq already seen) ;Avoid inf-loop on dependency cycles.
1482 (message "Dependency cycle going through %S"
1483 (package-desc-full-name already))
1484 (setq packages (delq already packages))
1485 (setq already nil))
1486 (error "Need package `%s-%s', but only %s is being installed"
1487 next-pkg (package-version-join next-version)
1488 (package-version-join (package-desc-version already)))))
1489 (cond
1490 (already nil)
1491 ((package-installed-p next-pkg next-version) nil)
1494 ;; A package is required, but not installed. It might also be
1495 ;; blocked via `package-load-list'.
1496 (let ((pkg-descs (cdr (assq next-pkg package-archive-contents)))
1497 (found nil)
1498 (problem nil))
1499 (while (and pkg-descs (not found))
1500 (let* ((pkg-desc (pop pkg-descs))
1501 (version (package-desc-version pkg-desc))
1502 (disabled (package-disabled-p next-pkg version)))
1503 (cond
1504 ((version-list-< version next-version)
1505 (error
1506 "Need package `%s-%s', but only %s is available"
1507 next-pkg (package-version-join next-version)
1508 (package-version-join version)))
1509 (disabled
1510 (unless problem
1511 (setq problem
1512 (if (stringp disabled)
1513 (format "Package `%s' held at version %s, \
1514 but version %s required"
1515 next-pkg disabled
1516 (package-version-join next-version))
1517 (format "Required package '%s' is disabled"
1518 next-pkg)))))
1519 (t (setq found pkg-desc)))))
1520 (unless found
1521 (if problem
1522 (error "%s" problem)
1523 (error "Package `%s-%s' is unavailable"
1524 next-pkg (package-version-join next-version))))
1525 (setq packages
1526 (package-compute-transaction (cons found packages)
1527 (package-desc-reqs found)
1528 (cons found seen))))))))
1529 packages)
1531 (defun package--find-non-dependencies ()
1532 "Return a list of installed packages which are not dependencies.
1533 Finds all packages in `package-alist' which are not dependencies
1534 of any other packages.
1535 Used to populate `package-selected-packages'."
1536 (let ((dep-list
1537 (delete-dups
1538 (apply #'append
1539 (mapcar (lambda (p) (mapcar #'car (package-desc-reqs (cadr p))))
1540 package-alist)))))
1541 (cl-loop for p in package-alist
1542 for name = (car p)
1543 unless (memq name dep-list)
1544 collect name)))
1546 (defun package--user-selected-p (pkg)
1547 "Return non-nil if PKG is a package was installed by the user.
1548 PKG is a package name.
1549 This looks into `package-selected-packages', populating it first
1550 if it is still empty."
1551 (unless (consp package-selected-packages)
1552 (customize-save-variable
1553 'package-selected-packages
1554 (setq package-selected-packages (package--find-non-dependencies))))
1555 (memq pkg package-selected-packages))
1557 (defun package--get-deps (pkg &optional only)
1558 (let* ((pkg-desc (cadr (assq pkg package-alist)))
1559 (direct-deps (cl-loop for p in (package-desc-reqs pkg-desc)
1560 for name = (car p)
1561 when (assq name package-alist)
1562 collect name))
1563 (indirect-deps (unless (eq only 'direct)
1564 (delete-dups
1565 (cl-loop for p in direct-deps
1566 append (package--get-deps p))))))
1567 (cl-case only
1568 (direct direct-deps)
1569 (separate (list direct-deps indirect-deps))
1570 (indirect indirect-deps)
1571 (t (delete-dups (append direct-deps indirect-deps))))))
1573 (defun package--removable-packages ()
1574 "Return a list of names of packages no longer needed.
1575 These are packages which are neither contained in
1576 `package-selected-packages' nor a dependency of one that is."
1577 (let ((needed (cl-loop for p in package-selected-packages
1578 if (assq p package-alist)
1579 ;; `p' and its dependencies are needed.
1580 append (cons p (package--get-deps p)))))
1581 (cl-loop for p in (mapcar #'car package-alist)
1582 unless (memq p needed)
1583 collect p)))
1585 (defun package--used-elsewhere-p (pkg-desc &optional pkg-list)
1586 "Non-nil if PKG-DESC is a dependency of a package in PKG-LIST.
1587 Return the first package found in PKG-LIST of which PKG is a
1588 dependency.
1590 When not specified, PKG-LIST defaults to `package-alist'
1591 with PKG-DESC entry removed."
1592 (unless (string= (package-desc-status pkg-desc) "obsolete")
1593 (let ((pkg (package-desc-name pkg-desc)))
1594 (cl-loop with alist = (or pkg-list
1595 (remove (assq pkg package-alist)
1596 package-alist))
1597 for p in alist thereis
1598 (and (memq pkg (mapcar #'car (package-desc-reqs (cadr p))))
1599 (car p))))))
1601 (defun package--sort-deps-in-alist (package only)
1602 "Return a list of dependencies for PACKAGE sorted by dependency.
1603 PACKAGE is included as the first element of the returned list.
1604 ONLY is an alist associating package names to package objects.
1605 Only these packages will be in the return value an their cdrs are
1606 destructively set to nil in ONLY."
1607 (let ((out))
1608 (dolist (dep (package-desc-reqs package))
1609 (when-let ((cell (assq (car dep) only))
1610 (dep-package (cdr-safe cell)))
1611 (setcdr cell nil)
1612 (setq out (append (package--sort-deps-in-alist dep-package only)
1613 out))))
1614 (cons package out)))
1616 (defun package--sort-by-dependence (package-list)
1617 "Return PACKAGE-LIST sorted by dependence.
1618 That is, any element of the returned list is guaranteed to not
1619 directly depend on any elements that come before it.
1621 PACKAGE-LIST is a list of package-desc objects.
1622 Indirect dependencies are guaranteed to be returned in order only
1623 if all the in-between dependencies are also in PACKAGE-LIST."
1624 (let ((alist (mapcar (lambda (p) (cons (package-desc-name p) p)) package-list))
1625 out-list)
1626 (dolist (cell alist out-list)
1627 ;; `package--sort-deps-in-alist' destructively changes alist, so
1628 ;; some cells might already be empty. We check this here.
1629 (when-let ((pkg-desc (cdr cell)))
1630 (setcdr cell nil)
1631 (setq out-list
1632 (append (package--sort-deps-in-alist pkg-desc alist)
1633 out-list))))))
1636 ;;; Installation Functions
1637 ;; As opposed to the previous section (which listed some underlying
1638 ;; functions necessary for installation), this one contains the actual
1639 ;; functions that install packages. The package itself can be
1640 ;; installed in a variety of ways (archives, buffer, file), but
1641 ;; requirements (dependencies) are always satisfied by looking in
1642 ;; `package-archive-contents'.
1643 (defun package-archive-base (desc)
1644 "Return the archive containing the package NAME."
1645 (cdr (assoc (package-desc-archive desc) package-archives)))
1647 (defun package-install-from-archive (pkg-desc)
1648 "Download and install a tar package."
1649 ;; This won't happen, unless the archive is doing something wrong.
1650 (when (eq (package-desc-kind pkg-desc) 'dir)
1651 (error "Can't install directory package from archive"))
1652 (let* ((location (package-archive-base pkg-desc))
1653 (file (concat (package-desc-full-name pkg-desc)
1654 (package-desc-suffix pkg-desc)))
1655 (sig-file (concat file ".sig"))
1656 good-signatures pkg-descs)
1657 (package--with-work-buffer location file
1658 (if (and package-check-signature
1659 (not (member (package-desc-archive pkg-desc)
1660 package-unsigned-archives)))
1661 (if (package--archive-file-exists-p location sig-file)
1662 (setq good-signatures (package--check-signature location file))
1663 (unless (eq package-check-signature 'allow-unsigned)
1664 (error "Unsigned package: `%s'"
1665 (package-desc-name pkg-desc)))))
1666 (package-unpack pkg-desc))
1667 ;; Here the package has been installed successfully, mark it as
1668 ;; signed if appropriate.
1669 (when good-signatures
1670 ;; Write out good signatures into NAME-VERSION.signed file.
1671 (write-region (mapconcat #'epg-signature-to-string good-signatures "\n")
1673 (expand-file-name
1674 (concat (package-desc-full-name pkg-desc)
1675 ".signed")
1676 package-user-dir)
1677 nil 'silent)
1678 ;; Update the old pkg-desc which will be shown on the description buffer.
1679 (setf (package-desc-signed pkg-desc) t)
1680 ;; Update the new (activated) pkg-desc as well.
1681 (setq pkg-descs (cdr (assq (package-desc-name pkg-desc) package-alist)))
1682 (if pkg-descs
1683 (setf (package-desc-signed (car pkg-descs)) t)))))
1685 (defun package-installed-p (package &optional min-version)
1686 "Return true if PACKAGE, of MIN-VERSION or newer, is installed.
1687 If PACKAGE is a symbol, it is the package name and MIN-VERSION
1688 should be a version list.
1690 If PACKAGE is a package-desc object, MIN-VERSION is ignored."
1691 (unless package--initialized (error "package.el is not yet initialized!"))
1692 (if (package-desc-p package)
1693 (let ((dir (package-desc-dir package)))
1694 (and (stringp dir)
1695 (file-exists-p dir)))
1697 (let ((pkg-descs (cdr (assq package package-alist))))
1698 (and pkg-descs
1699 (version-list-<= min-version
1700 (package-desc-version (car pkg-descs)))))
1701 ;; Also check built-in packages.
1702 (package-built-in-p package min-version))))
1704 (defun package-download-transaction (packages)
1705 "Download and install all the packages in PACKAGES.
1706 PACKAGES should be a list of package-desc.
1707 This function assumes that all package requirements in
1708 PACKAGES are satisfied, i.e. that PACKAGES is computed
1709 using `package-compute-transaction'."
1710 (mapc #'package-install-from-archive packages))
1712 ;;;###autoload
1713 (defun package-install (pkg &optional dont-select)
1714 "Install the package PKG.
1715 PKG can be a package-desc or the package name of one the available packages
1716 in an archive in `package-archives'. Interactively, prompt for its name.
1718 If called interactively or if DONT-SELECT nil, add PKG to
1719 `package-selected-packages'.
1721 If PKG is a package-desc and it is already installed, don't try
1722 to install it but still mark it as selected."
1723 (interactive
1724 (progn
1725 ;; Initialize the package system to get the list of package
1726 ;; symbols for completion.
1727 (unless package--initialized
1728 (package-initialize t))
1729 (unless package-archive-contents
1730 (package-refresh-contents))
1731 (list (intern (completing-read
1732 "Install package: "
1733 (delq nil
1734 (mapcar (lambda (elt)
1735 (unless (package-installed-p (car elt))
1736 (symbol-name (car elt))))
1737 package-archive-contents))
1738 nil t))
1739 nil)))
1740 (let ((name (if (package-desc-p pkg)
1741 (package-desc-name pkg)
1742 pkg)))
1743 (unless (or dont-select (package--user-selected-p name))
1744 (customize-save-variable 'package-selected-packages
1745 (cons name package-selected-packages))))
1746 (if (package-desc-p pkg)
1747 (if (package-installed-p pkg)
1748 (message "`%s' is already installed" (package-desc-full-name pkg))
1749 (package-download-transaction
1750 (package-compute-transaction (list pkg)
1751 (package-desc-reqs pkg))))
1752 (package-download-transaction
1753 (package-compute-transaction ()
1754 (list (list pkg))))))
1756 (defun package-strip-rcs-id (str)
1757 "Strip RCS version ID from the version string STR.
1758 If the result looks like a dotted numeric version, return it.
1759 Otherwise return nil."
1760 (when str
1761 (when (string-match "\\`[ \t]*[$]Revision:[ \t]+" str)
1762 (setq str (substring str (match-end 0))))
1763 (condition-case nil
1764 (if (version-to-list str)
1765 str)
1766 (error nil))))
1768 (declare-function lm-homepage "lisp-mnt" (&optional file))
1770 ;;;###autoload
1771 (defun package-install-from-buffer ()
1772 "Install a package from the current buffer.
1773 The current buffer is assumed to be a single .el or .tar file or
1774 a directory. These must follow the packaging guidelines (see
1775 info node `(elisp)Packaging').
1777 Specially, if current buffer is a directory, the -pkg.el
1778 description file is not mandatory, in which case the information
1779 is derived from the main .el file in the directory.
1781 Downloads and installs required packages as needed."
1782 (interactive)
1783 (let* ((pkg-desc
1784 (cond
1785 ((derived-mode-p 'dired-mode)
1786 ;; This is the only way a package-desc object with a `dir'
1787 ;; desc-kind can be created. Such packages can't be
1788 ;; uploaded or installed from archives, they can only be
1789 ;; installed from local buffers or directories.
1790 (package-dir-info))
1791 ((derived-mode-p 'tar-mode)
1792 (package-tar-file-info))
1794 (package-buffer-info))))
1795 (name (package-desc-name pkg-desc)))
1796 ;; Download and install the dependencies.
1797 (let* ((requires (package-desc-reqs pkg-desc))
1798 (transaction (package-compute-transaction nil requires)))
1799 (package-download-transaction transaction))
1800 ;; Install the package itself.
1801 (package-unpack pkg-desc)
1802 (unless (package--user-selected-p name)
1803 (customize-save-variable 'package-selected-packages
1804 (cons name package-selected-packages)))
1805 pkg-desc))
1807 ;;;###autoload
1808 (defun package-install-file (file)
1809 "Install a package from a file.
1810 The file can either be a tar file or an Emacs Lisp file."
1811 (interactive "fPackage file name: ")
1812 (with-temp-buffer
1813 (if (file-directory-p file)
1814 (progn
1815 (setq default-directory file)
1816 (dired-mode))
1817 (insert-file-contents-literally file)
1818 (when (string-match "\\.tar\\'" file) (tar-mode)))
1819 (package-install-from-buffer)))
1821 ;;;###autoload
1822 (defun package-install-user-selected-packages ()
1823 "Ensure packages in `package-selected-packages' are installed.
1824 If some packages are not installed propose to install them."
1825 (interactive)
1826 ;; We don't need to populate `package-selected-packages' before
1827 ;; using here, because the outcome is the same either way (nothing
1828 ;; gets installed).
1829 (if (not package-selected-packages)
1830 (message "`package-selected-packages' is empty, nothing to install")
1831 (cl-loop for p in package-selected-packages
1832 unless (package-installed-p p)
1833 collect p into lst
1834 finally
1835 (if lst
1836 (when (y-or-n-p
1837 (format "%s packages will be installed:\n%s, proceed?"
1838 (length lst)
1839 (mapconcat #'symbol-name lst ", ")))
1840 (mapc #'package-install lst))
1841 (message "All your packages are already installed")))))
1844 ;;; Package Deletion
1845 (defun package--newest-p (pkg)
1846 "Return t if PKG is the newest package with its name."
1847 (equal (cadr (assq (package-desc-name pkg) package-alist))
1848 pkg))
1850 (defun package-delete (pkg-desc &optional force nosave)
1851 "Delete package PKG-DESC.
1853 Argument PKG-DESC is a full description of package as vector.
1854 When package is used elsewhere as dependency of another package,
1855 refuse deleting it and return an error.
1856 If FORCE is non-nil package will be deleted even if it is used
1857 elsewhere.
1858 If NOSAVE is non-nil, the package is not removed from
1859 `package-selected-packages'."
1860 (let ((dir (package-desc-dir pkg-desc))
1861 (name (package-desc-name pkg-desc))
1862 pkg-used-elsewhere-by)
1863 ;; If the user is trying to delete this package, they definitely
1864 ;; don't want it marked as selected, so we remove it from
1865 ;; `package-selected-packages' even if it can't be deleted.
1866 (when (and (null nosave)
1867 (package--user-selected-p name)
1868 ;; Don't deselect if this is an older version of an
1869 ;; upgraded package.
1870 (package--newest-p pkg-desc))
1871 (customize-save-variable
1872 'package-selected-packages (remove name package-selected-packages)))
1873 (cond ((not (string-prefix-p (file-name-as-directory
1874 (expand-file-name package-user-dir))
1875 (expand-file-name dir)))
1876 ;; Don't delete "system" packages.
1877 (error "Package `%s' is a system package, not deleting"
1878 (package-desc-full-name pkg-desc)))
1879 ((and (null force)
1880 (setq pkg-used-elsewhere-by
1881 (package--used-elsewhere-p pkg-desc)))
1882 ;; Don't delete packages used as dependency elsewhere.
1883 (error "Package `%s' is used by `%s' as dependency, not deleting"
1884 (package-desc-full-name pkg-desc)
1885 pkg-used-elsewhere-by))
1887 (delete-directory dir t t)
1888 ;; Remove NAME-VERSION.signed file.
1889 (let ((signed-file (concat dir ".signed")))
1890 (if (file-exists-p signed-file)
1891 (delete-file signed-file)))
1892 ;; Update package-alist.
1893 (let ((pkgs (assq name package-alist)))
1894 (delete pkg-desc pkgs)
1895 (unless (cdr pkgs)
1896 (setq package-alist (delq pkgs package-alist))))
1897 (message "Package `%s' deleted." (package-desc-full-name pkg-desc))))))
1899 ;;;###autoload
1900 (defun package-reinstall (pkg)
1901 "Reinstall package PKG.
1902 PKG should be either a symbol, the package name, or a package-desc
1903 object."
1904 (interactive (list (intern (completing-read
1905 "Reinstall package: "
1906 (mapcar #'symbol-name
1907 (mapcar #'car package-alist))))))
1908 (package-delete
1909 (if (package-desc-p pkg) pkg (cadr (assq pkg package-alist)))
1910 'force 'nosave)
1911 (package-install pkg 'dont-select))
1913 ;;;###autoload
1914 (defun package-autoremove ()
1915 "Remove packages that are no more needed.
1917 Packages that are no more needed by other packages in
1918 `package-selected-packages' and their dependencies
1919 will be deleted."
1920 (interactive)
1921 ;; If `package-selected-packages' is nil, it would make no sense to
1922 ;; try to populate it here, because then `package-autoremove' will
1923 ;; do absolutely nothing.
1924 (when (or package-selected-packages
1925 (yes-or-no-p
1926 "`package-selected-packages' is empty! Really remove ALL packages? "))
1927 (let ((removable (package--removable-packages)))
1928 (if removable
1929 (when (y-or-n-p
1930 (format "%s packages will be deleted:\n%s, proceed? "
1931 (length removable)
1932 (mapconcat #'symbol-name removable ", ")))
1933 (mapc (lambda (p)
1934 (package-delete (cadr (assq p package-alist)) t))
1935 removable))
1936 (message "Nothing to autoremove")))))
1939 ;;;; Package description buffer.
1941 ;;;###autoload
1942 (defun describe-package (package)
1943 "Display the full documentation of PACKAGE (a symbol)."
1944 (interactive
1945 (let* ((guess (function-called-at-point)))
1946 (require 'finder-inf nil t)
1947 ;; Load the package list if necessary (but don't activate them).
1948 (unless package--initialized
1949 (package-initialize t))
1950 (let ((packages (append (mapcar 'car package-alist)
1951 (mapcar 'car package-archive-contents)
1952 (mapcar 'car package--builtins))))
1953 (unless (memq guess packages)
1954 (setq guess nil))
1955 (setq packages (mapcar 'symbol-name packages))
1956 (let ((val
1957 (completing-read (if guess
1958 (format "Describe package (default %s): "
1959 guess)
1960 "Describe package: ")
1961 packages nil t nil nil guess)))
1962 (list (intern val))))))
1963 (if (not (or (package-desc-p package) (and package (symbolp package))))
1964 (message "No package specified")
1965 (help-setup-xref (list #'describe-package package)
1966 (called-interactively-p 'interactive))
1967 (with-help-window (help-buffer)
1968 (with-current-buffer standard-output
1969 (describe-package-1 package)))))
1971 (declare-function lm-commentary "lisp-mnt" (&optional file))
1973 (defun describe-package-1 (pkg)
1974 (require 'lisp-mnt)
1975 (let* ((desc (or
1976 (if (package-desc-p pkg) pkg)
1977 (cadr (assq pkg package-alist))
1978 (let ((built-in (assq pkg package--builtins)))
1979 (if built-in
1980 (package--from-builtin built-in)
1981 (cadr (assq pkg package-archive-contents))))))
1982 (name (if desc (package-desc-name desc) pkg))
1983 (pkg-dir (if desc (package-desc-dir desc)))
1984 (reqs (if desc (package-desc-reqs desc)))
1985 (version (if desc (package-desc-version desc)))
1986 (archive (if desc (package-desc-archive desc)))
1987 (extras (and desc (package-desc-extras desc)))
1988 (homepage (cdr (assoc :url extras)))
1989 (keywords (if desc (package-desc--keywords desc)))
1990 (built-in (eq pkg-dir 'builtin))
1991 (installable (and archive (not built-in)))
1992 (status (if desc (package-desc-status desc) "orphan"))
1993 (incompatible-reason (package--incompatible-p desc))
1994 (signed (if desc (package-desc-signed desc))))
1995 (when incompatible-reason
1996 (setq status "incompatible"))
1997 (prin1 name)
1998 (princ " is ")
1999 (princ (if (memq (aref status 0) '(?a ?e ?i ?o ?u)) "an " "a "))
2000 (princ status)
2001 (princ " package.\n\n")
2003 (insert " " (propertize "Status" 'font-lock-face 'bold) ": ")
2004 (cond (built-in
2005 (insert (propertize (capitalize status)
2006 'font-lock-face 'font-lock-builtin-face)
2007 "."))
2008 (pkg-dir
2009 (insert (propertize (if (member status '("unsigned" "dependency"))
2010 "Installed"
2011 (capitalize status)) ;FIXME: Why comment-face?
2012 'font-lock-face 'font-lock-comment-face))
2013 (insert " in `")
2014 ;; Todo: Add button for uninstalling.
2015 (help-insert-xref-button (abbreviate-file-name
2016 (file-name-as-directory pkg-dir))
2017 'help-package-def pkg-dir)
2018 (if (and (package-built-in-p name)
2019 (not (package-built-in-p name version)))
2020 (insert "',\n shadowing a "
2021 (propertize "built-in package"
2022 'font-lock-face 'font-lock-builtin-face))
2023 (insert "'"))
2024 (if signed
2025 (insert ".")
2026 (insert " (unsigned).")))
2027 (incompatible-reason
2028 (insert (propertize "Incompatible" 'face font-lock-warning-face)
2029 " because it depends on ")
2030 (if (stringp incompatible-reason)
2031 (insert "Emacs " incompatible-reason ".")
2032 (insert "uninstallable packages.")))
2033 (installable
2034 (insert (capitalize status))
2035 (insert " from " (format "%s" archive))
2036 (insert " -- ")
2037 (package-make-button
2038 "Install"
2039 'action 'package-install-button-action
2040 'package-desc desc))
2041 (t (insert (capitalize status) ".")))
2042 (insert "\n")
2043 (insert " " (propertize "Archive" 'font-lock-face 'bold)
2044 ": " (or archive "n/a") "\n")
2045 (and version
2046 (insert " "
2047 (propertize "Version" 'font-lock-face 'bold) ": "
2048 (package-version-join version) "\n"))
2050 (setq reqs (if desc (package-desc-reqs desc)))
2051 (when reqs
2052 (insert " " (propertize "Requires" 'font-lock-face 'bold) ": ")
2053 (let ((first t))
2054 (dolist (req reqs)
2055 (let* ((name (car req))
2056 (vers (cadr req))
2057 (text (format "%s-%s" (symbol-name name)
2058 (package-version-join vers)))
2059 (reason (if (and (listp incompatible-reason)
2060 (assq name incompatible-reason))
2061 " (not available)" "")))
2062 (cond (first (setq first nil))
2063 ((>= (+ 2 (current-column) (length text) (length reason))
2064 (window-width))
2065 (insert ",\n "))
2066 (t (insert ", ")))
2067 (help-insert-xref-button text 'help-package name)
2068 (insert reason)))
2069 (insert "\n")))
2070 (insert " " (propertize "Summary" 'font-lock-face 'bold)
2071 ": " (if desc (package-desc-summary desc)) "\n")
2072 (when homepage
2073 (insert " " (propertize "Homepage" 'font-lock-face 'bold) ": ")
2074 (help-insert-xref-button homepage 'help-url homepage)
2075 (insert "\n"))
2076 (when keywords
2077 (insert " " (propertize "Keywords" 'font-lock-face 'bold) ": ")
2078 (dolist (k keywords)
2079 (package-make-button
2081 'package-keyword k
2082 'action 'package-keyword-button-action)
2083 (insert " "))
2084 (insert "\n"))
2085 (let* ((all-pkgs (append (cdr (assq name package-alist))
2086 (cdr (assq name package-archive-contents))
2087 (let ((bi (assq name package--builtins)))
2088 (if bi (list (package--from-builtin bi))))))
2089 (other-pkgs (delete desc all-pkgs)))
2090 (when other-pkgs
2091 (insert " " (propertize "Other versions" 'font-lock-face 'bold) ": "
2092 (mapconcat
2093 (lambda (opkg)
2094 (let* ((ov (package-desc-version opkg))
2095 (dir (package-desc-dir opkg))
2096 (from (or (package-desc-archive opkg)
2097 (if (stringp dir) "installed" dir))))
2098 (if (not ov) (format "%s" from)
2099 (format "%s (%s)"
2100 (make-text-button (package-version-join ov) nil
2101 'face 'link
2102 'follow-link t
2103 'action
2104 (lambda (_button)
2105 (describe-package opkg)))
2106 from))))
2107 other-pkgs ", ")
2108 ".\n")))
2110 (insert "\n")
2112 (if built-in
2113 ;; For built-in packages, insert the commentary.
2114 (let ((fn (locate-file (format "%s.el" name) load-path
2115 load-file-rep-suffixes))
2116 (opoint (point)))
2117 (insert (or (lm-commentary fn) ""))
2118 (save-excursion
2119 (goto-char opoint)
2120 (when (re-search-forward "^;;; Commentary:\n" nil t)
2121 (replace-match ""))
2122 (while (re-search-forward "^\\(;+ ?\\)" nil t)
2123 (replace-match ""))))
2124 (let ((readme (expand-file-name (format "%s-readme.txt" name)
2125 package-user-dir))
2126 readme-string)
2127 ;; For elpa packages, try downloading the commentary. If that
2128 ;; fails, try an existing readme file in `package-user-dir'.
2129 (cond ((condition-case nil
2130 (save-excursion
2131 (package--with-work-buffer
2132 (package-archive-base desc)
2133 (format "%s-readme.txt" name)
2134 (save-excursion
2135 (goto-char (point-max))
2136 (unless (bolp)
2137 (insert ?\n)))
2138 (write-region nil nil
2139 (expand-file-name readme package-user-dir)
2140 nil 'silent)
2141 (setq readme-string (buffer-string))
2143 (error nil))
2144 (insert readme-string))
2145 ((file-readable-p readme)
2146 (insert-file-contents readme)
2147 (goto-char (point-max))))))))
2149 (defun package-install-button-action (button)
2150 (let ((pkg-desc (button-get button 'package-desc)))
2151 (when (y-or-n-p (format "Install package `%s'? "
2152 (package-desc-full-name pkg-desc)))
2153 (package-install pkg-desc nil)
2154 (revert-buffer nil t)
2155 (goto-char (point-min)))))
2157 (defun package-keyword-button-action (button)
2158 (let ((pkg-keyword (button-get button 'package-keyword)))
2159 (package-show-package-list t (list pkg-keyword))))
2161 (defun package-make-button (text &rest props)
2162 (let ((button-text (if (display-graphic-p) text (concat "[" text "]")))
2163 (button-face (if (display-graphic-p)
2164 '(:box (:line-width 2 :color "dark grey")
2165 :background "light grey"
2166 :foreground "black")
2167 'link)))
2168 (apply 'insert-text-button button-text 'face button-face 'follow-link t
2169 props)))
2172 ;;;; Package menu mode.
2174 (defvar package-menu-mode-map
2175 (let ((map (make-sparse-keymap))
2176 (menu-map (make-sparse-keymap "Package")))
2177 (set-keymap-parent map tabulated-list-mode-map)
2178 (define-key map "\C-m" 'package-menu-describe-package)
2179 (define-key map "u" 'package-menu-mark-unmark)
2180 (define-key map "\177" 'package-menu-backup-unmark)
2181 (define-key map "d" 'package-menu-mark-delete)
2182 (define-key map "i" 'package-menu-mark-install)
2183 (define-key map "U" 'package-menu-mark-upgrades)
2184 (define-key map "r" 'package-menu-refresh)
2185 (define-key map "f" 'package-menu-filter)
2186 (define-key map "~" 'package-menu-mark-obsolete-for-deletion)
2187 (define-key map "x" 'package-menu-execute)
2188 (define-key map "h" 'package-menu-quick-help)
2189 (define-key map "?" 'package-menu-describe-package)
2190 (define-key map [menu-bar package-menu] (cons "Package" menu-map))
2191 (define-key menu-map [mq]
2192 '(menu-item "Quit" quit-window
2193 :help "Quit package selection"))
2194 (define-key menu-map [s1] '("--"))
2195 (define-key menu-map [mn]
2196 '(menu-item "Next" next-line
2197 :help "Next Line"))
2198 (define-key menu-map [mp]
2199 '(menu-item "Previous" previous-line
2200 :help "Previous Line"))
2201 (define-key menu-map [s2] '("--"))
2202 (define-key menu-map [mu]
2203 '(menu-item "Unmark" package-menu-mark-unmark
2204 :help "Clear any marks on a package and move to the next line"))
2205 (define-key menu-map [munm]
2206 '(menu-item "Unmark Backwards" package-menu-backup-unmark
2207 :help "Back up one line and clear any marks on that package"))
2208 (define-key menu-map [md]
2209 '(menu-item "Mark for Deletion" package-menu-mark-delete
2210 :help "Mark a package for deletion and move to the next line"))
2211 (define-key menu-map [mi]
2212 '(menu-item "Mark for Install" package-menu-mark-install
2213 :help "Mark a package for installation and move to the next line"))
2214 (define-key menu-map [mupgrades]
2215 '(menu-item "Mark Upgradable Packages" package-menu-mark-upgrades
2216 :help "Mark packages that have a newer version for upgrading"))
2217 (define-key menu-map [s3] '("--"))
2218 (define-key menu-map [mf]
2219 '(menu-item "Filter Package List..." package-menu-filter
2220 :help "Filter package selection (q to go back)"))
2221 (define-key menu-map [mg]
2222 '(menu-item "Update Package List" revert-buffer
2223 :help "Update the list of packages"))
2224 (define-key menu-map [mr]
2225 '(menu-item "Refresh Package List" package-menu-refresh
2226 :help "Download the ELPA archive"))
2227 (define-key menu-map [s4] '("--"))
2228 (define-key menu-map [mt]
2229 '(menu-item "Mark Obsolete Packages" package-menu-mark-obsolete-for-deletion
2230 :help "Mark all obsolete packages for deletion"))
2231 (define-key menu-map [mx]
2232 '(menu-item "Execute Actions" package-menu-execute
2233 :help "Perform all the marked actions"))
2234 (define-key menu-map [s5] '("--"))
2235 (define-key menu-map [mh]
2236 '(menu-item "Help" package-menu-quick-help
2237 :help "Show short key binding help for package-menu-mode"))
2238 (define-key menu-map [mc]
2239 '(menu-item "Describe Package" package-menu-describe-package
2240 :help "Display information about this package"))
2241 map)
2242 "Local keymap for `package-menu-mode' buffers.")
2244 (defvar-local package-menu--new-package-list nil
2245 "List of newly-available packages since `list-packages' was last called.")
2247 (define-derived-mode package-menu-mode tabulated-list-mode "Package Menu"
2248 "Major mode for browsing a list of packages.
2249 Letters do not insert themselves; instead, they are commands.
2250 \\<package-menu-mode-map>
2251 \\{package-menu-mode-map}"
2252 (setq tabulated-list-format
2253 `[("Package" 18 package-menu--name-predicate)
2254 ("Version" 13 nil)
2255 ("Status" 10 package-menu--status-predicate)
2256 ,@(if (cdr package-archives)
2257 '(("Archive" 10 package-menu--archive-predicate)))
2258 ("Description" 0 nil)])
2259 (setq tabulated-list-padding 2)
2260 (setq tabulated-list-sort-key (cons "Status" nil))
2261 (add-hook 'tabulated-list-revert-hook 'package-menu--refresh nil t)
2262 (tabulated-list-init-header))
2264 (defmacro package--push (pkg-desc status listname)
2265 "Convenience macro for `package-menu--generate'.
2266 If the alist stored in the symbol LISTNAME lacks an entry for a
2267 package PKG-DESC, add one. The alist is keyed with PKG-DESC."
2268 `(unless (assoc ,pkg-desc ,listname)
2269 ;; FIXME: Should we move status into pkg-desc?
2270 (push (cons ,pkg-desc ,status) ,listname)))
2272 (defvar package-list-unversioned nil
2273 "If non-nil include packages that don't have a version in `list-package'.")
2275 (defvar package-list-unsigned nil
2276 "If non-nil, mention in the list which packages were installed w/o signature.")
2278 (defvar package--emacs-version-list (version-to-list emacs-version)
2279 "`emacs-version', as a list.")
2281 (defun package--incompatible-p (pkg &optional shallow)
2282 "Return non-nil if PKG has no chance of being installable.
2283 PKG is a package-desc object.
2285 If SHALLOW is non-nil, this only checks if PKG depends on a
2286 higher `emacs-version' than the one being used. Otherwise, also
2287 checks the viability of dependencies, according to
2288 `package--compatibility-table'.
2290 If PKG requires an incompatible Emacs version, the return value
2291 is this version (as a string).
2292 If PKG requires incompatible packages, the return value is a list
2293 of these dependencies, similar to the list returned by
2294 `package-desc-reqs'."
2295 (let* ((reqs (package-desc-reqs pkg))
2296 (version (cadr (assq 'emacs reqs))))
2297 (if (and version (version-list-< package--emacs-version-list version))
2298 (package-version-join version)
2299 (unless shallow
2300 (let (out)
2301 (dolist (dep (package-desc-reqs pkg) out)
2302 (let ((dep-name (car dep)))
2303 (unless (eq 'emacs dep-name)
2304 (let ((cv (gethash dep-name package--compatibility-table)))
2305 (when (version-list-< (or cv '(0)) (or (cadr dep) '(0)))
2306 (push dep out)))))))))))
2308 (defun package-desc-status (pkg-desc)
2309 (let* ((name (package-desc-name pkg-desc))
2310 (dir (package-desc-dir pkg-desc))
2311 (lle (assq name package-load-list))
2312 (held (cadr lle))
2313 (version (package-desc-version pkg-desc))
2314 (signed (or (not package-list-unsigned)
2315 (package-desc-signed pkg-desc))))
2316 (cond
2317 ((eq dir 'builtin) "built-in")
2318 ((and lle (null held)) "disabled")
2319 ((stringp held)
2320 (let ((hv (if (stringp held) (version-to-list held))))
2321 (cond
2322 ((version-list-= version hv) "held")
2323 ((version-list-< version hv) "obsolete")
2324 (t "disabled"))))
2325 ((package-built-in-p name version) "obsolete")
2326 ((package--incompatible-p pkg-desc) "incompat")
2327 (dir ;One of the installed packages.
2328 (cond
2329 ((not (file-exists-p (package-desc-dir pkg-desc))) "deleted")
2330 ((eq pkg-desc (cadr (assq name package-alist)))
2331 (if (not signed) "unsigned"
2332 (if (package--user-selected-p name)
2333 "installed" "dependency")))
2334 (t "obsolete")))
2336 (let* ((ins (cadr (assq name package-alist)))
2337 (ins-v (if ins (package-desc-version ins))))
2338 (cond
2339 ((or (null ins) (version-list-< ins-v version))
2340 (if (memq name package-menu--new-package-list)
2341 "new" "available"))
2342 ((version-list-< version ins-v) "obsolete")
2343 ((version-list-= version ins-v)
2344 (if (not signed) "unsigned"
2345 (if (package--user-selected-p name)
2346 "installed" "dependency")))))))))
2348 (defun package-menu--refresh (&optional packages keywords)
2349 "Re-populate the `tabulated-list-entries'.
2350 PACKAGES should be nil or t, which means to display all known packages.
2351 KEYWORDS should be nil or a list of keywords."
2352 ;; Construct list of (PKG-DESC . STATUS).
2353 (unless packages (setq packages t))
2354 (let (info-list name)
2355 ;; Installed packages:
2356 (dolist (elt package-alist)
2357 (setq name (car elt))
2358 (when (or (eq packages t) (memq name packages))
2359 (dolist (pkg (cdr elt))
2360 (when (package--has-keyword-p pkg keywords)
2361 (package--push pkg (package-desc-status pkg) info-list)))))
2363 ;; Built-in packages:
2364 (dolist (elt package--builtins)
2365 (setq name (car elt))
2366 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
2367 (package--has-keyword-p (package--from-builtin elt) keywords)
2368 (or package-list-unversioned
2369 (package--bi-desc-version (cdr elt)))
2370 (or (eq packages t) (memq name packages)))
2371 (package--push (package--from-builtin elt) "built-in" info-list)))
2373 ;; Available and disabled packages:
2374 (dolist (elt package-archive-contents)
2375 (setq name (car elt))
2376 (when (or (eq packages t) (memq name packages))
2377 (dolist (pkg (cdr elt))
2378 ;; Hide obsolete packages.
2379 (when (and (not (package-installed-p (package-desc-name pkg)
2380 (package-desc-version pkg)))
2381 (package--has-keyword-p pkg keywords))
2382 (package--push pkg (package-desc-status pkg) info-list)))))
2384 ;; Print the result.
2385 (setq tabulated-list-entries
2386 (mapcar #'package-menu--print-info info-list))))
2388 (defun package-all-keywords ()
2389 "Collect all package keywords"
2390 (let (keywords)
2391 (package--mapc (lambda (desc)
2392 (let* ((desc-keywords (and desc (package-desc--keywords desc))))
2393 (setq keywords (append keywords desc-keywords)))))
2394 keywords))
2396 (defun package--mapc (function &optional packages)
2397 "Call FUNCTION for all known PACKAGES.
2398 PACKAGES can be nil or t, which means to display all known
2399 packages, or a list of packages.
2401 Built-in packages are converted with `package--from-builtin'."
2402 (unless packages (setq packages t))
2403 (let (name)
2404 ;; Installed packages:
2405 (dolist (elt package-alist)
2406 (setq name (car elt))
2407 (when (or (eq packages t) (memq name packages))
2408 (mapc function (cdr elt))))
2410 ;; Built-in packages:
2411 (dolist (elt package--builtins)
2412 (setq name (car elt))
2413 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
2414 (or package-list-unversioned
2415 (package--bi-desc-version (cdr elt)))
2416 (or (eq packages t) (memq name packages)))
2417 (funcall function (package--from-builtin elt))))
2419 ;; Available and disabled packages:
2420 (dolist (elt package-archive-contents)
2421 (setq name (car elt))
2422 (when (or (eq packages t) (memq name packages))
2423 (dolist (pkg (cdr elt))
2424 ;; Hide obsolete packages.
2425 (unless (package-installed-p (package-desc-name pkg)
2426 (package-desc-version pkg))
2427 (funcall function pkg)))))))
2429 (defun package--has-keyword-p (desc &optional keywords)
2430 "Test if package DESC has any of the given KEYWORDS.
2431 When none are given, the package matches."
2432 (if keywords
2433 (let* ((desc-keywords (and desc (package-desc--keywords desc)))
2434 found)
2435 (dolist (k keywords)
2436 (when (and (not found)
2437 (member k desc-keywords))
2438 (setq found t)))
2439 found)
2442 (defun package-menu--generate (remember-pos packages &optional keywords)
2443 "Populate the Package Menu.
2444 If REMEMBER-POS is non-nil, keep point on the same entry.
2445 PACKAGES should be t, which means to display all known packages,
2446 or a list of package names (symbols) to display.
2448 With KEYWORDS given, only packages with those keywords are
2449 shown."
2450 (package-menu--refresh packages keywords)
2451 (setf (car (aref tabulated-list-format 0))
2452 (if keywords
2453 (let ((filters (mapconcat 'identity keywords ",")))
2454 (concat "Package[" filters "]"))
2455 "Package"))
2456 (if keywords
2457 (define-key package-menu-mode-map "q" 'package-show-package-list)
2458 (define-key package-menu-mode-map "q" 'quit-window))
2459 (tabulated-list-init-header)
2460 (tabulated-list-print remember-pos))
2462 (defun package-menu--print-info (pkg)
2463 "Return a package entry suitable for `tabulated-list-entries'.
2464 PKG has the form (PKG-DESC . STATUS).
2465 Return (PKG-DESC [NAME VERSION STATUS DOC])."
2466 (let* ((pkg-desc (car pkg))
2467 (status (cdr pkg))
2468 (face (pcase status
2469 (`"built-in" 'font-lock-builtin-face)
2470 (`"available" 'default)
2471 (`"new" 'bold)
2472 (`"held" 'font-lock-constant-face)
2473 (`"disabled" 'font-lock-warning-face)
2474 (`"installed" 'font-lock-comment-face)
2475 (`"dependency" 'font-lock-comment-face)
2476 (`"unsigned" 'font-lock-warning-face)
2477 (`"incompat" 'font-lock-comment-face)
2478 (_ 'font-lock-warning-face)))) ; obsolete.
2479 (list pkg-desc
2480 `[,(list (symbol-name (package-desc-name pkg-desc))
2481 'face 'link
2482 'follow-link t
2483 'package-desc pkg-desc
2484 'action 'package-menu-describe-package)
2485 ,(propertize (package-version-join
2486 (package-desc-version pkg-desc))
2487 'font-lock-face face)
2488 ,(propertize status 'font-lock-face face)
2489 ,@(if (cdr package-archives)
2490 (list (propertize (or (package-desc-archive pkg-desc) "")
2491 'font-lock-face face)))
2492 ,(propertize (package-desc-summary pkg-desc)
2493 'font-lock-face face)])))
2495 (defun package-menu-refresh ()
2496 "Download the Emacs Lisp package archive.
2497 This fetches the contents of each archive specified in
2498 `package-archives', and then refreshes the package menu."
2499 (interactive)
2500 (unless (derived-mode-p 'package-menu-mode)
2501 (user-error "The current buffer is not a Package Menu"))
2502 (package-refresh-contents)
2503 (package-menu--generate t t))
2505 (defun package-menu-describe-package (&optional button)
2506 "Describe the current package.
2507 If optional arg BUTTON is non-nil, describe its associated package."
2508 (interactive)
2509 (let ((pkg-desc (if button (button-get button 'package-desc)
2510 (tabulated-list-get-id))))
2511 (if pkg-desc
2512 (describe-package pkg-desc)
2513 (user-error "No package here"))))
2515 ;; fixme numeric argument
2516 (defun package-menu-mark-delete (&optional _num)
2517 "Mark a package for deletion and move to the next line."
2518 (interactive "p")
2519 (if (member (package-menu-get-status)
2520 '("installed" "dependency" "obsolete" "unsigned"))
2521 (tabulated-list-put-tag "D" t)
2522 (forward-line)))
2524 (defun package-menu-mark-install (&optional _num)
2525 "Mark a package for installation and move to the next line."
2526 (interactive "p")
2527 (if (member (package-menu-get-status) '("available" "new" "dependency"))
2528 (tabulated-list-put-tag "I" t)
2529 (forward-line)))
2531 (defun package-menu-mark-unmark (&optional _num)
2532 "Clear any marks on a package and move to the next line."
2533 (interactive "p")
2534 (tabulated-list-put-tag " " t))
2536 (defun package-menu-backup-unmark ()
2537 "Back up one line and clear any marks on that package."
2538 (interactive)
2539 (forward-line -1)
2540 (tabulated-list-put-tag " "))
2542 (defun package-menu-mark-obsolete-for-deletion ()
2543 "Mark all obsolete packages for deletion."
2544 (interactive)
2545 (save-excursion
2546 (goto-char (point-min))
2547 (while (not (eobp))
2548 (if (equal (package-menu-get-status) "obsolete")
2549 (tabulated-list-put-tag "D" t)
2550 (forward-line 1)))))
2552 (defun package-menu-quick-help ()
2553 "Show short key binding help for package-menu-mode."
2554 (interactive)
2555 (message "n-ext, i-nstall, d-elete, u-nmark, x-ecute, r-efresh, h-elp"))
2557 (define-obsolete-function-alias
2558 'package-menu-view-commentary 'package-menu-describe-package "24.1")
2560 (defun package-menu-get-status ()
2561 (let* ((id (tabulated-list-get-id))
2562 (entry (and id (assq id tabulated-list-entries))))
2563 (if entry
2564 (aref (cadr entry) 2)
2565 "")))
2567 (defun package-archive-priority (archive)
2568 "Return the priority of ARCHIVE.
2570 The archive priorities are specified in
2571 `package-archive-priorities'. If not given there, the priority
2572 defaults to 0."
2573 (or (cdr (assoc archive package-archive-priorities))
2576 (defun package-desc-priority-version (pkg-desc)
2577 "Return the version PKG-DESC with the archive priority prepended.
2579 This allows for easy comparison of package versions from
2580 different archives if archive priorities are meant to be taken in
2581 consideration."
2582 (cons (package-archive-priority
2583 (package-desc-archive pkg-desc))
2584 (package-desc-version pkg-desc)))
2586 (defun package-menu--find-upgrades ()
2587 (let (installed available upgrades)
2588 ;; Build list of installed/available packages in this buffer.
2589 (dolist (entry tabulated-list-entries)
2590 ;; ENTRY is (PKG-DESC [NAME VERSION STATUS DOC])
2591 (let ((pkg-desc (car entry))
2592 (status (aref (cadr entry) 2)))
2593 (cond ((member status '("installed" "dependency" "unsigned"))
2594 (push pkg-desc installed))
2595 ((member status '("available" "new"))
2596 (setq available (package--append-to-alist pkg-desc available))))))
2597 ;; Loop through list of installed packages, finding upgrades.
2598 (dolist (pkg-desc installed)
2599 (let* ((name (package-desc-name pkg-desc))
2600 (avail-pkg (cadr (assq name available))))
2601 (and avail-pkg
2602 (version-list-< (package-desc-priority-version pkg-desc)
2603 (package-desc-priority-version avail-pkg))
2604 (push (cons name avail-pkg) upgrades))))
2605 upgrades))
2607 (defun package-menu-mark-upgrades ()
2608 "Mark all upgradable packages in the Package Menu.
2609 For each installed package with a newer version available, place
2610 an (I)nstall flag on the available version and a (D)elete flag on
2611 the installed version. A subsequent \\[package-menu-execute]
2612 call will upgrade the package."
2613 (interactive)
2614 (unless (derived-mode-p 'package-menu-mode)
2615 (error "The current buffer is not a Package Menu"))
2616 (let ((upgrades (package-menu--find-upgrades)))
2617 (if (null upgrades)
2618 (message "No packages to upgrade.")
2619 (widen)
2620 (save-excursion
2621 (goto-char (point-min))
2622 (while (not (eobp))
2623 (let* ((pkg-desc (tabulated-list-get-id))
2624 (upgrade (cdr (assq (package-desc-name pkg-desc) upgrades))))
2625 (cond ((null upgrade)
2626 (forward-line 1))
2627 ((equal pkg-desc upgrade)
2628 (package-menu-mark-install))
2630 (package-menu-mark-delete))))))
2631 (message "%d package%s marked for upgrading."
2632 (length upgrades)
2633 (if (= (length upgrades) 1) "" "s")))))
2635 (defun package-menu-execute (&optional noquery)
2636 "Perform marked Package Menu actions.
2637 Packages marked for installation are downloaded and installed;
2638 packages marked for deletion are removed.
2639 Optional argument NOQUERY non-nil means do not ask the user to confirm."
2640 (interactive)
2641 (unless (derived-mode-p 'package-menu-mode)
2642 (error "The current buffer is not in Package Menu mode"))
2643 (let (install-list delete-list cmd pkg-desc)
2644 (save-excursion
2645 (goto-char (point-min))
2646 (while (not (eobp))
2647 (setq cmd (char-after))
2648 (unless (eq cmd ?\s)
2649 ;; This is the key PKG-DESC.
2650 (setq pkg-desc (tabulated-list-get-id))
2651 (cond ((eq cmd ?D)
2652 (push pkg-desc delete-list))
2653 ((eq cmd ?I)
2654 (push pkg-desc install-list))))
2655 (forward-line)))
2656 (when install-list
2657 (if (or
2658 noquery
2659 (yes-or-no-p
2660 (if (= (length install-list) 1)
2661 (format "Install package `%s'? "
2662 (package-desc-full-name (car install-list)))
2663 (format "Install these %d packages (%s)? "
2664 (length install-list)
2665 (mapconcat #'package-desc-full-name
2666 install-list ", ")))))
2667 (mapc (lambda (p)
2668 ;; Don't mark as selected if it's a new version of
2669 ;; an installed package.
2670 (package-install p (and (not (package-installed-p p))
2671 (package-installed-p
2672 (package-desc-name p)))))
2673 install-list)))
2674 ;; Delete packages, prompting if necessary.
2675 (when delete-list
2676 (if (or
2677 noquery
2678 (yes-or-no-p
2679 (if (= (length delete-list) 1)
2680 (format "Delete package `%s'? "
2681 (package-desc-full-name (car delete-list)))
2682 (format "Delete these %d packages (%s)? "
2683 (length delete-list)
2684 (mapconcat #'package-desc-full-name
2685 delete-list ", ")))))
2686 (dolist (elt (package--sort-by-dependence delete-list))
2687 (condition-case-unless-debug err
2688 (package-delete elt)
2689 (error (message (cadr err)))))
2690 (error "Aborted")))
2691 (if (not (or delete-list install-list))
2692 (message "No operations specified.")
2693 (when package-selected-packages
2694 (let ((removable (package--removable-packages)))
2695 (when (and removable
2696 (y-or-n-p
2697 (format "These %d packages are no longer needed, delete them (%s)? "
2698 (length removable)
2699 (mapconcat #'symbol-name removable ", "))))
2700 ;; We know these are removable, so we can use force instead of sorting them.
2701 (mapc (lambda (p) (package-delete (cadr (assq p package-alist)) 'force 'nosave))
2702 removable))))
2703 (package-menu--generate t t))))
2705 (defun package-menu--version-predicate (A B)
2706 (let ((vA (or (aref (cadr A) 1) '(0)))
2707 (vB (or (aref (cadr B) 1) '(0))))
2708 (if (version-list-= vA vB)
2709 (package-menu--name-predicate A B)
2710 (version-list-< vA vB))))
2712 (defun package-menu--status-predicate (A B)
2713 (let ((sA (aref (cadr A) 2))
2714 (sB (aref (cadr B) 2)))
2715 (cond ((string= sA sB)
2716 (package-menu--name-predicate A B))
2717 ((string= sA "new") t)
2718 ((string= sB "new") nil)
2719 ((string= sA "available") t)
2720 ((string= sB "available") nil)
2721 ((string= sA "installed") t)
2722 ((string= sB "installed") nil)
2723 ((string= sA "dependency") t)
2724 ((string= sB "dependency") nil)
2725 ((string= sA "unsigned") t)
2726 ((string= sB "unsigned") nil)
2727 ((string= sA "held") t)
2728 ((string= sB "held") nil)
2729 ((string= sA "built-in") t)
2730 ((string= sB "built-in") nil)
2731 ((string= sA "obsolete") t)
2732 ((string= sB "obsolete") nil)
2733 ((string= sA "incompat") t)
2734 ((string= sB "incompat") nil)
2735 (t (string< sA sB)))))
2737 (defun package-menu--description-predicate (A B)
2738 (let ((dA (aref (cadr A) 3))
2739 (dB (aref (cadr B) 3)))
2740 (if (string= dA dB)
2741 (package-menu--name-predicate A B)
2742 (string< dA dB))))
2744 (defun package-menu--name-predicate (A B)
2745 (string< (symbol-name (package-desc-name (car A)))
2746 (symbol-name (package-desc-name (car B)))))
2748 (defun package-menu--archive-predicate (A B)
2749 (string< (or (package-desc-archive (car A)) "")
2750 (or (package-desc-archive (car B)) "")))
2752 (defvar-local package-menu--old-archive-contents nil
2753 "`package-archive-contents' before the latest refresh.")
2755 (defun package-menu--populate-new-package-list ()
2756 "Decide which packages are new in `package-archives-contents'.
2757 Store this list in `package-menu--new-package-list'."
2758 ;; Find which packages are new.
2759 (when package-menu--old-archive-contents
2760 (dolist (elt package-archive-contents)
2761 (unless (assq (car elt) package-menu--old-archive-contents)
2762 (push (car elt) package-menu--new-package-list)))
2763 (setq package-menu--old-archive-contents nil)))
2765 (defun package-menu--find-and-notify-upgrades ()
2766 "Notify the user of upgradeable packages."
2767 (when-let ((upgrades (package-menu--find-upgrades)))
2768 (message "%d package%s can be upgraded; type `%s' to mark %s for upgrading."
2769 (length upgrades)
2770 (if (= (length upgrades) 1) "" "s")
2771 (substitute-command-keys "\\[package-menu-mark-upgrades]")
2772 (if (= (length upgrades) 1) "it" "them"))))
2774 (defun package-menu--post-refresh ()
2775 "Function to be called after `package-refresh-contents' is done.
2776 Checks for new packages, reverts the *Packages* buffer, and
2777 checks for upgrades.
2778 This goes in `package--post-download-archives-hook', so that it
2779 works with async refresh as well."
2780 (package-menu--populate-new-package-list)
2781 (let ((buf (get-buffer "*Packages*")))
2782 (when (buffer-live-p buf)
2783 (with-current-buffer buf
2784 (revert-buffer nil 'noconfirm))))
2785 (package-menu--find-and-notify-upgrades))
2787 (defcustom package-menu-async t
2788 "If non-nil, package-menu will use async operations when possible.
2789 Currently, only the refreshing of archive contents supports
2790 asynchronous operations. Package transactions are still done
2791 synchronously."
2792 :type 'boolean
2793 :group 'package)
2795 ;;;###autoload
2796 (defun list-packages (&optional no-fetch)
2797 "Display a list of packages.
2798 This first fetches the updated list of packages before
2799 displaying, unless a prefix argument NO-FETCH is specified.
2800 The list is displayed in a buffer named `*Packages*'."
2801 (interactive "P")
2802 (require 'finder-inf nil t)
2803 ;; Initialize the package system if necessary.
2804 (unless package--initialized
2805 (package-initialize t))
2806 ;; Integrate the package-menu with updating the archives.
2807 (add-hook 'package--post-download-archives-hook
2808 #'package-menu--post-refresh)
2810 (unless no-fetch
2811 (setq package-menu--old-archive-contents package-archive-contents)
2812 (setq package-menu--new-package-list nil)
2813 ;; Fetch the remote list of packages.
2814 (package-refresh-contents package-menu-async))
2816 ;; Generate the Package Menu.
2817 (let ((buf (get-buffer-create "*Packages*")))
2818 (with-current-buffer buf
2819 (package-menu-mode)
2820 (package-menu--generate nil t))
2821 ;; The package menu buffer has keybindings. If the user types
2822 ;; `M-x list-packages', that suggests it should become current.
2823 (switch-to-buffer buf)))
2825 ;;;###autoload
2826 (defalias 'package-list-packages 'list-packages)
2828 ;; Used in finder.el
2829 (defun package-show-package-list (&optional packages keywords)
2830 "Display PACKAGES in a *Packages* buffer.
2831 This is similar to `list-packages', but it does not fetch the
2832 updated list of packages, and it only displays packages with
2833 names in PACKAGES (which should be a list of symbols).
2835 When KEYWORDS are given, only packages with those KEYWORDS are
2836 shown."
2837 (interactive)
2838 (require 'finder-inf nil t)
2839 (let* ((buf (get-buffer-create "*Packages*"))
2840 (win (get-buffer-window buf)))
2841 (with-current-buffer buf
2842 (package-menu-mode)
2843 (package-menu--generate nil packages keywords))
2844 (if win
2845 (select-window win)
2846 (switch-to-buffer buf))))
2848 ;; package-menu--generate rebinds "q" on the fly, so we have to
2849 ;; hard-code the binding in the doc-string here.
2850 (defun package-menu-filter (keyword)
2851 "Filter the *Packages* buffer.
2852 Show only those items that relate to the specified KEYWORD.
2853 To restore the full package list, type `q'."
2854 (interactive (list (completing-read "Keyword: " (package-all-keywords))))
2855 (package-show-package-list t (list keyword)))
2857 (defun package-list-packages-no-fetch ()
2858 "Display a list of packages.
2859 Does not fetch the updated list of packages before displaying.
2860 The list is displayed in a buffer named `*Packages*'."
2861 (interactive)
2862 (list-packages t))
2864 (provide 'package)
2866 ;;; package.el ends here