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