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