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