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