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