package.el: various fixes.
[bpt/emacs.git] / lisp / emacs-lisp / package.el
1 ;;; package.el --- Simple package system for Emacs -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2007-2014 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 ;; - a trust mechanism, since compiling a package can run arbitrary code.
117 ;; For example, download package signatures and check that they match.
118 ;; - putting info dirs at the start of the info path means
119 ;; users see a weird ordering of categories. OTOH we want to
120 ;; override later entries. maybe emacs needs to enforce
121 ;; the standard layout?
122 ;; - put bytecode in a separate directory tree
123 ;; - perhaps give users a way to recompile their bytecode
124 ;; or do it automatically when emacs changes
125 ;; - give users a way to know whether a package is installed ok
126 ;; - give users a way to view a package's documentation when it
127 ;; only appears in the .el
128 ;; - use/extend checkdoc so people can tell if their package will work
129 ;; - "installed" instead of a blank in the status column
130 ;; - tramp needs its files to be compiled in a certain order.
131 ;; how to handle this? fix tramp?
132 ;; - on emacs 21 we don't kill the -autoloads.el buffer. what about 22?
133 ;; - maybe we need separate .elc directories for various emacs versions
134 ;; and also emacs-vs-xemacs. That way conditional compilation can
135 ;; work. But would this break anything?
136 ;; - should store the package's keywords in archive-contents, then
137 ;; let the users filter the package-menu by keyword. See
138 ;; finder-by-keyword. (We could also let people view the
139 ;; Commentary, but it isn't clear how useful this is.)
140 ;; - William Xu suggests being able to open a package file without
141 ;; installing it
142 ;; - Interface with desktop.el so that restarting after an install
143 ;; works properly
144 ;; - Use hierarchical layout. PKG/etc PKG/lisp PKG/info
145 ;; ... except maybe lisp?
146 ;; - It may be nice to have a macro that expands to the package's
147 ;; private data dir, aka ".../etc". Or, maybe data-directory
148 ;; needs to be a list (though this would be less nice)
149 ;; a few packages want this, eg sokoban
150 ;; - package menu needs:
151 ;; ability to know which packages are built-in & thus not deletable
152 ;; it can sometimes print odd results, like 0.3 available but 0.4 active
153 ;; why is that?
154 ;; - Allow multiple versions on the server...?
155 ;; [ why bother? ]
156 ;; - Don't install a package which will invalidate dependencies overall
157 ;; - Allow something like (or (>= emacs 21.0) (>= xemacs 21.5))
158 ;; [ currently thinking, why bother.. KISS ]
159 ;; - Allow optional package dependencies
160 ;; then if we require 'bbdb', bbdb-specific lisp in lisp/bbdb
161 ;; and just don't compile to add to load path ...?
162 ;; - Our treatment of the info path is somewhat bogus
163
164 ;;; Code:
165
166 (eval-when-compile (require 'cl-lib))
167
168 (require 'tabulated-list)
169
170 (defgroup package nil
171 "Manager for Emacs Lisp packages."
172 :group 'applications
173 :version "24.1")
174
175 ;;;###autoload
176 (defcustom package-enable-at-startup t
177 "Whether to activate installed packages when Emacs starts.
178 If non-nil, packages are activated after reading the init file
179 and before `after-init-hook'. Activation is not done if
180 `user-init-file' is nil (e.g. Emacs was started with \"-q\").
181
182 Even if the value is nil, you can type \\[package-initialize] to
183 activate the package system at any time."
184 :type 'boolean
185 :group 'package
186 :version "24.1")
187
188 (defcustom package-load-list '(all)
189 "List of packages for `package-initialize' to load.
190 Each element in this list should be a list (NAME VERSION), or the
191 symbol `all'. The symbol `all' says to load the latest installed
192 versions of all packages not specified by other elements.
193
194 For an element (NAME VERSION), NAME is a package name (a symbol).
195 VERSION should be t, a string, or nil.
196 If VERSION is t, the most recent version is activated.
197 If VERSION is a string, only that version is ever loaded.
198 Any other version, even if newer, is silently ignored.
199 Hence, the package is \"held\" at that version.
200 If VERSION is nil, the package is not loaded (it is \"disabled\")."
201 :type '(repeat symbol)
202 :risky t
203 :group 'package
204 :version "24.1")
205
206 (defvar Info-directory-list)
207 (declare-function info-initialize "info" ())
208 (declare-function url-http-parse-response "url-http" ())
209 (declare-function url-http-file-exists-p "url-http" (url))
210 (declare-function lm-header "lisp-mnt" (header))
211 (declare-function lm-commentary "lisp-mnt" (&optional file))
212 (defvar url-http-end-of-headers)
213 (declare-function url-recreate-url "url" (urlobj))
214 (defvar url-http-target-url)
215
216 (defcustom package-archives '(("gnu" . "http://elpa.gnu.org/packages/"))
217 "An alist of archives from which to fetch.
218 The default value points to the GNU Emacs package repository.
219
220 Each element has the form (ID . LOCATION).
221 ID is an archive name, as a string.
222 LOCATION specifies the base location for the archive.
223 If it starts with \"http:\", it is treated as a HTTP URL;
224 otherwise it should be an absolute directory name.
225 (Other types of URL are currently not supported.)
226
227 Only add locations that you trust, since fetching and installing
228 a package can run arbitrary code."
229 :type '(alist :key-type (string :tag "Archive name")
230 :value-type (string :tag "URL or directory name"))
231 :risky t
232 :group 'package
233 :version "24.1")
234
235 (defcustom package-pinned-packages nil
236 "An alist of packages that are pinned to a specific archive
237
238 Each element has the form (SYM . ID).
239 SYM is a package, as a symbol.
240 ID is an archive name. This should correspond to an
241 entry in `package-archives'.
242
243 If the archive of name ID does not contain the package SYM, no
244 other location will be considered, which will make the
245 package unavailable."
246 :type '(alist :key-type (symbol :tag "Package")
247 :value-type (string :tag "Archive name"))
248 :risky t
249 :group 'package
250 :version "24.4")
251
252 (defconst package-archive-version 1
253 "Version number of the package archive understood by this file.
254 Lower version numbers than this will probably be understood as well.")
255
256 ;; We don't prime the cache since it tends to get out of date.
257 (defvar package-archive-contents nil
258 "Cache of the contents of the Emacs Lisp Package Archive.
259 This is an alist mapping package names (symbols) to
260 non-empty lists of `package-desc' structures.")
261 (put 'package-archive-contents 'risky-local-variable t)
262
263 (defcustom package-user-dir (locate-user-emacs-file "elpa")
264 "Directory containing the user's Emacs Lisp packages.
265 The directory name should be absolute.
266 Apart from this directory, Emacs also looks for system-wide
267 packages in `package-directory-list'."
268 :type 'directory
269 :risky t
270 :group 'package
271 :version "24.1")
272
273 (defcustom package-directory-list
274 ;; Defaults are subdirs named "elpa" in the site-lisp dirs.
275 (let (result)
276 (dolist (f load-path)
277 (and (stringp f)
278 (equal (file-name-nondirectory f) "site-lisp")
279 (push (expand-file-name "elpa" f) result)))
280 (nreverse result))
281 "List of additional directories containing Emacs Lisp packages.
282 Each directory name should be absolute.
283
284 These directories contain packages intended for system-wide; in
285 contrast, `package-user-dir' contains packages for personal use."
286 :type '(repeat directory)
287 :risky t
288 :group 'package
289 :version "24.1")
290
291 (defcustom package-check-signature 'allow-unsigned
292 "Whether to check package signatures when installing."
293 :type '(choice (const nil :tag "Never")
294 (const allow-unsigned :tag "Allow unsigned")
295 (const t :tag "Check always"))
296 :risky t
297 :group 'package
298 :version "24.1")
299
300 (defcustom package-unsigned-archives nil
301 "A list of archives which do not use package signature."
302 :type '(repeat (string :tag "Archive name"))
303 :risky t
304 :group 'package
305 :version "24.1")
306
307 (defvar package--default-summary "No description available.")
308
309 (cl-defstruct (package-desc
310 ;; Rename the default constructor from `make-package-desc'.
311 (:constructor package-desc-create)
312 ;; Has the same interface as the old `define-package',
313 ;; which is still used in the "foo-pkg.el" files. Extra
314 ;; options can be supported by adding additional keys.
315 (:constructor
316 package-desc-from-define
317 (name-string version-string &optional summary requirements
318 &rest rest-plist
319 &aux
320 (name (intern name-string))
321 (version (version-to-list version-string))
322 (reqs (mapcar #'(lambda (elt)
323 (list (car elt)
324 (version-to-list (cadr elt))))
325 (if (eq 'quote (car requirements))
326 (nth 1 requirements)
327 requirements)))
328 (kind (plist-get rest-plist :kind))
329 (archive (plist-get rest-plist :archive))
330 (extras (let (alist)
331 (while rest-plist
332 (unless (memq (car rest-plist) '(:kind :archive))
333 (let ((value (cadr rest-plist)))
334 (when value
335 (push (cons (car rest-plist) value)
336 alist))))
337 (setq rest-plist (cddr rest-plist)))
338 alist)))))
339 "Structure containing information about an individual package.
340 Slots:
341
342 `name' Name of the package, as a symbol.
343
344 `version' Version of the package, as a version list.
345
346 `summary' Short description of the package, typically taken from
347 the first line of the file.
348
349 `reqs' Requirements of the package. A list of (PACKAGE
350 VERSION-LIST) naming the dependent package and the minimum
351 required version.
352
353 `kind' The distribution format of the package. Currently, it is
354 either `single' or `tar'.
355
356 `archive' The name of the archive (as a string) whence this
357 package came.
358
359 `dir' The directory where the package is installed (if installed),
360 `builtin' if it is built-in, or nil otherwise.
361
362 `extras' Optional alist of additional keyword-value pairs.
363
364 `signed' Flag to indicate that the package is signed by provider."
365 name
366 version
367 (summary package--default-summary)
368 reqs
369 kind
370 archive
371 dir
372 extras
373 signed)
374
375 ;; Pseudo fields.
376 (defun package-desc-full-name (pkg-desc)
377 (format "%s-%s"
378 (package-desc-name pkg-desc)
379 (package-version-join (package-desc-version pkg-desc))))
380
381 (defun package-desc-suffix (pkg-desc)
382 (pcase (package-desc-kind pkg-desc)
383 (`single ".el")
384 (`tar ".tar")
385 (kind (error "Unknown package kind: %s" kind))))
386
387 ;; Package descriptor format used in finder-inf.el and package--builtins.
388 (cl-defstruct (package--bi-desc
389 (:constructor package-make-builtin (version summary))
390 (:type vector))
391 version
392 reqs
393 summary)
394
395 (defvar package--builtins nil
396 "Alist of built-in packages.
397 The actual value is initialized by loading the library
398 `finder-inf'; this is not done until it is needed, e.g. by the
399 function `package-built-in-p'.
400
401 Each element has the form (PKG . PACKAGE-BI-DESC), where PKG is a package
402 name (a symbol) and DESC is a `package--bi-desc' structure.")
403 (put 'package--builtins 'risky-local-variable t)
404
405 (defvar package-alist nil
406 "Alist of all packages available for activation.
407 Each element has the form (PKG . DESCS), where PKG is a package
408 name (a symbol) and DESCS is a non-empty list of `package-desc' structure,
409 sorted by decreasing versions.
410
411 This variable is set automatically by `package-load-descriptor',
412 called via `package-initialize'. To change which packages are
413 loaded and/or activated, customize `package-load-list'.")
414 (put 'package-alist 'risky-local-variable t)
415
416 (defvar package-activated-list nil
417 ;; FIXME: This should implicitly include all builtin packages.
418 "List of the names of currently activated packages.")
419 (put 'package-activated-list 'risky-local-variable t)
420
421 (defun package-version-join (vlist)
422 "Return the version string corresponding to the list VLIST.
423 This is, approximately, the inverse of `version-to-list'.
424 \(Actually, it returns only one of the possible inverses, since
425 `version-to-list' is a many-to-one operation.)"
426 (if (null vlist)
427 ""
428 (let ((str-list (list "." (int-to-string (car vlist)))))
429 (dolist (num (cdr vlist))
430 (cond
431 ((>= num 0)
432 (push (int-to-string num) str-list)
433 (push "." str-list))
434 ((< num -4)
435 (error "Invalid version list `%s'" vlist))
436 (t
437 ;; pre, or beta, or alpha
438 (cond ((equal "." (car str-list))
439 (pop str-list))
440 ((not (string-match "[0-9]+" (car str-list)))
441 (error "Invalid version list `%s'" vlist)))
442 (push (cond ((= num -1) "pre")
443 ((= num -2) "beta")
444 ((= num -3) "alpha")
445 ((= num -4) "snapshot"))
446 str-list))))
447 (if (equal "." (car str-list))
448 (pop str-list))
449 (apply 'concat (nreverse str-list)))))
450
451 (defun package-load-descriptor (pkg-dir)
452 "Load the description file in directory PKG-DIR."
453 (let ((pkg-file (expand-file-name (package--description-file pkg-dir)
454 pkg-dir))
455 (signed-file (concat pkg-dir ".signed")))
456 (when (file-exists-p pkg-file)
457 (with-temp-buffer
458 (insert-file-contents pkg-file)
459 (goto-char (point-min))
460 (let ((pkg-desc (package-process-define-package
461 (read (current-buffer)) pkg-file)))
462 (setf (package-desc-dir pkg-desc) pkg-dir)
463 (if (file-exists-p signed-file)
464 (setf (package-desc-signed pkg-desc) t))
465 pkg-desc)))))
466
467 (defun package-load-all-descriptors ()
468 "Load descriptors for installed Emacs Lisp packages.
469 This looks for package subdirectories in `package-user-dir' and
470 `package-directory-list'. The variable `package-load-list'
471 controls which package subdirectories may be loaded.
472
473 In each valid package subdirectory, this function loads the
474 description file containing a call to `define-package', which
475 updates `package-alist'."
476 (dolist (dir (cons package-user-dir package-directory-list))
477 (when (file-directory-p dir)
478 (dolist (subdir (directory-files dir))
479 (let ((pkg-dir (expand-file-name subdir dir)))
480 (when (file-directory-p pkg-dir)
481 (package-load-descriptor pkg-dir)))))))
482
483 (defun package-disabled-p (pkg-name version)
484 "Return whether PKG-NAME at VERSION can be activated.
485 The decision is made according to `package-load-list'.
486 Return nil if the package can be activated.
487 Return t if the package is completely disabled.
488 Return the max version (as a string) if the package is held at a lower version."
489 (let ((force (assq pkg-name package-load-list)))
490 (cond ((null force) (not (memq 'all package-load-list)))
491 ((null (setq force (cadr force))) t) ; disabled
492 ((eq force t) nil)
493 ((stringp force) ; held
494 (unless (version-list-= version (version-to-list force))
495 force))
496 (t (error "Invalid element in `package-load-list'")))))
497
498 (defun package-activate-1 (pkg-desc)
499 (let* ((name (package-desc-name pkg-desc))
500 (pkg-dir (package-desc-dir pkg-desc))
501 (pkg-dir-dir (file-name-as-directory pkg-dir)))
502 (unless pkg-dir
503 (error "Internal error: unable to find directory for `%s'"
504 (package-desc-full-name pkg-desc)))
505 ;; Add to load path, add autoloads, and activate the package.
506 (let ((old-lp load-path))
507 (with-demoted-errors
508 (load (expand-file-name (format "%s-autoloads" name) pkg-dir) nil t))
509 (when (and (eq old-lp load-path)
510 (not (or (member pkg-dir load-path)
511 (member pkg-dir-dir load-path))))
512 ;; Old packages don't add themselves to the `load-path', so we have to
513 ;; do it ourselves.
514 (push pkg-dir load-path)))
515 ;; Add info node.
516 (when (file-exists-p (expand-file-name "dir" pkg-dir))
517 ;; FIXME: not the friendliest, but simple.
518 (require 'info)
519 (info-initialize)
520 (push pkg-dir Info-directory-list))
521 (push name package-activated-list)
522 ;; Don't return nil.
523 t))
524
525 (defun package-built-in-p (package &optional min-version)
526 "Return true if PACKAGE is built-in to Emacs.
527 Optional arg MIN-VERSION, if non-nil, should be a version list
528 specifying the minimum acceptable version."
529 (if (package-desc-p package) ;; was built-in and then was converted
530 (eq 'builtin (package-desc-dir package))
531 (let ((bi (assq package package--builtin-versions)))
532 (cond
533 (bi (version-list-<= min-version (cdr bi)))
534 (min-version nil)
535 (t
536 (require 'finder-inf nil t) ; For `package--builtins'.
537 (assq package package--builtins))))))
538
539 (defun package--from-builtin (bi-desc)
540 (package-desc-create :name (pop bi-desc)
541 :version (package--bi-desc-version bi-desc)
542 :summary (package--bi-desc-summary bi-desc)
543 :dir 'builtin))
544
545 ;; This function goes ahead and activates a newer version of a package
546 ;; if an older one was already activated. This is not ideal; we'd at
547 ;; least need to check to see if the package has actually been loaded,
548 ;; and not merely activated.
549 (defun package-activate (package &optional force)
550 "Activate package PACKAGE.
551 If FORCE is true, (re-)activate it if it's already activated."
552 (let ((pkg-descs (cdr (assq package package-alist))))
553 ;; Check if PACKAGE is available in `package-alist'.
554 (while
555 (when pkg-descs
556 (let ((available-version (package-desc-version (car pkg-descs))))
557 (or (package-disabled-p package available-version)
558 ;; Prefer a builtin package.
559 (package-built-in-p package available-version))))
560 (setq pkg-descs (cdr pkg-descs)))
561 (cond
562 ;; If no such package is found, maybe it's built-in.
563 ((null pkg-descs)
564 (package-built-in-p package))
565 ;; If the package is already activated, just return t.
566 ((and (memq package package-activated-list) (not force))
567 t)
568 ;; Otherwise, proceed with activation.
569 (t
570 (let* ((pkg-vec (car pkg-descs))
571 (fail (catch 'dep-failure
572 ;; Activate its dependencies recursively.
573 (dolist (req (package-desc-reqs pkg-vec))
574 (unless (package-activate (car req) (cadr req))
575 (throw 'dep-failure req))))))
576 (if fail
577 (warn "Unable to activate package `%s'.
578 Required package `%s-%s' is unavailable"
579 package (car fail) (package-version-join (cadr fail)))
580 ;; If all goes well, activate the package itself.
581 (package-activate-1 pkg-vec)))))))
582
583 (defun define-package (_name-string _version-string
584 &optional _docstring _requirements
585 &rest _extra-properties)
586 "Define a new package.
587 NAME-STRING is the name of the package, as a string.
588 VERSION-STRING is the version of the package, as a string.
589 DOCSTRING is a short description of the package, a string.
590 REQUIREMENTS is a list of dependencies on other packages.
591 Each requirement is of the form (OTHER-PACKAGE OTHER-VERSION),
592 where OTHER-VERSION is a string.
593
594 EXTRA-PROPERTIES is currently unused."
595 ;; FIXME: Placeholder! Should we keep it?
596 (error "Don't call me!"))
597
598 (defun package-process-define-package (exp origin)
599 (unless (eq (car-safe exp) 'define-package)
600 (error "Can't find define-package in %s" origin))
601 (let* ((new-pkg-desc (apply #'package-desc-from-define (cdr exp)))
602 (name (package-desc-name new-pkg-desc))
603 (version (package-desc-version new-pkg-desc))
604 (old-pkgs (assq name package-alist)))
605 (if (null old-pkgs)
606 ;; If there's no old package, just add this to `package-alist'.
607 (push (list name new-pkg-desc) package-alist)
608 ;; If there is, insert the new package at the right place in the list.
609 (while
610 (if (and (cdr old-pkgs)
611 (version-list-< version
612 (package-desc-version (cadr old-pkgs))))
613 (setq old-pkgs (cdr old-pkgs))
614 (push new-pkg-desc (cdr old-pkgs))
615 nil)))
616 new-pkg-desc))
617
618 ;; From Emacs 22, but changed so it adds to load-path.
619 (defun package-autoload-ensure-default-file (file)
620 "Make sure that the autoload file FILE exists and if not create it."
621 (unless (file-exists-p file)
622 (write-region
623 (concat ";;; " (file-name-nondirectory file)
624 " --- automatically extracted autoloads\n"
625 ";;\n"
626 ";;; Code:\n"
627 "(add-to-list 'load-path (or (file-name-directory #$) (car load-path)))\n"
628 "\f\n;; Local Variables:\n"
629 ";; version-control: never\n"
630 ";; no-byte-compile: t\n"
631 ";; no-update-autoloads: t\n"
632 ";; End:\n"
633 ";;; " (file-name-nondirectory file)
634 " ends here\n")
635 nil file))
636 file)
637
638 (defvar generated-autoload-file)
639 (defvar version-control)
640
641 (defun package-generate-autoloads (name pkg-dir)
642 (let* ((auto-name (format "%s-autoloads.el" name))
643 ;;(ignore-name (concat name "-pkg.el"))
644 (generated-autoload-file (expand-file-name auto-name pkg-dir))
645 (version-control 'never))
646 (package-autoload-ensure-default-file generated-autoload-file)
647 (update-directory-autoloads pkg-dir)
648 (let ((buf (find-buffer-visiting generated-autoload-file)))
649 (when buf (kill-buffer buf)))
650 auto-name))
651
652 (defvar tar-parse-info)
653 (declare-function tar-untar-buffer "tar-mode" ())
654 (declare-function tar-header-name "tar-mode" (tar-header) t)
655 (declare-function tar-header-link-type "tar-mode" (tar-header) t)
656
657 (defun package-untar-buffer (dir)
658 "Untar the current buffer.
659 This uses `tar-untar-buffer' from Tar mode. All files should
660 untar into a directory named DIR; otherwise, signal an error."
661 (require 'tar-mode)
662 (tar-mode)
663 ;; Make sure everything extracts into DIR.
664 (let ((regexp (concat "\\`" (regexp-quote (expand-file-name dir)) "/"))
665 (case-fold-search (memq system-type '(windows-nt ms-dos cygwin))))
666 (dolist (tar-data tar-parse-info)
667 (let ((name (expand-file-name (tar-header-name tar-data))))
668 (or (string-match regexp name)
669 ;; Tarballs created by some utilities don't list
670 ;; directories with a trailing slash (Bug#13136).
671 (and (string-equal dir name)
672 (eq (tar-header-link-type tar-data) 5))
673 (error "Package does not untar cleanly into directory %s/" dir)))))
674 (tar-untar-buffer))
675
676 (defun package-generate-description-file (pkg-desc pkg-dir)
677 "Create the foo-pkg.el file for single-file packages."
678 (let* ((name (package-desc-name pkg-desc))
679 (pkg-file (expand-file-name (package--description-file pkg-dir)
680 pkg-dir)))
681 (let ((print-level nil)
682 (print-quoted t)
683 (print-length nil))
684 (write-region
685 (concat
686 (prin1-to-string
687 (nconc
688 (list 'define-package
689 (symbol-name name)
690 (package-version-join (package-desc-version pkg-desc))
691 (package-desc-summary pkg-desc)
692 (let ((requires (package-desc-reqs pkg-desc)))
693 (list 'quote
694 ;; Turn version lists into string form.
695 (mapcar
696 (lambda (elt)
697 (list (car elt)
698 (package-version-join (cadr elt))))
699 requires))))
700 (package--alist-to-plist
701 (package-desc-extras pkg-desc))))
702 "\n")
703 nil
704 pkg-file))))
705
706 (defun package--alist-to-plist (alist)
707 (apply #'nconc (mapcar (lambda (pair) (list (car pair) (cdr pair))) alist)))
708
709 (defun package-unpack (pkg-desc)
710 "Install the contents of the current buffer as a package."
711 (let* ((name (package-desc-name pkg-desc))
712 (dirname (package-desc-full-name pkg-desc))
713 (pkg-dir (expand-file-name dirname package-user-dir)))
714 (pcase (package-desc-kind pkg-desc)
715 (`tar
716 (make-directory package-user-dir t)
717 ;; FIXME: should we delete PKG-DIR if it exists?
718 (let* ((default-directory (file-name-as-directory package-user-dir)))
719 (package-untar-buffer dirname)))
720 (`single
721 (let ((el-file (expand-file-name (format "%s.el" name) pkg-dir)))
722 (make-directory pkg-dir t)
723 (package--write-file-no-coding el-file)))
724 (kind (error "Unknown package kind: %S" kind)))
725 (package--make-autoloads-and-stuff pkg-desc pkg-dir)
726 ;; Update package-alist.
727 (let ((new-desc (package-load-descriptor pkg-dir)))
728 ;; FIXME: Check that `new-desc' matches `desc'!
729 ;; FIXME: Compilation should be done as a separate, optional, step.
730 ;; E.g. for multi-package installs, we should first install all packages
731 ;; and then compile them.
732 (package--compile new-desc))
733 ;; Try to activate it.
734 (package-activate name 'force)
735 pkg-dir))
736
737 (defun package--make-autoloads-and-stuff (pkg-desc pkg-dir)
738 "Generate autoloads, description file, etc.. for PKG-DESC installed at PKG-DIR."
739 (package-generate-autoloads (package-desc-name pkg-desc) pkg-dir)
740 (let ((desc-file (package--description-file pkg-dir)))
741 (unless (file-exists-p desc-file)
742 (package-generate-description-file pkg-desc pkg-dir)))
743 ;; FIXME: Create foo.info and dir file from foo.texi?
744 )
745
746 (defun package--compile (pkg-desc)
747 "Byte-compile installed package PKG-DESC."
748 (package-activate-1 pkg-desc)
749 (byte-recompile-directory (package-desc-dir pkg-desc) 0 t))
750
751 (defun package--write-file-no-coding (file-name)
752 (let ((buffer-file-coding-system 'no-conversion))
753 (write-region (point-min) (point-max) file-name)))
754
755 (defmacro package--with-work-buffer (location file &rest body)
756 "Run BODY in a buffer containing the contents of FILE at LOCATION.
757 LOCATION is the base location of a package archive, and should be
758 one of the URLs (or file names) specified in `package-archives'.
759 FILE is the name of a file relative to that base location.
760
761 This macro retrieves FILE from LOCATION into a temporary buffer,
762 and evaluates BODY while that buffer is current. This work
763 buffer is killed afterwards. Return the last value in BODY."
764 (declare (indent 2) (debug t))
765 `(let* ((http (string-match "\\`https?:" ,location))
766 (buffer
767 (if http
768 (url-retrieve-synchronously (concat ,location ,file))
769 (generate-new-buffer "*package work buffer*"))))
770 (prog1
771 (with-current-buffer buffer
772 (if http
773 (progn (package-handle-response)
774 (re-search-forward "^$" nil 'move)
775 (forward-char)
776 (delete-region (point-min) (point)))
777 (unless (file-name-absolute-p ,location)
778 (error "Archive location %s is not an absolute file name"
779 ,location))
780 (insert-file-contents (expand-file-name ,file ,location)))
781 ,@body)
782 (kill-buffer buffer))))
783
784 (defun package-handle-response ()
785 "Handle the response from a `url-retrieve-synchronously' call.
786 Parse the HTTP response and throw if an error occurred.
787 The url package seems to require extra processing for this.
788 This should be called in a `save-excursion', in the download buffer.
789 It will move point to somewhere in the headers."
790 ;; We assume HTTP here.
791 (require 'url-http)
792 (let ((response (url-http-parse-response)))
793 (when (or (< response 200) (>= response 300))
794 (error "Error downloading %s:%s"
795 (url-recreate-url url-http-target-url)
796 (buffer-substring-no-properties (point) (line-end-position))))))
797
798 (defun package--archive-file-exists-p (location file)
799 (let ((http (string-match "\\`https?:" location)))
800 (if http
801 (progn
802 (require 'url-http)
803 (url-http-file-exists-p (concat location file)))
804 (file-exists-p (expand-file-name file location)))))
805
806 (declare-function epg-make-context "epg"
807 (&optional protocol armor textmode include-certs
808 cipher-algorithm
809 digest-algorithm
810 compress-algorithm))
811 (declare-function epg-context-set-home-directory "epg" (context directory))
812 (declare-function epg-verify-string "epg" (context signature
813 &optional signed-text))
814 (declare-function epg-context-result-for "epg" (context name))
815 (declare-function epg-signature-status "epg" (signature))
816 (declare-function epg-signature-to-string "epg" (signature))
817
818 (defun package--check-signature (location file)
819 "Check signature of the current buffer.
820 GnuPG keyring is located under \"gnupg\" in `package-user-dir'."
821 (let ((context (epg-make-context 'OpenPGP))
822 (homedir (expand-file-name "gnupg" package-user-dir))
823 (sig-file (concat file ".sig"))
824 sig-content
825 good-signatures)
826 (setq sig-content (package--with-work-buffer location sig-file
827 (buffer-string)))
828 (epg-context-set-home-directory context homedir)
829 (epg-verify-string context sig-content (buffer-string))
830 ;; The .sig file may contain multiple signatures. Success if one
831 ;; of the signatures is good.
832 (setq good-signatures
833 (delq nil (mapcar (lambda (sig)
834 (if (eq (epg-signature-status sig) 'good)
835 sig))
836 (epg-context-result-for context 'verify))))
837 (if (null good-signatures)
838 (error "Failed to verify signature %s: %S"
839 sig-file
840 (mapcar #'epg-signature-to-string
841 (epg-context-result-for context 'verify)))
842 good-signatures)))
843
844 (defun package-install-from-archive (pkg-desc)
845 "Download and install a tar package."
846 (let* ((location (package-archive-base pkg-desc))
847 (file (concat (package-desc-full-name pkg-desc)
848 (package-desc-suffix pkg-desc)))
849 (sig-file (concat file ".sig"))
850 good-signatures pkg-descs)
851 (package--with-work-buffer location file
852 (if (and package-check-signature
853 (not (member (package-desc-archive pkg-desc)
854 package-unsigned-archives)))
855 (if (package--archive-file-exists-p location sig-file)
856 (setq good-signatures (package--check-signature location file))
857 (unless (eq package-check-signature 'allow-unsigned)
858 (error "Unsigned package: `%s'"
859 (package-desc-name pkg-desc)))))
860 (package-unpack pkg-desc))
861 ;; Here the package has been installed successfully, mark it as
862 ;; signed if appropriate.
863 (when good-signatures
864 ;; Write out good signatures into NAME-VERSION.signed file.
865 (write-region (mapconcat #'epg-signature-to-string good-signatures "\n")
866 nil
867 (expand-file-name
868 (concat (package-desc-full-name pkg-desc)
869 ".signed")
870 package-user-dir))
871 ;; Update the old pkg-desc which will be shown on the description buffer.
872 (setf (package-desc-signed pkg-desc) t)
873 ;; Update the new (activated) pkg-desc as well.
874 (setq pkg-descs (cdr (assq (package-desc-name pkg-desc) package-alist)))
875 (if pkg-descs
876 (setf (package-desc-signed (car pkg-descs)) t)))))
877
878 (defvar package--initialized nil)
879
880 (defun package-installed-p (package &optional min-version)
881 "Return true if PACKAGE, of MIN-VERSION or newer, is installed.
882 MIN-VERSION should be a version list."
883 (unless package--initialized (error "package.el is not yet initialized!"))
884 (when (assq package package-alist)
885 (or
886 (let ((pkg-descs (cdr (assq package package-alist))))
887 (and pkg-descs
888 (version-list-<= min-version
889 (package-desc-version (car pkg-descs)))))
890 ;; Also check built-in packages.
891 (package-built-in-p package min-version))))
892
893 (defun package-compute-transaction (packages requirements)
894 "Return a list of packages to be installed, including PACKAGES.
895 PACKAGES should be a list of `package-desc'.
896
897 REQUIREMENTS should be a list of additional requirements; each
898 element in this list should have the form (PACKAGE VERSION-LIST),
899 where PACKAGE is a package name and VERSION-LIST is the required
900 version of that package.
901
902 This function recursively computes the requirements of the
903 packages in REQUIREMENTS, and returns a list of all the packages
904 that must be installed. Packages that are already installed are
905 not included in this list."
906 ;; FIXME: We really should use backtracking to explore the whole
907 ;; search space (e.g. if foo require bar-1.3, and bar-1.4 requires toto-1.1
908 ;; whereas bar-1.3 requires toto-1.0 and the user has put a hold on toto-1.0:
909 ;; the current code might fail to see that it could install foo by using the
910 ;; older bar-1.3).
911 (dolist (elt requirements)
912 (let* ((next-pkg (car elt))
913 (next-version (cadr elt))
914 (already ()))
915 (dolist (pkg packages)
916 (if (eq next-pkg (package-desc-name pkg))
917 (setq already pkg)))
918 (cond
919 (already
920 (if (version-list-< next-version (package-desc-version already))
921 ;; Move to front, so it gets installed early enough (bug#14082).
922 (setq packages (cons already (delq already packages)))
923 (error "Need package `%s-%s', but only %s is available"
924 next-pkg (package-version-join next-version)
925 (package-version-join (package-desc-version already)))))
926
927 ((package-installed-p next-pkg next-version) nil)
928
929 (t
930 ;; A package is required, but not installed. It might also be
931 ;; blocked via `package-load-list'.
932 (let ((pkg-descs (cdr (assq next-pkg package-archive-contents)))
933 (found nil)
934 (problem nil))
935 (while (and pkg-descs (not found))
936 (let* ((pkg-desc (pop pkg-descs))
937 (version (package-desc-version pkg-desc))
938 (disabled (package-disabled-p next-pkg version)))
939 (cond
940 ((version-list-< version next-version)
941 (error
942 "Need package `%s-%s', but only %s is available"
943 next-pkg (package-version-join next-version)
944 (package-version-join version)))
945 (disabled
946 (unless problem
947 (setq problem
948 (if (stringp disabled)
949 (format "Package `%s' held at version %s, \
950 but version %s required"
951 next-pkg disabled
952 (package-version-join next-version))
953 (format "Required package '%s' is disabled"
954 next-pkg)))))
955 (t (setq found pkg-desc)))))
956 (unless found
957 (if problem
958 (error problem)
959 (error "Package `%s-%s' is unavailable"
960 next-pkg (package-version-join next-version))))
961 (setq packages
962 (package-compute-transaction (cons found packages)
963 (package-desc-reqs found))))))))
964 packages)
965
966 (defun package-read-from-string (str)
967 "Read a Lisp expression from STR.
968 Signal an error if the entire string was not used."
969 (let* ((read-data (read-from-string str))
970 (more-left
971 (condition-case nil
972 ;; The call to `ignore' suppresses a compiler warning.
973 (progn (ignore (read-from-string
974 (substring str (cdr read-data))))
975 t)
976 (end-of-file nil))))
977 (if more-left
978 (error "Can't read whole string")
979 (car read-data))))
980
981 (defun package--read-archive-file (file)
982 "Re-read archive file FILE, if it exists.
983 Will return the data from the file, or nil if the file does not exist.
984 Will throw an error if the archive version is too new."
985 (let ((filename (expand-file-name file package-user-dir)))
986 (when (file-exists-p filename)
987 (with-temp-buffer
988 (insert-file-contents-literally filename)
989 (let ((contents (read (current-buffer))))
990 (if (> (car contents) package-archive-version)
991 (error "Package archive version %d is higher than %d"
992 (car contents) package-archive-version))
993 (cdr contents))))))
994
995 (defun package-read-all-archive-contents ()
996 "Re-read `archive-contents', if it exists.
997 If successful, set `package-archive-contents'."
998 (setq package-archive-contents nil)
999 (dolist (archive package-archives)
1000 (package-read-archive-contents (car archive))))
1001
1002 (defun package-read-archive-contents (archive)
1003 "Re-read archive contents for ARCHIVE.
1004 If successful, set the variable `package-archive-contents'.
1005 If the archive version is too new, signal an error."
1006 ;; Version 1 of 'archive-contents' is identical to our internal
1007 ;; representation.
1008 (let* ((contents-file (format "archives/%s/archive-contents" archive))
1009 (contents (package--read-archive-file contents-file)))
1010 (when contents
1011 (dolist (package contents)
1012 (package--add-to-archive-contents package archive)))))
1013
1014 ;; Package descriptor objects used inside the "archive-contents" file.
1015 ;; Changing this defstruct implies changing the format of the
1016 ;; "archive-contents" files.
1017 (cl-defstruct (package--ac-desc
1018 (:constructor package-make-ac-desc (version reqs summary kind extras))
1019 (:copier nil)
1020 (:type vector))
1021 version reqs summary kind extras)
1022
1023 (defun package--add-to-archive-contents (package archive)
1024 "Add the PACKAGE from the given ARCHIVE if necessary.
1025 PACKAGE should have the form (NAME . PACKAGE--AC-DESC).
1026 Also, add the originating archive to the `package-desc' structure."
1027 (let* ((name (car package))
1028 (version (package--ac-desc-version (cdr package)))
1029 (pkg-desc
1030 (package-desc-create
1031 :name name
1032 :version version
1033 :reqs (package--ac-desc-reqs (cdr package))
1034 :summary (package--ac-desc-summary (cdr package))
1035 :kind (package--ac-desc-kind (cdr package))
1036 :archive archive
1037 :extras (and (> (length (cdr package)) 4)
1038 ;; Older archive-contents files have only 4
1039 ;; elements here.
1040 (package--ac-desc-extras (cdr package)))))
1041 (existing-packages (assq name package-archive-contents))
1042 (pinned-to-archive (assoc name package-pinned-packages)))
1043 (cond
1044 ;; Skip entirely if pinned to another archive or already installed.
1045 ((or (and pinned-to-archive
1046 (not (equal (cdr pinned-to-archive) archive)))
1047 (let ((bi (assq name package--builtin-versions)))
1048 (and bi (version-list-= version (cdr bi))))
1049 (let ((ins (cdr (assq name package-alist))))
1050 (and ins (version-list-= version
1051 (package-desc-version (car ins))))))
1052 nil)
1053 ((not existing-packages)
1054 (push (list name pkg-desc) package-archive-contents))
1055 (t
1056 (while
1057 (if (and (cdr existing-packages)
1058 (version-list-<
1059 version (package-desc-version (cadr existing-packages))))
1060 (setq existing-packages (cdr existing-packages))
1061 (push pkg-desc (cdr existing-packages))
1062 nil))))))
1063
1064 (defun package-download-transaction (packages)
1065 "Download and install all the packages in PACKAGES.
1066 PACKAGES should be a list of package-desc.
1067 This function assumes that all package requirements in
1068 PACKAGES are satisfied, i.e. that PACKAGES is computed
1069 using `package-compute-transaction'."
1070 (mapc #'package-install-from-archive packages))
1071
1072 ;;;###autoload
1073 (defun package-install (pkg)
1074 "Install the package PKG.
1075 PKG can be a package-desc or the package name of one the available packages
1076 in an archive in `package-archives'. Interactively, prompt for its name."
1077 (interactive
1078 (progn
1079 ;; Initialize the package system to get the list of package
1080 ;; symbols for completion.
1081 (unless package--initialized
1082 (package-initialize t))
1083 (unless package-archive-contents
1084 (package-refresh-contents))
1085 (list (intern (completing-read
1086 "Install package: "
1087 (mapcar (lambda (elt) (symbol-name (car elt)))
1088 package-archive-contents)
1089 nil t)))))
1090 (package-download-transaction
1091 (if (package-desc-p pkg)
1092 (package-compute-transaction (list pkg)
1093 (package-desc-reqs pkg))
1094 (package-compute-transaction ()
1095 (list (list pkg))))))
1096
1097 (defun package-strip-rcs-id (str)
1098 "Strip RCS version ID from the version string STR.
1099 If the result looks like a dotted numeric version, return it.
1100 Otherwise return nil."
1101 (when str
1102 (when (string-match "\\`[ \t]*[$]Revision:[ \t]+" str)
1103 (setq str (substring str (match-end 0))))
1104 (condition-case nil
1105 (if (version-to-list str)
1106 str)
1107 (error nil))))
1108
1109 (declare-function lm-homepage "lisp-mnt" (&optional file))
1110
1111 (defun package--prepare-dependencies (deps)
1112 "Turn DEPS into an acceptable list of dependencies.
1113
1114 Any parts missing a version string get a default version string
1115 of \"0\" (meaning any version) and an appropriate level of lists
1116 is wrapped around any parts requiring it."
1117 (cond
1118 ((not (listp deps))
1119 (error "Invalid requirement specifier: %S" deps))
1120 (t (mapcar (lambda (dep)
1121 (cond
1122 ((symbolp dep) `(,dep "0"))
1123 ((stringp dep)
1124 (error "Invalid requirement specifier: %S" dep))
1125 (t dep)))
1126 deps))))
1127
1128 (defun package-buffer-info ()
1129 "Return a `package-desc' describing the package in the current buffer.
1130
1131 If the buffer does not contain a conforming package, signal an
1132 error. If there is a package, narrow the buffer to the file's
1133 boundaries."
1134 (goto-char (point-min))
1135 (unless (re-search-forward "^;;; \\([^ ]*\\)\\.el ---[ \t]*\\(.*?\\)[ \t]*\\(-\\*-.*-\\*-[ \t]*\\)?$" nil t)
1136 (error "Package lacks a file header"))
1137 (let ((file-name (match-string-no-properties 1))
1138 (desc (match-string-no-properties 2))
1139 (start (line-beginning-position)))
1140 (unless (search-forward (concat ";;; " file-name ".el ends here"))
1141 (error "Package lacks a terminating comment"))
1142 ;; Try to include a trailing newline.
1143 (forward-line)
1144 (narrow-to-region start (point))
1145 (require 'lisp-mnt)
1146 ;; Use some headers we've invented to drive the process.
1147 (let* ((requires-str (lm-header "package-requires"))
1148 ;; Prefer Package-Version; if defined, the package author
1149 ;; probably wants us to use it. Otherwise try Version.
1150 (pkg-version
1151 (or (package-strip-rcs-id (lm-header "package-version"))
1152 (package-strip-rcs-id (lm-header "version"))))
1153 (homepage (lm-homepage)))
1154 (unless pkg-version
1155 (error
1156 "Package lacks a \"Version\" or \"Package-Version\" header"))
1157 (package-desc-from-define
1158 file-name pkg-version desc
1159 (if requires-str
1160 (package--prepare-dependencies
1161 (package-read-from-string requires-str)))
1162 :kind 'single
1163 :url homepage))))
1164
1165 (declare-function tar-get-file-descriptor "tar-mode" (file))
1166 (declare-function tar--extract "tar-mode" (descriptor))
1167
1168 (defun package-tar-file-info ()
1169 "Find package information for a tar file.
1170 The return result is a `package-desc'."
1171 (cl-assert (derived-mode-p 'tar-mode))
1172 (let* ((dir-name (file-name-directory
1173 (tar-header-name (car tar-parse-info))))
1174 (desc-file (package--description-file dir-name))
1175 (tar-desc (tar-get-file-descriptor (concat dir-name desc-file))))
1176 (unless tar-desc
1177 (error "No package descriptor file found"))
1178 (with-current-buffer (tar--extract tar-desc)
1179 (goto-char (point-min))
1180 (unwind-protect
1181 (let* ((pkg-def-parsed (read (current-buffer)))
1182 (pkg-desc
1183 (if (not (eq (car pkg-def-parsed) 'define-package))
1184 (error "Can't find define-package in %s"
1185 (tar-header-name tar-desc))
1186 (apply #'package-desc-from-define
1187 (append (cdr pkg-def-parsed))))))
1188 (setf (package-desc-kind pkg-desc) 'tar)
1189 pkg-desc)
1190 (kill-buffer (current-buffer))))))
1191
1192
1193 ;;;###autoload
1194 (defun package-install-from-buffer ()
1195 "Install a package from the current buffer.
1196 The current buffer is assumed to be a single .el or .tar file that follows the
1197 packaging guidelines; see info node `(elisp)Packaging'.
1198 Downloads and installs required packages as needed."
1199 (interactive)
1200 (let ((pkg-desc (if (derived-mode-p 'tar-mode)
1201 (package-tar-file-info)
1202 (package-buffer-info))))
1203 ;; Download and install the dependencies.
1204 (let* ((requires (package-desc-reqs pkg-desc))
1205 (transaction (package-compute-transaction nil requires)))
1206 (package-download-transaction transaction))
1207 ;; Install the package itself.
1208 (package-unpack pkg-desc)
1209 pkg-desc))
1210
1211 ;;;###autoload
1212 (defun package-install-file (file)
1213 "Install a package from a file.
1214 The file can either be a tar file or an Emacs Lisp file."
1215 (interactive "fPackage file name: ")
1216 (with-temp-buffer
1217 (insert-file-contents-literally file)
1218 (when (string-match "\\.tar\\'" file) (tar-mode))
1219 (package-install-from-buffer)))
1220
1221 (defun package-delete (pkg-desc)
1222 (let ((dir (package-desc-dir pkg-desc)))
1223 (if (not (string-prefix-p (file-name-as-directory
1224 (expand-file-name package-user-dir))
1225 (expand-file-name dir)))
1226 ;; Don't delete "system" packages.
1227 (error "Package `%s' is a system package, not deleting"
1228 (package-desc-full-name pkg-desc))
1229 (delete-directory dir t t)
1230 ;; Remove NAME-VERSION.signed file.
1231 (let ((signed-file (concat dir ".signed")))
1232 (if (file-exists-p signed-file)
1233 (delete-file signed-file)))
1234 ;; Update package-alist.
1235 (let* ((name (package-desc-name pkg-desc)))
1236 (setq package-alist (delete (assq name package-alist) package-alist)))
1237 (message "Package `%s' deleted." (package-desc-full-name pkg-desc)))))
1238
1239 (defun package-archive-base (desc)
1240 "Return the archive containing the package NAME."
1241 (cdr (assoc (package-desc-archive desc) package-archives)))
1242
1243 (defun package--download-one-archive (archive file)
1244 "Retrieve an archive file FILE from ARCHIVE, and cache it.
1245 ARCHIVE should be a cons cell of the form (NAME . LOCATION),
1246 similar to an entry in `package-alist'. Save the cached copy to
1247 \"archives/NAME/archive-contents\" in `package-user-dir'."
1248 (let ((dir (expand-file-name (format "archives/%s" (car archive))
1249 package-user-dir))
1250 (sig-file (concat file ".sig"))
1251 good-signatures)
1252 (package--with-work-buffer (cdr archive) file
1253 ;; Check signature of archive-contents, if desired.
1254 (if (and package-check-signature
1255 (not (member archive package-unsigned-archives)))
1256 (if (package--archive-file-exists-p (cdr archive) sig-file)
1257 (setq good-signatures (package--check-signature (cdr archive)
1258 file))
1259 (unless (eq package-check-signature 'allow-unsigned)
1260 (error "Unsigned archive `%s'"
1261 (car archive)))))
1262 ;; Read the retrieved buffer to make sure it is valid (e.g. it
1263 ;; may fetch a URL redirect page).
1264 (when (listp (read buffer))
1265 (make-directory dir t)
1266 (setq buffer-file-name (expand-file-name file dir))
1267 (let ((version-control 'never)
1268 (require-final-newline nil))
1269 (save-buffer))))
1270 (when good-signatures
1271 ;; Write out good signatures into archive-contents.signed file.
1272 (write-region (mapconcat #'epg-signature-to-string good-signatures "\n")
1273 nil
1274 (expand-file-name (concat file ".signed") dir)))))
1275
1276 (declare-function epg-check-configuration "epg-config"
1277 (config &optional minimum-version))
1278 (declare-function epg-configuration "epg-config" ())
1279 (declare-function epg-import-keys-from-file "epg" (context keys))
1280
1281 ;;;###autoload
1282 (defun package-import-keyring (&optional file)
1283 "Import keys from FILE."
1284 (interactive "fFile: ")
1285 (setq file (expand-file-name file))
1286 (let ((context (epg-make-context 'OpenPGP))
1287 (homedir (expand-file-name "gnupg" package-user-dir)))
1288 (make-directory homedir t)
1289 (epg-context-set-home-directory context homedir)
1290 (message "Importing %s..." (file-name-nondirectory file))
1291 (epg-import-keys-from-file context file)
1292 (message "Importing %s...done" (file-name-nondirectory file))))
1293
1294 ;;;###autoload
1295 (defun package-refresh-contents ()
1296 "Download the ELPA archive description if needed.
1297 This informs Emacs about the latest versions of all packages, and
1298 makes them available for download."
1299 (interactive)
1300 ;; FIXME: Do it asynchronously.
1301 (unless (file-exists-p package-user-dir)
1302 (make-directory package-user-dir t))
1303 (let ((default-keyring (expand-file-name "package-keyring.gpg"
1304 data-directory)))
1305 (if (file-exists-p default-keyring)
1306 (condition-case-unless-debug error
1307 (progn
1308 (epg-check-configuration (epg-configuration))
1309 (package-import-keyring default-keyring))
1310 (error (message "Cannot import default keyring: %S" (cdr error))))))
1311 (dolist (archive package-archives)
1312 (condition-case-unless-debug nil
1313 (package--download-one-archive archive "archive-contents")
1314 (error (message "Failed to download `%s' archive."
1315 (car archive)))))
1316 (package-read-all-archive-contents))
1317
1318 ;;;###autoload
1319 (defun package-initialize (&optional no-activate)
1320 "Load Emacs Lisp packages, and activate them.
1321 The variable `package-load-list' controls which packages to load.
1322 If optional arg NO-ACTIVATE is non-nil, don't activate packages."
1323 (interactive)
1324 (setq package-alist nil)
1325 (package-load-all-descriptors)
1326 (package-read-all-archive-contents)
1327 (unless no-activate
1328 (dolist (elt package-alist)
1329 (package-activate (car elt))))
1330 (setq package--initialized t))
1331
1332 \f
1333 ;;;; Package description buffer.
1334
1335 ;;;###autoload
1336 (defun describe-package (package)
1337 "Display the full documentation of PACKAGE (a symbol)."
1338 (interactive
1339 (let* ((guess (function-called-at-point)))
1340 (require 'finder-inf nil t)
1341 ;; Load the package list if necessary (but don't activate them).
1342 (unless package--initialized
1343 (package-initialize t))
1344 (let ((packages (append (mapcar 'car package-alist)
1345 (mapcar 'car package-archive-contents)
1346 (mapcar 'car package--builtins))))
1347 (unless (memq guess packages)
1348 (setq guess nil))
1349 (setq packages (mapcar 'symbol-name packages))
1350 (let ((val
1351 (completing-read (if guess
1352 (format "Describe package (default %s): "
1353 guess)
1354 "Describe package: ")
1355 packages nil t nil nil guess)))
1356 (list (intern val))))))
1357 (if (not (or (package-desc-p package) (and package (symbolp package))))
1358 (message "No package specified")
1359 (help-setup-xref (list #'describe-package package)
1360 (called-interactively-p 'interactive))
1361 (with-help-window (help-buffer)
1362 (with-current-buffer standard-output
1363 (describe-package-1 package)))))
1364
1365 (defun describe-package-1 (pkg)
1366 (require 'lisp-mnt)
1367 (let* ((desc (or
1368 (if (package-desc-p pkg) pkg)
1369 (cadr (assq pkg package-alist))
1370 (let ((built-in (assq pkg package--builtins)))
1371 (if built-in
1372 (package--from-builtin built-in)
1373 (cadr (assq pkg package-archive-contents))))))
1374 (name (if desc (package-desc-name desc) pkg))
1375 (pkg-dir (if desc (package-desc-dir desc)))
1376 (reqs (if desc (package-desc-reqs desc)))
1377 (version (if desc (package-desc-version desc)))
1378 (archive (if desc (package-desc-archive desc)))
1379 (extras (and desc (package-desc-extras desc)))
1380 (homepage (cdr (assoc :url extras)))
1381 (keywords (cdr (assoc :keywords extras)))
1382 (built-in (eq pkg-dir 'builtin))
1383 (installable (and archive (not built-in)))
1384 (status (if desc (package-desc-status desc) "orphan"))
1385 (signed (if desc (package-desc-signed desc))))
1386 (prin1 name)
1387 (princ " is ")
1388 (princ (if (memq (aref status 0) '(?a ?e ?i ?o ?u)) "an " "a "))
1389 (princ status)
1390 (princ " package.\n\n")
1391
1392 (insert " " (propertize "Status" 'font-lock-face 'bold) ": ")
1393 (cond (built-in
1394 (insert (propertize (capitalize status)
1395 'font-lock-face 'font-lock-builtin-face)
1396 "."))
1397 (pkg-dir
1398 (insert (propertize (if (equal status "unsigned")
1399 "Installed"
1400 (capitalize status)) ;FIXME: Why comment-face?
1401 'font-lock-face 'font-lock-comment-face))
1402 (insert " in `")
1403 ;; Todo: Add button for uninstalling.
1404 (help-insert-xref-button (abbreviate-file-name
1405 (file-name-as-directory pkg-dir))
1406 'help-package-def pkg-dir)
1407 (if (and (package-built-in-p name)
1408 (not (package-built-in-p name version)))
1409 (insert "',\n shadowing a "
1410 (propertize "built-in package"
1411 'font-lock-face 'font-lock-builtin-face))
1412 (insert "'"))
1413 (if signed
1414 (insert ".")
1415 (insert " (unsigned).")))
1416 (installable
1417 (insert (capitalize status))
1418 (insert " from " (format "%s" archive))
1419 (insert " -- ")
1420 (package-make-button
1421 "Install"
1422 'action 'package-install-button-action
1423 'package-desc desc))
1424 (t (insert (capitalize status) ".")))
1425 (insert "\n")
1426 (insert " " (propertize "Archive" 'font-lock-face 'bold)
1427 ": " (or archive "n/a") "\n")
1428 (and version
1429 (insert " "
1430 (propertize "Version" 'font-lock-face 'bold) ": "
1431 (package-version-join version) "\n"))
1432
1433 (setq reqs (if desc (package-desc-reqs desc)))
1434 (when reqs
1435 (insert " " (propertize "Requires" 'font-lock-face 'bold) ": ")
1436 (let ((first t)
1437 name vers text)
1438 (dolist (req reqs)
1439 (setq name (car req)
1440 vers (cadr req)
1441 text (format "%s-%s" (symbol-name name)
1442 (package-version-join vers)))
1443 (cond (first (setq first nil))
1444 ((>= (+ 2 (current-column) (length text))
1445 (window-width))
1446 (insert ",\n "))
1447 (t (insert ", ")))
1448 (help-insert-xref-button text 'help-package name))
1449 (insert "\n")))
1450 (insert " " (propertize "Summary" 'font-lock-face 'bold)
1451 ": " (if desc (package-desc-summary desc)) "\n")
1452 (when homepage
1453 (insert " " (propertize "Homepage" 'font-lock-face 'bold) ": ")
1454 (help-insert-xref-button homepage 'help-url homepage)
1455 (insert "\n"))
1456 (when keywords
1457 (insert " " (propertize "Keywords" 'font-lock-face 'bold) ": ")
1458 (dolist (k keywords)
1459 (package-make-button
1460 k
1461 'package-keyword k
1462 'action 'package-keyword-button-action)
1463 (insert " "))
1464 (insert "\n"))
1465 (let* ((all-pkgs (append (cdr (assq name package-alist))
1466 (cdr (assq name package-archive-contents))
1467 (let ((bi (assq name package--builtins)))
1468 (if bi (list (package--from-builtin bi))))))
1469 (other-pkgs (delete desc all-pkgs)))
1470 (when other-pkgs
1471 (insert " " (propertize "Other versions" 'font-lock-face 'bold) ": "
1472 (mapconcat
1473 (lambda (opkg)
1474 (let* ((ov (package-desc-version opkg))
1475 (dir (package-desc-dir opkg))
1476 (from (or (package-desc-archive opkg)
1477 (if (stringp dir) "installed" dir))))
1478 (if (not ov) (format "%s" from)
1479 (format "%s (%s)"
1480 (make-text-button (package-version-join ov) nil
1481 'face 'link
1482 'follow-link t
1483 'action
1484 (lambda (_button)
1485 (describe-package opkg)))
1486 from))))
1487 other-pkgs ", ")
1488 ".\n")))
1489
1490 (insert "\n")
1491
1492 (if built-in
1493 ;; For built-in packages, insert the commentary.
1494 (let ((fn (locate-file (format "%s.el" name) load-path
1495 load-file-rep-suffixes))
1496 (opoint (point)))
1497 (insert (or (lm-commentary fn) ""))
1498 (save-excursion
1499 (goto-char opoint)
1500 (when (re-search-forward "^;;; Commentary:\n" nil t)
1501 (replace-match ""))
1502 (while (re-search-forward "^\\(;+ ?\\)" nil t)
1503 (replace-match ""))))
1504 (let ((readme (expand-file-name (format "%s-readme.txt" name)
1505 package-user-dir))
1506 readme-string)
1507 ;; For elpa packages, try downloading the commentary. If that
1508 ;; fails, try an existing readme file in `package-user-dir'.
1509 (cond ((condition-case nil
1510 (save-excursion
1511 (package--with-work-buffer
1512 (package-archive-base desc)
1513 (format "%s-readme.txt" name)
1514 (setq buffer-file-name
1515 (expand-file-name readme package-user-dir))
1516 (let ((version-control 'never)
1517 (require-final-newline t))
1518 (save-buffer))
1519 (setq readme-string (buffer-string))
1520 t))
1521 (error nil))
1522 (insert readme-string))
1523 ((file-readable-p readme)
1524 (insert-file-contents readme)
1525 (goto-char (point-max))))))))
1526
1527 (defun package-install-button-action (button)
1528 (let ((pkg-desc (button-get button 'package-desc)))
1529 (when (y-or-n-p (format "Install package `%s'? "
1530 (package-desc-full-name pkg-desc)))
1531 (package-install pkg-desc)
1532 (revert-buffer nil t)
1533 (goto-char (point-min)))))
1534
1535 (defun package-keyword-button-action (button)
1536 (let ((pkg-keyword (button-get button 'package-keyword)))
1537 (package-show-package-list t (list pkg-keyword))))
1538
1539 (defun package-make-button (text &rest props)
1540 (let ((button-text (if (display-graphic-p) text (concat "[" text "]")))
1541 (button-face (if (display-graphic-p)
1542 '(:box (:line-width 2 :color "dark grey")
1543 :background "light grey"
1544 :foreground "black")
1545 'link)))
1546 (apply 'insert-text-button button-text 'face button-face 'follow-link t
1547 props)))
1548
1549 \f
1550 ;;;; Package menu mode.
1551
1552 (defvar package-menu-mode-map
1553 (let ((map (make-sparse-keymap))
1554 (menu-map (make-sparse-keymap "Package")))
1555 (set-keymap-parent map tabulated-list-mode-map)
1556 (define-key map "\C-m" 'package-menu-describe-package)
1557 (define-key map "u" 'package-menu-mark-unmark)
1558 (define-key map "\177" 'package-menu-backup-unmark)
1559 (define-key map "d" 'package-menu-mark-delete)
1560 (define-key map "i" 'package-menu-mark-install)
1561 (define-key map "U" 'package-menu-mark-upgrades)
1562 (define-key map "r" 'package-menu-refresh)
1563 (define-key map "f" 'package-menu-filter-interactive)
1564 (define-key map "~" 'package-menu-mark-obsolete-for-deletion)
1565 (define-key map "x" 'package-menu-execute)
1566 (define-key map "h" 'package-menu-quick-help)
1567 (define-key map "?" 'package-menu-describe-package)
1568 (define-key map [menu-bar package-menu] (cons "Package" menu-map))
1569 (define-key menu-map [mq]
1570 '(menu-item "Quit" quit-window
1571 :help "Quit package selection"))
1572 (define-key menu-map [mf]
1573 '(menu-item "Filter" package-menu-filter-interactive
1574 :help "Filter package selection (q to go back)"))
1575 (define-key menu-map [s1] '("--"))
1576 (define-key menu-map [mn]
1577 '(menu-item "Next" next-line
1578 :help "Next Line"))
1579 (define-key menu-map [mp]
1580 '(menu-item "Previous" previous-line
1581 :help "Previous Line"))
1582 (define-key menu-map [s2] '("--"))
1583 (define-key menu-map [mu]
1584 '(menu-item "Unmark" package-menu-mark-unmark
1585 :help "Clear any marks on a package and move to the next line"))
1586 (define-key menu-map [munm]
1587 '(menu-item "Unmark Backwards" package-menu-backup-unmark
1588 :help "Back up one line and clear any marks on that package"))
1589 (define-key menu-map [md]
1590 '(menu-item "Mark for Deletion" package-menu-mark-delete
1591 :help "Mark a package for deletion and move to the next line"))
1592 (define-key menu-map [mi]
1593 '(menu-item "Mark for Install" package-menu-mark-install
1594 :help "Mark a package for installation and move to the next line"))
1595 (define-key menu-map [mupgrades]
1596 '(menu-item "Mark Upgradable Packages" package-menu-mark-upgrades
1597 :help "Mark packages that have a newer version for upgrading"))
1598 (define-key menu-map [s3] '("--"))
1599 (define-key menu-map [mg]
1600 '(menu-item "Update Package List" revert-buffer
1601 :help "Update the list of packages"))
1602 (define-key menu-map [mr]
1603 '(menu-item "Refresh Package List" package-menu-refresh
1604 :help "Download the ELPA archive"))
1605 (define-key menu-map [s4] '("--"))
1606 (define-key menu-map [mt]
1607 '(menu-item "Mark Obsolete Packages" package-menu-mark-obsolete-for-deletion
1608 :help "Mark all obsolete packages for deletion"))
1609 (define-key menu-map [mx]
1610 '(menu-item "Execute Actions" package-menu-execute
1611 :help "Perform all the marked actions"))
1612 (define-key menu-map [s5] '("--"))
1613 (define-key menu-map [mh]
1614 '(menu-item "Help" package-menu-quick-help
1615 :help "Show short key binding help for package-menu-mode"))
1616 (define-key menu-map [mc]
1617 '(menu-item "View Commentary" package-menu-view-commentary
1618 :help "Display information about this package"))
1619 map)
1620 "Local keymap for `package-menu-mode' buffers.")
1621
1622 (defvar package-menu--new-package-list nil
1623 "List of newly-available packages since `list-packages' was last called.")
1624
1625 (define-derived-mode package-menu-mode tabulated-list-mode "Package Menu"
1626 "Major mode for browsing a list of packages.
1627 Letters do not insert themselves; instead, they are commands.
1628 \\<package-menu-mode-map>
1629 \\{package-menu-mode-map}"
1630 (setq tabulated-list-format [("Package" 18 package-menu--name-predicate)
1631 ("Version" 12 nil)
1632 ("Status" 10 package-menu--status-predicate)
1633 ("Archive" 10 package-menu--archive-predicate)
1634 ("Description" 0 nil)])
1635 (setq tabulated-list-padding 2)
1636 (setq tabulated-list-sort-key (cons "Status" nil))
1637 (add-hook 'tabulated-list-revert-hook 'package-menu--refresh nil t)
1638 (tabulated-list-init-header))
1639
1640 (defmacro package--push (pkg-desc status listname)
1641 "Convenience macro for `package-menu--generate'.
1642 If the alist stored in the symbol LISTNAME lacks an entry for a
1643 package PKG-DESC, add one. The alist is keyed with PKG-DESC."
1644 `(unless (assoc ,pkg-desc ,listname)
1645 ;; FIXME: Should we move status into pkg-desc?
1646 (push (cons ,pkg-desc ,status) ,listname)))
1647
1648 (defvar package-list-unversioned nil
1649 "If non-nil include packages that don't have a version in `list-package'.")
1650
1651 (defun package-desc-status (pkg-desc)
1652 (let* ((name (package-desc-name pkg-desc))
1653 (dir (package-desc-dir pkg-desc))
1654 (lle (assq name package-load-list))
1655 (held (cadr lle))
1656 (version (package-desc-version pkg-desc))
1657 (signed (package-desc-signed pkg-desc)))
1658 (cond
1659 ((eq dir 'builtin) "built-in")
1660 ((and lle (null held)) "disabled")
1661 ((stringp held)
1662 (let ((hv (if (stringp held) (version-to-list held))))
1663 (cond
1664 ((version-list-= version hv) "held")
1665 ((version-list-< version hv) "obsolete")
1666 (t "disabled"))))
1667 ((package-built-in-p name version) "obsolete")
1668 (dir ;One of the installed packages.
1669 (cond
1670 ((not (file-exists-p (package-desc-dir pkg-desc))) "deleted")
1671 ((eq pkg-desc (cadr (assq name package-alist))) (if signed
1672 "installed"
1673 "unsigned"))
1674 (t "obsolete")))
1675 (t
1676 (let* ((ins (cadr (assq name package-alist)))
1677 (ins-v (if ins (package-desc-version ins))))
1678 (cond
1679 ((or (null ins) (version-list-< ins-v version))
1680 (if (memq name package-menu--new-package-list)
1681 "new" "available"))
1682 ((version-list-< version ins-v) "obsolete")
1683 ((version-list-= version ins-v) (if signed
1684 "installed"
1685 "unsigned"))))))))
1686
1687 (defun package-menu--refresh (&optional packages keywords)
1688 "Re-populate the `tabulated-list-entries'.
1689 PACKAGES should be nil or t, which means to display all known packages.
1690 KEYWORDS should be nil or a list of keywords."
1691 ;; Construct list of (PKG-DESC . STATUS).
1692 (unless packages (setq packages t))
1693 (let (info-list name)
1694 ;; Installed packages:
1695 (dolist (elt package-alist)
1696 (setq name (car elt))
1697 (when (or (eq packages t) (memq name packages))
1698 (dolist (pkg (cdr elt))
1699 (when (package--has-keyword-p pkg keywords)
1700 (package--push pkg (package-desc-status pkg) info-list)))))
1701
1702 ;; Built-in packages:
1703 (dolist (elt package--builtins)
1704 (setq name (car elt))
1705 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
1706 (package--has-keyword-p (package--from-builtin elt) keywords)
1707 (or package-list-unversioned
1708 (package--bi-desc-version (cdr elt)))
1709 (or (eq packages t) (memq name packages)))
1710 (package--push (package--from-builtin elt) "built-in" info-list)))
1711
1712 ;; Available and disabled packages:
1713 (dolist (elt package-archive-contents)
1714 (setq name (car elt))
1715 (when (or (eq packages t) (memq name packages))
1716 (dolist (pkg (cdr elt))
1717 ;; Hide obsolete packages.
1718 (when (and (not (package-installed-p (package-desc-name pkg)
1719 (package-desc-version pkg)))
1720 (package--has-keyword-p pkg keywords))
1721 (package--push pkg (package-desc-status pkg) info-list)))))
1722
1723 ;; Print the result.
1724 (setq tabulated-list-entries
1725 (mapcar #'package-menu--print-info info-list))))
1726
1727 (defun package-all-keywords ()
1728 "Collect all package keywords"
1729 (let (keywords)
1730 (package--mapc (lambda (desc)
1731 (let* ((extras (and desc (package-desc-extras desc)))
1732 (desc-keywords (cdr (assoc :keywords extras))))
1733 (setq keywords (append keywords desc-keywords)))))
1734 keywords))
1735
1736 (defun package--mapc (function &optional packages)
1737 "Call FUNCTION for all known PACKAGES.
1738 PACKAGES can be nil or t, which means to display all known
1739 packages, or a list of packages.
1740
1741 Built-in packages are converted with `package--from-builtin'."
1742 (unless packages (setq packages t))
1743 (let (name)
1744 ;; Installed packages:
1745 (dolist (elt package-alist)
1746 (setq name (car elt))
1747 (when (or (eq packages t) (memq name packages))
1748 (mapc function (cdr elt))))
1749
1750 ;; Built-in packages:
1751 (dolist (elt package--builtins)
1752 (setq name (car elt))
1753 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
1754 (or package-list-unversioned
1755 (package--bi-desc-version (cdr elt)))
1756 (or (eq packages t) (memq name packages)))
1757 (funcall function (package--from-builtin elt))))
1758
1759 ;; Available and disabled packages:
1760 (dolist (elt package-archive-contents)
1761 (setq name (car elt))
1762 (when (or (eq packages t) (memq name packages))
1763 (dolist (pkg (cdr elt))
1764 ;; Hide obsolete packages.
1765 (unless (package-installed-p (package-desc-name pkg)
1766 (package-desc-version pkg))
1767 (funcall function pkg)))))))
1768
1769 (defun package--has-keyword-p (desc &optional keywords)
1770 "Test if package DESC has any of the given KEYWORDS.
1771 When none are given, the package matches."
1772 (if keywords
1773 (let* ((extras (and desc (package-desc-extras desc)))
1774 (desc-keywords (cdr (assoc :keywords extras)))
1775 found)
1776 (dolist (k keywords)
1777 (when (and (not found)
1778 (member k desc-keywords))
1779 (setq found t)))
1780 found)
1781 t))
1782
1783 (defun package-menu--generate (remember-pos packages &optional keywords)
1784 "Populate the Package Menu.
1785 If REMEMBER-POS is non-nil, keep point on the same entry.
1786 PACKAGES should be t, which means to display all known packages,
1787 or a list of package names (symbols) to display.
1788
1789 With KEYWORDS given, only packages with those keywords are
1790 shown."
1791 (package-menu--refresh packages keywords)
1792 (setf (car (aref tabulated-list-format 0))
1793 (if keywords
1794 (let ((filters (mapconcat 'identity keywords ",")))
1795 (concat "Package[" filters "]"))
1796 "Package"))
1797 (if keywords
1798 (define-key package-menu-mode-map "q" 'package-show-package-list)
1799 (define-key package-menu-mode-map "q" 'quit-window))
1800 (tabulated-list-init-header)
1801 (tabulated-list-print remember-pos))
1802
1803 (defun package-menu--print-info (pkg)
1804 "Return a package entry suitable for `tabulated-list-entries'.
1805 PKG has the form (PKG-DESC . STATUS).
1806 Return (PKG-DESC [NAME VERSION STATUS DOC])."
1807 (let* ((pkg-desc (car pkg))
1808 (status (cdr pkg))
1809 (face (pcase status
1810 (`"built-in" 'font-lock-builtin-face)
1811 (`"available" 'default)
1812 (`"new" 'bold)
1813 (`"held" 'font-lock-constant-face)
1814 (`"disabled" 'font-lock-warning-face)
1815 (`"installed" 'font-lock-comment-face)
1816 (`"unsigned" 'font-lock-warning-face)
1817 (_ 'font-lock-warning-face)))) ; obsolete.
1818 (list pkg-desc
1819 (vector (list (symbol-name (package-desc-name pkg-desc))
1820 'face 'link
1821 'follow-link t
1822 'package-desc pkg-desc
1823 'action 'package-menu-describe-package)
1824 (propertize (package-version-join
1825 (package-desc-version pkg-desc))
1826 'font-lock-face face)
1827 (propertize status 'font-lock-face face)
1828 (propertize (or (package-desc-archive pkg-desc) "")
1829 'font-lock-face face)
1830 (propertize (package-desc-summary pkg-desc)
1831 'font-lock-face face)))))
1832
1833 (defun package-menu-refresh ()
1834 "Download the Emacs Lisp package archive.
1835 This fetches the contents of each archive specified in
1836 `package-archives', and then refreshes the package menu."
1837 (interactive)
1838 (unless (derived-mode-p 'package-menu-mode)
1839 (user-error "The current buffer is not a Package Menu"))
1840 (package-refresh-contents)
1841 (package-menu--generate t t))
1842
1843 (defun package-menu-describe-package (&optional button)
1844 "Describe the current package.
1845 If optional arg BUTTON is non-nil, describe its associated package."
1846 (interactive)
1847 (let ((pkg-desc (if button (button-get button 'package-desc)
1848 (tabulated-list-get-id))))
1849 (if pkg-desc
1850 (describe-package pkg-desc)
1851 (user-error "No package here"))))
1852
1853 ;; fixme numeric argument
1854 (defun package-menu-mark-delete (&optional _num)
1855 "Mark a package for deletion and move to the next line."
1856 (interactive "p")
1857 (if (member (package-menu-get-status) '("installed" "obsolete" "unsigned"))
1858 (tabulated-list-put-tag "D" t)
1859 (forward-line)))
1860
1861 (defun package-menu-mark-install (&optional _num)
1862 "Mark a package for installation and move to the next line."
1863 (interactive "p")
1864 (if (member (package-menu-get-status) '("available" "new"))
1865 (tabulated-list-put-tag "I" t)
1866 (forward-line)))
1867
1868 (defun package-menu-mark-unmark (&optional _num)
1869 "Clear any marks on a package and move to the next line."
1870 (interactive "p")
1871 (tabulated-list-put-tag " " t))
1872
1873 (defun package-menu-backup-unmark ()
1874 "Back up one line and clear any marks on that package."
1875 (interactive)
1876 (forward-line -1)
1877 (tabulated-list-put-tag " "))
1878
1879 (defun package-menu-mark-obsolete-for-deletion ()
1880 "Mark all obsolete packages for deletion."
1881 (interactive)
1882 (save-excursion
1883 (goto-char (point-min))
1884 (while (not (eobp))
1885 (if (equal (package-menu-get-status) "obsolete")
1886 (tabulated-list-put-tag "D" t)
1887 (forward-line 1)))))
1888
1889 (defun package-menu-quick-help ()
1890 "Show short key binding help for package-menu-mode."
1891 (interactive)
1892 (message "n-ext, i-nstall, d-elete, u-nmark, x-ecute, r-efresh, h-elp"))
1893
1894 (define-obsolete-function-alias
1895 'package-menu-view-commentary 'package-menu-describe-package "24.1")
1896
1897 (defun package-menu-get-status ()
1898 (let* ((id (tabulated-list-get-id))
1899 (entry (and id (assq id tabulated-list-entries))))
1900 (if entry
1901 (aref (cadr entry) 2)
1902 "")))
1903
1904 (defun package-menu--find-upgrades ()
1905 (let (installed available upgrades)
1906 ;; Build list of installed/available packages in this buffer.
1907 (dolist (entry tabulated-list-entries)
1908 ;; ENTRY is (PKG-DESC [NAME VERSION STATUS DOC])
1909 (let ((pkg-desc (car entry))
1910 (status (aref (cadr entry) 2)))
1911 (cond ((member status '("installed" "unsigned"))
1912 (push pkg-desc installed))
1913 ((member status '("available" "new"))
1914 (push (cons (package-desc-name pkg-desc) pkg-desc)
1915 available)))))
1916 ;; Loop through list of installed packages, finding upgrades.
1917 (dolist (pkg-desc installed)
1918 (let ((avail-pkg (assq (package-desc-name pkg-desc) available)))
1919 (and avail-pkg
1920 (version-list-< (package-desc-version pkg-desc)
1921 (package-desc-version (cdr avail-pkg)))
1922 (push avail-pkg upgrades))))
1923 upgrades))
1924
1925 (defun package-menu-mark-upgrades ()
1926 "Mark all upgradable packages in the Package Menu.
1927 For each installed package with a newer version available, place
1928 an (I)nstall flag on the available version and a (D)elete flag on
1929 the installed version. A subsequent \\[package-menu-execute]
1930 call will upgrade the package."
1931 (interactive)
1932 (unless (derived-mode-p 'package-menu-mode)
1933 (error "The current buffer is not a Package Menu"))
1934 (let ((upgrades (package-menu--find-upgrades)))
1935 (if (null upgrades)
1936 (message "No packages to upgrade.")
1937 (widen)
1938 (save-excursion
1939 (goto-char (point-min))
1940 (while (not (eobp))
1941 (let* ((pkg-desc (tabulated-list-get-id))
1942 (upgrade (cdr (assq (package-desc-name pkg-desc) upgrades))))
1943 (cond ((null upgrade)
1944 (forward-line 1))
1945 ((equal pkg-desc upgrade)
1946 (package-menu-mark-install))
1947 (t
1948 (package-menu-mark-delete))))))
1949 (message "%d package%s marked for upgrading."
1950 (length upgrades)
1951 (if (= (length upgrades) 1) "" "s")))))
1952
1953 (defun package-menu-execute (&optional noquery)
1954 "Perform marked Package Menu actions.
1955 Packages marked for installation are downloaded and installed;
1956 packages marked for deletion are removed.
1957 Optional argument NOQUERY non-nil means do not ask the user to confirm."
1958 (interactive)
1959 (unless (derived-mode-p 'package-menu-mode)
1960 (error "The current buffer is not in Package Menu mode"))
1961 (let (install-list delete-list cmd pkg-desc)
1962 (save-excursion
1963 (goto-char (point-min))
1964 (while (not (eobp))
1965 (setq cmd (char-after))
1966 (unless (eq cmd ?\s)
1967 ;; This is the key PKG-DESC.
1968 (setq pkg-desc (tabulated-list-get-id))
1969 (cond ((eq cmd ?D)
1970 (push pkg-desc delete-list))
1971 ((eq cmd ?I)
1972 (push pkg-desc install-list))))
1973 (forward-line)))
1974 (when install-list
1975 (if (or
1976 noquery
1977 (yes-or-no-p
1978 (if (= (length install-list) 1)
1979 (format "Install package `%s'? "
1980 (package-desc-full-name (car install-list)))
1981 (format "Install these %d packages (%s)? "
1982 (length install-list)
1983 (mapconcat #'package-desc-full-name
1984 install-list ", ")))))
1985 (mapc 'package-install install-list)))
1986 ;; Delete packages, prompting if necessary.
1987 (when delete-list
1988 (if (or
1989 noquery
1990 (yes-or-no-p
1991 (if (= (length delete-list) 1)
1992 (format "Delete package `%s'? "
1993 (package-desc-full-name (car delete-list)))
1994 (format "Delete these %d packages (%s)? "
1995 (length delete-list)
1996 (mapconcat #'package-desc-full-name
1997 delete-list ", ")))))
1998 (dolist (elt delete-list)
1999 (condition-case-unless-debug err
2000 (package-delete elt)
2001 (error (message (cadr err)))))
2002 (error "Aborted")))
2003 (if (or delete-list install-list)
2004 (package-menu--generate t t)
2005 (message "No operations specified."))))
2006
2007 (defun package-menu--version-predicate (A B)
2008 (let ((vA (or (aref (cadr A) 1) '(0)))
2009 (vB (or (aref (cadr B) 1) '(0))))
2010 (if (version-list-= vA vB)
2011 (package-menu--name-predicate A B)
2012 (version-list-< vA vB))))
2013
2014 (defun package-menu--status-predicate (A B)
2015 (let ((sA (aref (cadr A) 2))
2016 (sB (aref (cadr B) 2)))
2017 (cond ((string= sA sB)
2018 (package-menu--name-predicate A B))
2019 ((string= sA "new") t)
2020 ((string= sB "new") nil)
2021 ((string= sA "available") t)
2022 ((string= sB "available") nil)
2023 ((string= sA "installed") t)
2024 ((string= sB "installed") nil)
2025 ((string= sA "unsigned") t)
2026 ((string= sB "unsigned") nil)
2027 ((string= sA "held") t)
2028 ((string= sB "held") nil)
2029 ((string= sA "built-in") t)
2030 ((string= sB "built-in") nil)
2031 ((string= sA "obsolete") t)
2032 ((string= sB "obsolete") nil)
2033 (t (string< sA sB)))))
2034
2035 (defun package-menu--description-predicate (A B)
2036 (let ((dA (aref (cadr A) 3))
2037 (dB (aref (cadr B) 3)))
2038 (if (string= dA dB)
2039 (package-menu--name-predicate A B)
2040 (string< dA dB))))
2041
2042 (defun package-menu--name-predicate (A B)
2043 (string< (symbol-name (package-desc-name (car A)))
2044 (symbol-name (package-desc-name (car B)))))
2045
2046 (defun package-menu--archive-predicate (A B)
2047 (string< (or (package-desc-archive (car A)) "")
2048 (or (package-desc-archive (car B)) "")))
2049
2050 ;;;###autoload
2051 (defun list-packages (&optional no-fetch)
2052 "Display a list of packages.
2053 This first fetches the updated list of packages before
2054 displaying, unless a prefix argument NO-FETCH is specified.
2055 The list is displayed in a buffer named `*Packages*'."
2056 (interactive "P")
2057 (require 'finder-inf nil t)
2058 ;; Initialize the package system if necessary.
2059 (unless package--initialized
2060 (package-initialize t))
2061 (let (old-archives new-packages)
2062 (unless no-fetch
2063 ;; Read the locally-cached archive-contents.
2064 (package-read-all-archive-contents)
2065 (setq old-archives package-archive-contents)
2066 ;; Fetch the remote list of packages.
2067 (package-refresh-contents)
2068 ;; Find which packages are new.
2069 (dolist (elt package-archive-contents)
2070 (unless (assq (car elt) old-archives)
2071 (push (car elt) new-packages))))
2072
2073 ;; Generate the Package Menu.
2074 (let ((buf (get-buffer-create "*Packages*")))
2075 (with-current-buffer buf
2076 (package-menu-mode)
2077 (set (make-local-variable 'package-menu--new-package-list)
2078 new-packages)
2079 (package-menu--generate nil t))
2080 ;; The package menu buffer has keybindings. If the user types
2081 ;; `M-x list-packages', that suggests it should become current.
2082 (switch-to-buffer buf))
2083
2084 (let ((upgrades (package-menu--find-upgrades)))
2085 (if upgrades
2086 (message "%d package%s can be upgraded; type `%s' to mark %s for upgrading."
2087 (length upgrades)
2088 (if (= (length upgrades) 1) "" "s")
2089 (substitute-command-keys "\\[package-menu-mark-upgrades]")
2090 (if (= (length upgrades) 1) "it" "them"))))))
2091
2092 ;;;###autoload
2093 (defalias 'package-list-packages 'list-packages)
2094
2095 ;; Used in finder.el
2096 (defun package-show-package-list (&optional packages keywords)
2097 "Display PACKAGES in a *Packages* buffer.
2098 This is similar to `list-packages', but it does not fetch the
2099 updated list of packages, and it only displays packages with
2100 names in PACKAGES (which should be a list of symbols).
2101
2102 When KEYWORDS are given, only packages with those KEYWORDS are
2103 shown."
2104 (interactive)
2105 (require 'finder-inf nil t)
2106 (let ((buf (get-buffer-create "*Packages*")))
2107 (with-current-buffer buf
2108 (package-menu-mode)
2109 (package-menu--generate nil packages keywords))
2110 (switch-to-buffer buf)))
2111
2112 (defun package-menu-filter-interactive (keyword)
2113 "Filter the *Packages* buffer."
2114 (interactive (list (completing-read "Keyword: " (package-all-keywords))))
2115 (package-show-package-list t (list keyword)))
2116
2117 (defun package-list-packages-no-fetch ()
2118 "Display a list of packages.
2119 Does not fetch the updated list of packages before displaying.
2120 The list is displayed in a buffer named `*Packages*'."
2121 (interactive)
2122 (list-packages t))
2123
2124 (provide 'package)
2125
2126 ;;; package.el ends here