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