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