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