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