Merge from mainline.
[bpt/emacs.git] / lisp / emacs-lisp / package.el
1 ;;; package.el --- Simple package system for Emacs
2
3 ;; Copyright (C) 2007-2011 Free Software Foundation, Inc.
4
5 ;; Author: Tom Tromey <tromey@redhat.com>
6 ;; Created: 10 Mar 2007
7 ;; Version: 0.9
8 ;; Keywords: tools
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
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-list-packages-no-fetch
88 ;; Like package-list-packages, but does not automatically fetch the
89 ;; new list of packages.
90 ;;
91 ;; M-x package-install-from-buffer
92 ;; Install a package consisting of a single .el file that appears
93 ;; in the current buffer. This only works for packages which
94 ;; define a Version header properly; package.el also supports the
95 ;; extension headers Package-Version (in case Version is an RCS id
96 ;; or similar), and Package-Requires (if the package requires other
97 ;; packages).
98 ;;
99 ;; M-x package-install-file
100 ;; Install a package from the indicated file. The package can be
101 ;; either a tar file or a .el file. A tar file must contain an
102 ;; appropriately-named "-pkg.el" file; a .el file must be properly
103 ;; formatted as with package-install-from-buffer.
104
105 ;;; Thanks:
106 ;;; (sorted by sort-lines):
107
108 ;; Jim Blandy <jimb@red-bean.com>
109 ;; Karl Fogel <kfogel@red-bean.com>
110 ;; Kevin Ryde <user42@zip.com.au>
111 ;; Lawrence Mitchell
112 ;; Michael Olson <mwolson@member.fsf.org>
113 ;; Sebastian Tennant <sebyte@smolny.plus.com>
114 ;; Stefan Monnier <monnier@iro.umontreal.ca>
115 ;; Vinicius Jose Latorre <viniciusjl@ig.com.br>
116 ;; Phil Hagelberg <phil@hagelb.org>
117
118 ;;; ToDo:
119
120 ;; - putting info dirs at the start of the info path means
121 ;; users see a weird ordering of categories. OTOH we want to
122 ;; override later entries. maybe emacs needs to enforce
123 ;; the standard layout?
124 ;; - put bytecode in a separate directory tree
125 ;; - perhaps give users a way to recompile their bytecode
126 ;; or do it automatically when emacs changes
127 ;; - give users a way to know whether a package is installed ok
128 ;; - give users a way to view a package's documentation when it
129 ;; only appears in the .el
130 ;; - use/extend checkdoc so people can tell if their package will work
131 ;; - "installed" instead of a blank in the status column
132 ;; - tramp needs its files to be compiled in a certain order.
133 ;; how to handle this? fix tramp?
134 ;; - on emacs 21 we don't kill the -autoloads.el buffer. what about 22?
135 ;; - maybe we need separate .elc directories for various emacs versions
136 ;; and also emacs-vs-xemacs. That way conditional compilation can
137 ;; work. But would this break anything?
138 ;; - should store the package's keywords in archive-contents, then
139 ;; let the users filter the package-menu by keyword. See
140 ;; finder-by-keyword. (We could also let people view the
141 ;; Commentary, but it isn't clear how useful this is.)
142 ;; - William Xu suggests being able to open a package file without
143 ;; installing it
144 ;; - Interface with desktop.el so that restarting after an install
145 ;; works properly
146 ;; - Implement M-x package-upgrade, to upgrade any/all existing packages
147 ;; - Use hierarchical layout. PKG/etc PKG/lisp PKG/info
148 ;; ... except maybe lisp?
149 ;; - It may be nice to have a macro that expands to the package's
150 ;; private data dir, aka ".../etc". Or, maybe data-directory
151 ;; needs to be a list (though this would be less nice)
152 ;; a few packages want this, eg sokoban
153 ;; - package menu needs:
154 ;; ability to know which packages are built-in & thus not deletable
155 ;; it can sometimes print odd results, like 0.3 available but 0.4 active
156 ;; why is that?
157 ;; - Allow multiple versions on the server...?
158 ;; [ why bother? ]
159 ;; - Don't install a package which will invalidate dependencies overall
160 ;; - Allow something like (or (>= emacs 21.0) (>= xemacs 21.5))
161 ;; [ currently thinking, why bother.. KISS ]
162 ;; - Allow optional package dependencies
163 ;; then if we require 'bbdb', bbdb-specific lisp in lisp/bbdb
164 ;; and just don't compile to add to load path ...?
165 ;; - Have a list of archive URLs? [ maybe there's no point ]
166 ;; - David Kastrup pointed out on the xemacs list that for GPL it
167 ;; is friendlier to ship the source tree. We could "support" that
168 ;; by just having a "src" subdir in the package. This isn't ideal
169 ;; but it probably is not worth trying to support random source
170 ;; tree layouts, build schemes, etc.
171 ;; - Our treatment of the info path is somewhat bogus
172 ;; - perhaps have an "unstable" tree in ELPA as well as a stable one
173
174 ;;; Code:
175
176 (defgroup package nil
177 "Manager for Emacs Lisp packages."
178 :group 'applications
179 :version "24.1")
180
181 ;;;###autoload
182 (defcustom package-enable-at-startup t
183 "Whether to activate installed packages when Emacs starts.
184 If non-nil, packages are activated after reading the init file
185 and before `after-init-hook'. Activation is not done if
186 `user-init-file' is nil (e.g. Emacs was started with \"-q\").
187
188 Even if the value is nil, you can type \\[package-initialize] to
189 activate the package system at any time."
190 :type 'boolean
191 :group 'package
192 :version "24.1")
193
194 (defcustom package-load-list '(all)
195 "List of packages for `package-initialize' to load.
196 Each element in this list should be a list (NAME VERSION), or the
197 symbol `all'. The symbol `all' says to load the latest installed
198 versions of all packages not specified by other elements.
199
200 For an element (NAME VERSION), NAME is a package name (a symbol).
201 VERSION should be t, a string, or nil.
202 If VERSION is t, all versions are loaded, though obsolete ones
203 will be put in `package-obsolete-alist' and not activated.
204 If VERSION is a string, only that version is ever loaded.
205 Any other version, even if newer, is silently ignored.
206 Hence, the package is \"held\" at that version.
207 If VERSION is nil, the package is not loaded (it is \"disabled\")."
208 :type '(repeat symbol)
209 :risky t
210 :group 'package
211 :version "24.1")
212
213 (defvar Info-directory-list)
214 (declare-function info-initialize "info" ())
215 (declare-function url-http-parse-response "url-http" ())
216 (declare-function lm-header "lisp-mnt" (header))
217 (declare-function lm-commentary "lisp-mnt" (&optional file))
218 (defvar url-http-end-of-headers)
219
220 (defcustom package-archives '(("gnu" . "http://elpa.gnu.org/packages/"))
221 "An alist of archives from which to fetch.
222 The default value points to the GNU Emacs package repository.
223 Each element has the form (ID . URL), where ID is an identifier
224 string for an archive and URL is a http: URL (a string)."
225 :type '(alist :key-type (string :tag "Archive name")
226 :value-type (string :tag "Archive URL"))
227 :risky t
228 :group 'package
229 :version "24.1")
230
231 (defconst package-archive-version 1
232 "Version number of the package archive understood by this file.
233 Lower version numbers than this will probably be understood as well.")
234
235 (defconst package-el-version "1.0"
236 "Version of package.el.")
237
238 ;; We don't prime the cache since it tends to get out of date.
239 (defvar package-archive-contents nil
240 "Cache of the contents of the Emacs Lisp Package Archive.
241 This is an alist mapping package names (symbols) to package
242 descriptor vectors. These are like the vectors for `package-alist'
243 but have extra entries: one which is 'tar for tar packages and
244 'single for single-file packages, and one which is the name of
245 the archive from which it came.")
246 (put 'package-archive-contents 'risky-local-variable t)
247
248 (defcustom package-user-dir (locate-user-emacs-file "elpa")
249 "Directory containing the user's Emacs Lisp packages.
250 The directory name should be absolute.
251 Apart from this directory, Emacs also looks for system-wide
252 packages in `package-directory-list'."
253 :type 'directory
254 :risky t
255 :group 'package
256 :version "24.1")
257
258 (defcustom package-directory-list
259 ;; Defaults are subdirs named "elpa" in the site-lisp dirs.
260 (let (result)
261 (dolist (f load-path)
262 (and (stringp f)
263 (equal (file-name-nondirectory f) "site-lisp")
264 (push (expand-file-name "elpa" f) result)))
265 (nreverse result))
266 "List of additional directories containing Emacs Lisp packages.
267 Each directory name should be absolute.
268
269 These directories contain packages intended for system-wide; in
270 contrast, `package-user-dir' contains packages for personal use."
271 :type '(repeat directory)
272 :risky t
273 :group 'package
274 :version "24.1")
275
276 ;; The value is precomputed in finder-inf.el, but don't load that
277 ;; until it's needed (i.e. when `package-intialize' is called).
278 (defvar package--builtins nil
279 "Alist of built-in packages.
280 The actual value is initialized by loading the library
281 `finder-inf'; this is not done until it is needed, e.g. by the
282 function `package-built-in-p'.
283
284 Each element has the form (PKG . DESC), where PKG is a package
285 name (a symbol) and DESC is a vector that describes the package.
286 The vector DESC has the form [VERSION REQS DOCSTRING].
287 VERSION is a version list.
288 REQS is a list of packages (symbols) required by the package.
289 DOCSTRING is a brief description of the package.")
290 (put 'package--builtins 'risky-local-variable t)
291
292 (defvar package-alist nil
293 "Alist of all packages available for activation.
294 Each element has the form (PKG . DESC), where PKG is a package
295 name (a symbol) and DESC is a vector that describes the package.
296
297 The vector DESC has the form [VERSION REQS DOCSTRING].
298 VERSION is a version list.
299 REQS is a list of packages (symbols) required by the package.
300 DOCSTRING is a brief description of the package.
301
302 This variable is set automatically by `package-load-descriptor',
303 called via `package-initialize'. To change which packages are
304 loaded and/or activated, customize `package-load-list'.")
305 (put 'package-archive-contents 'risky-local-variable t)
306
307 (defvar package-activated-list nil
308 "List of the names of currently activated packages.")
309 (put 'package-activated-list 'risky-local-variable t)
310
311 (defvar package-obsolete-alist nil
312 "Representation of obsolete packages.
313 Like `package-alist', but maps package name to a second alist.
314 The inner alist is keyed by version.")
315 (put 'package-obsolete-alist 'risky-local-variable t)
316
317 (defconst package-subdirectory-regexp
318 "^\\([^.].*\\)-\\([0-9]+\\(?:[.][0-9]+\\)*\\)$"
319 "Regular expression matching the name of a package subdirectory.
320 The first subexpression is the package name.
321 The second subexpression is the version string.")
322
323 (defun package-version-join (l)
324 "Turn a list of version numbers into a version string."
325 (mapconcat 'int-to-string l "."))
326
327 (defun package-strip-version (dirname)
328 "Strip the version from a combined package name and version.
329 E.g., if given \"quux-23.0\", will return \"quux\""
330 (if (string-match package-subdirectory-regexp dirname)
331 (match-string 1 dirname)))
332
333 (defun package-load-descriptor (dir package)
334 "Load the description file in directory DIR for package PACKAGE.
335 Here, PACKAGE is a string of the form NAME-VER, where NAME is the
336 package name and VER is its version."
337 (let* ((pkg-dir (expand-file-name package dir))
338 (pkg-file (expand-file-name
339 (concat (package-strip-version package) "-pkg")
340 pkg-dir)))
341 (when (and (file-directory-p pkg-dir)
342 (file-exists-p (concat pkg-file ".el")))
343 (load pkg-file nil t))))
344
345 (defun package-load-all-descriptors ()
346 "Load descriptors for installed Emacs Lisp packages.
347 This looks for package subdirectories in `package-user-dir' and
348 `package-directory-list'. The variable `package-load-list'
349 controls which package subdirectories may be loaded.
350
351 In each valid package subdirectory, this function loads the
352 description file containing a call to `define-package', which
353 updates `package-alist' and `package-obsolete-alist'."
354 (let ((all (memq 'all package-load-list))
355 name version force)
356 (dolist (dir (cons package-user-dir package-directory-list))
357 (when (file-directory-p dir)
358 (dolist (subdir (directory-files dir))
359 (when (and (file-directory-p (expand-file-name subdir dir))
360 (string-match package-subdirectory-regexp subdir))
361 (setq name (intern (match-string 1 subdir))
362 version (match-string 2 subdir)
363 force (assq name package-load-list))
364 (when (cond
365 ((null force)
366 all) ; not in package-load-list
367 ((null (setq force (cadr force)))
368 nil) ; disabled
369 ((eq force t)
370 t)
371 ((stringp force) ; held
372 (version-list-= (version-to-list version)
373 (version-to-list force)))
374 (t
375 (error "Invalid element in `package-load-list'")))
376 (package-load-descriptor dir subdir))))))))
377
378 (defsubst package-desc-vers (desc)
379 "Extract version from a package description vector."
380 (aref desc 0))
381
382 (defsubst package-desc-reqs (desc)
383 "Extract requirements from a package description vector."
384 (aref desc 1))
385
386 (defsubst package-desc-doc (desc)
387 "Extract doc string from a package description vector."
388 (aref desc 2))
389
390 (defsubst package-desc-kind (desc)
391 "Extract the kind of download from an archive package description vector."
392 (aref desc 3))
393
394 (defun package--dir (name version)
395 "Return the directory where a package is installed, or nil if none.
396 NAME and VERSION are both strings."
397 (let* ((subdir (concat name "-" version))
398 (dir-list (cons package-user-dir package-directory-list))
399 pkg-dir)
400 (while dir-list
401 (let ((subdir-full (expand-file-name subdir (car dir-list))))
402 (if (file-directory-p subdir-full)
403 (setq pkg-dir subdir-full
404 dir-list nil)
405 (setq dir-list (cdr dir-list)))))
406 pkg-dir))
407
408 (defun package-activate-1 (package pkg-vec)
409 (let* ((name (symbol-name package))
410 (version-str (package-version-join (package-desc-vers pkg-vec)))
411 (pkg-dir (package--dir name version-str)))
412 (unless pkg-dir
413 (error "Internal error: unable to find directory for `%s-%s'"
414 name version-str))
415 ;; Add info node.
416 (when (file-exists-p (expand-file-name "dir" pkg-dir))
417 ;; FIXME: not the friendliest, but simple.
418 (require 'info)
419 (info-initialize)
420 (push pkg-dir Info-directory-list))
421 ;; Add to load path, add autoloads, and activate the package.
422 (push pkg-dir load-path)
423 (load (expand-file-name (concat name "-autoloads") pkg-dir) nil t)
424 (push package package-activated-list)
425 ;; Don't return nil.
426 t))
427
428 (defun package-built-in-p (package &optional version)
429 "Return true if PACKAGE, of VERSION or newer, is built-in to Emacs."
430 (require 'finder-inf nil t) ; For `package--builtins'.
431 (let ((elt (assq package package--builtins)))
432 (and elt (version-list-<= version (package-desc-vers (cdr elt))))))
433
434 ;; This function goes ahead and activates a newer version of a package
435 ;; if an older one was already activated. This is not ideal; we'd at
436 ;; least need to check to see if the package has actually been loaded,
437 ;; and not merely activated.
438 (defun package-activate (package version)
439 "Activate package PACKAGE, of version VERSION or newer.
440 If PACKAGE has any dependencies, recursively activate them.
441 Return nil if the package could not be activated."
442 (let ((pkg-vec (cdr (assq package package-alist)))
443 available-version found)
444 ;; Check if PACKAGE is available in `package-alist'.
445 (when pkg-vec
446 (setq available-version (package-desc-vers pkg-vec)
447 found (version-list-<= version available-version)))
448 (cond
449 ;; If no such package is found, maybe it's built-in.
450 ((null found)
451 (package-built-in-p package version))
452 ;; If the package is already activated, just return t.
453 ((memq package package-activated-list)
454 t)
455 ;; Otherwise, proceed with activation.
456 (t
457 (let ((fail (catch 'dep-failure
458 ;; Activate its dependencies recursively.
459 (dolist (req (package-desc-reqs pkg-vec))
460 (unless (package-activate (car req) (cadr req))
461 (throw 'dep-failure req))))))
462 (if fail
463 (warn "Unable to activate package `%s'.
464 Required package `%s-%s' is unavailable"
465 package (car fail) (package-version-join (cadr fail)))
466 ;; If all goes well, activate the package itself.
467 (package-activate-1 package pkg-vec)))))))
468
469 (defun package-mark-obsolete (package pkg-vec)
470 "Put package on the obsolete list, if not already there."
471 (let ((elt (assq package package-obsolete-alist)))
472 (if elt
473 ;; If this obsolete version does not exist in the list, update
474 ;; it the list.
475 (unless (assoc (package-desc-vers pkg-vec) (cdr elt))
476 (setcdr elt (cons (cons (package-desc-vers pkg-vec) pkg-vec)
477 (cdr elt))))
478 ;; Make a new association.
479 (push (cons package (list (cons (package-desc-vers pkg-vec)
480 pkg-vec)))
481 package-obsolete-alist))))
482
483 (defun define-package (name-string version-string
484 &optional docstring requirements
485 &rest extra-properties)
486 "Define a new package.
487 NAME-STRING is the name of the package, as a string.
488 VERSION-STRING is the version of the package, as a list of
489 integers of the form produced by `version-to-list'.
490 DOCSTRING is a short description of the package, a string.
491 REQUIREMENTS is a list of dependencies on other packages.
492 Each requirement is of the form (OTHER-PACKAGE \"VERSION\").
493
494 EXTRA-PROPERTIES is currently unused."
495 (let* ((name (intern name-string))
496 (version (version-to-list version-string))
497 (new-pkg-desc
498 (cons name
499 (vector version
500 (mapcar
501 (lambda (elt)
502 (list (car elt)
503 (version-to-list (car (cdr elt)))))
504 requirements)
505 docstring)))
506 (old-pkg (assq name package-alist)))
507 (cond
508 ;; If there's no old package, just add this to `package-alist'.
509 ((null old-pkg)
510 (push new-pkg-desc package-alist))
511 ((version-list-< (package-desc-vers (cdr old-pkg)) version)
512 ;; Remove the old package and declare it obsolete.
513 (package-mark-obsolete name (cdr old-pkg))
514 (setq package-alist (cons new-pkg-desc
515 (delq old-pkg package-alist))))
516 ;; You can have two packages with the same version, e.g. one in
517 ;; the system package directory and one in your private
518 ;; directory. We just let the first one win.
519 ((not (version-list-= (package-desc-vers (cdr old-pkg)) version))
520 ;; The package is born obsolete.
521 (package-mark-obsolete name (cdr new-pkg-desc))))))
522
523 ;; From Emacs 22.
524 (defun package-autoload-ensure-default-file (file)
525 "Make sure that the autoload file FILE exists and if not create it."
526 (unless (file-exists-p file)
527 (write-region
528 (concat ";;; " (file-name-nondirectory file)
529 " --- automatically extracted autoloads\n"
530 ";;\n"
531 ";;; Code:\n\n"
532 "\f\n;; Local Variables:\n"
533 ";; version-control: never\n"
534 ";; no-byte-compile: t\n"
535 ";; no-update-autoloads: t\n"
536 ";; End:\n"
537 ";;; " (file-name-nondirectory file)
538 " ends here\n")
539 nil file))
540 file)
541
542 (defun package-generate-autoloads (name pkg-dir)
543 (let* ((auto-name (concat name "-autoloads.el"))
544 (ignore-name (concat name "-pkg.el"))
545 (generated-autoload-file (expand-file-name auto-name pkg-dir))
546 (version-control 'never))
547 (require 'autoload)
548 (unless (fboundp 'autoload-ensure-default-file)
549 (package-autoload-ensure-default-file generated-autoload-file))
550 (update-directory-autoloads pkg-dir)))
551
552 (defun package-untar-buffer ()
553 "Untar the current buffer.
554 This uses `tar-untar-buffer' if it is available.
555 Otherwise it uses an external `tar' program.
556 `default-directory' should be set by the caller."
557 (require 'tar-mode)
558 (if (fboundp 'tar-untar-buffer)
559 (progn
560 ;; tar-mode messes with narrowing, so we just let it have the
561 ;; whole buffer to play with.
562 (delete-region (point-min) (point))
563 (tar-mode)
564 (tar-untar-buffer))
565 ;; FIXME: check the result.
566 (call-process-region (point) (point-max) "tar" nil '(nil nil) nil
567 "xf" "-")))
568
569 (defun package-unpack (name version)
570 (let ((pkg-dir (expand-file-name (concat (symbol-name name) "-" version)
571 package-user-dir)))
572 (make-directory package-user-dir t)
573 ;; FIXME: should we delete PKG-DIR if it exists?
574 (let* ((default-directory (file-name-as-directory package-user-dir)))
575 (package-untar-buffer)
576 (package-generate-autoloads (symbol-name name) pkg-dir)
577 (let ((load-path (cons pkg-dir load-path)))
578 (byte-recompile-directory pkg-dir 0 t)))))
579
580 (defun package--write-file-no-coding (file-name)
581 (let ((buffer-file-coding-system 'no-conversion))
582 (write-region (point-min) (point-max) file-name)))
583
584 (defun package-unpack-single (file-name version desc requires)
585 "Install the contents of the current buffer as a package."
586 ;; Special case "package".
587 (if (string= file-name "package")
588 (package--write-file-no-coding
589 (expand-file-name (concat file-name ".el") package-user-dir))
590 (let* ((pkg-dir (expand-file-name (concat file-name "-" version)
591 package-user-dir))
592 (el-file (expand-file-name (concat file-name ".el") pkg-dir))
593 (pkg-file (expand-file-name (concat file-name "-pkg.el") pkg-dir)))
594 (make-directory pkg-dir t)
595 (package--write-file-no-coding el-file)
596 (let ((print-level nil)
597 (print-length nil))
598 (write-region
599 (concat
600 (prin1-to-string
601 (list 'define-package
602 file-name
603 version
604 desc
605 (list 'quote
606 ;; Turn version lists into string form.
607 (mapcar
608 (lambda (elt)
609 (list (car elt)
610 (package-version-join (cadr elt))))
611 requires))))
612 "\n")
613 nil
614 pkg-file
615 nil nil nil 'excl))
616 (package-generate-autoloads file-name pkg-dir)
617 (let ((load-path (cons pkg-dir load-path)))
618 (byte-recompile-directory pkg-dir 0 t)))))
619
620 (defun package-handle-response ()
621 "Handle the response from the server.
622 Parse the HTTP response and throw if an error occurred.
623 The url package seems to require extra processing for this.
624 This should be called in a `save-excursion', in the download buffer.
625 It will move point to somewhere in the headers."
626 ;; We assume HTTP here.
627 (require 'url-http)
628 (let ((response (url-http-parse-response)))
629 (when (or (< response 200) (>= response 300))
630 (display-buffer (current-buffer))
631 (error "Error during download request:%s"
632 (buffer-substring-no-properties (point) (progn
633 (end-of-line)
634 (point)))))))
635
636 (defun package-download-single (name version desc requires)
637 "Download and install a single-file package."
638 (let ((buffer (url-retrieve-synchronously
639 (concat (package-archive-url name)
640 (symbol-name name) "-" version ".el"))))
641 (with-current-buffer buffer
642 (package-handle-response)
643 (re-search-forward "^$" nil 'move)
644 (forward-char)
645 (delete-region (point-min) (point))
646 (package-unpack-single (symbol-name name) version desc requires)
647 (kill-buffer buffer))))
648
649 (defun package-download-tar (name version)
650 "Download and install a tar package."
651 (let ((tar-buffer (url-retrieve-synchronously
652 (concat (package-archive-url name)
653 (symbol-name name) "-" version ".tar"))))
654 (with-current-buffer tar-buffer
655 (package-handle-response)
656 (re-search-forward "^$" nil 'move)
657 (forward-char)
658 (package-unpack name version)
659 (kill-buffer tar-buffer))))
660
661 (defun package-installed-p (package &optional min-version)
662 "Return true if PACKAGE, of VERSION or newer, is installed.
663 Built-in packages also qualify."
664 (let ((pkg-desc (assq package package-alist)))
665 (if pkg-desc
666 (version-list-<= min-version
667 (package-desc-vers (cdr pkg-desc)))
668 ;; Also check built-in packages.
669 (package-built-in-p package min-version))))
670
671 (defun package-compute-transaction (package-list requirements)
672 "Return a list of packages to be installed, including PACKAGE-LIST.
673 PACKAGE-LIST should be a list of package names (symbols).
674
675 REQUIREMENTS should be a list of additional requirements; each
676 element in this list should have the form (PACKAGE VERSION),
677 where PACKAGE is a package name and VERSION is the required
678 version of that package (as a list).
679
680 This function recursively computes the requirements of the
681 packages in REQUIREMENTS, and returns a list of all the packages
682 that must be installed. Packages that are already installed are
683 not included in this list."
684 (dolist (elt requirements)
685 (let* ((next-pkg (car elt))
686 (next-version (cadr elt)))
687 (unless (package-installed-p next-pkg next-version)
688 ;; A package is required, but not installed. It might also be
689 ;; blocked via `package-load-list'.
690 (let ((pkg-desc (assq next-pkg package-archive-contents))
691 hold)
692 (when (setq hold (assq next-pkg package-load-list))
693 (setq hold (cadr hold))
694 (cond ((eq hold nil)
695 (error "Required package '%s' is disabled"
696 (symbol-name next-pkg)))
697 ((null (stringp hold))
698 (error "Invalid element in `package-load-list'"))
699 ((version-list-< (version-to-list hold) next-version)
700 (error "Package `%s' held at version %s, \
701 but version %s required"
702 (symbol-name next-pkg) hold
703 (package-version-join next-version)))))
704 (unless pkg-desc
705 (error "Package `%s-%s' is unavailable"
706 (symbol-name next-pkg)
707 (package-version-join next-version)))
708 (unless (version-list-<= next-version
709 (package-desc-vers (cdr pkg-desc)))
710 (error
711 "Need package `%s-%s', but only %s is available"
712 (symbol-name next-pkg) (package-version-join next-version)
713 (package-version-join (package-desc-vers (cdr pkg-desc)))))
714 ;; Only add to the transaction if we don't already have it.
715 (unless (memq next-pkg package-list)
716 (push next-pkg package-list))
717 (setq package-list
718 (package-compute-transaction package-list
719 (package-desc-reqs
720 (cdr pkg-desc))))))))
721 package-list)
722
723 (defun package-read-from-string (str)
724 "Read a Lisp expression from STR.
725 Signal an error if the entire string was not used."
726 (let* ((read-data (read-from-string str))
727 (more-left
728 (condition-case nil
729 ;; The call to `ignore' suppresses a compiler warning.
730 (progn (ignore (read-from-string
731 (substring str (cdr read-data))))
732 t)
733 (end-of-file nil))))
734 (if more-left
735 (error "Can't read whole string")
736 (car read-data))))
737
738 (defun package--read-archive-file (file)
739 "Re-read archive file FILE, if it exists.
740 Will return the data from the file, or nil if the file does not exist.
741 Will throw an error if the archive version is too new."
742 (let ((filename (expand-file-name file package-user-dir)))
743 (when (file-exists-p filename)
744 (with-temp-buffer
745 (insert-file-contents-literally filename)
746 (let ((contents (read (current-buffer))))
747 (if (> (car contents) package-archive-version)
748 (error "Package archive version %d is higher than %d"
749 (car contents) package-archive-version))
750 (cdr contents))))))
751
752 (defun package-read-all-archive-contents ()
753 "Re-read `archive-contents', if it exists.
754 If successful, set `package-archive-contents'."
755 (setq package-archive-contents nil)
756 (dolist (archive package-archives)
757 (package-read-archive-contents (car archive))))
758
759 (defun package-read-archive-contents (archive)
760 "Re-read archive contents for ARCHIVE.
761 If successful, set the variable `package-archive-contents'.
762 If the archive version is too new, signal an error."
763 ;; Version 1 of 'archive-contents' is identical to our internal
764 ;; representation.
765 (let* ((dir (concat "archives/" archive))
766 (contents-file (concat dir "/archive-contents"))
767 contents)
768 (when (setq contents (package--read-archive-file contents-file))
769 (dolist (package contents)
770 (package--add-to-archive-contents package archive)))))
771
772 (defun package--add-to-archive-contents (package archive)
773 "Add the PACKAGE from the given ARCHIVE if necessary.
774 Also, add the originating archive to the end of the package vector."
775 (let* ((name (car package))
776 (version (aref (cdr package) 0))
777 (entry (cons (car package)
778 (vconcat (cdr package) (vector archive))))
779 (existing-package (cdr (assq name package-archive-contents))))
780 (when (or (not existing-package)
781 (version-list-< (aref existing-package 0) version))
782 (add-to-list 'package-archive-contents entry))))
783
784 (defun package-download-transaction (package-list)
785 "Download and install all the packages in PACKAGE-LIST.
786 PACKAGE-LIST should be a list of package names (symbols).
787 This function assumes that all package requirements in
788 PACKAGE-LIST are satisfied, i.e. that PACKAGE-LIST is computed
789 using `package-compute-transaction'."
790 (dolist (elt package-list)
791 (let* ((desc (cdr (assq elt package-archive-contents)))
792 ;; As an exception, if package is "held" in
793 ;; `package-load-list', download the held version.
794 (hold (cadr (assq elt package-load-list)))
795 (v-string (or (and (stringp hold) hold)
796 (package-version-join (package-desc-vers desc))))
797 (kind (package-desc-kind desc)))
798 (cond
799 ((eq kind 'tar)
800 (package-download-tar elt v-string))
801 ((eq kind 'single)
802 (package-download-single elt v-string
803 (package-desc-doc desc)
804 (package-desc-reqs desc)))
805 (t
806 (error "Unknown package kind: %s" (symbol-name kind)))))))
807
808 ;;;###autoload
809 (defun package-install (name)
810 "Install the package named NAME.
811 Interactively, prompt for the package name.
812 The package is found on one of the archives in `package-archives'."
813 (interactive
814 (list (intern (completing-read "Install package: "
815 (mapcar (lambda (elt)
816 (cons (symbol-name (car elt))
817 nil))
818 package-archive-contents)
819 nil t))))
820 (let ((pkg-desc (assq name package-archive-contents)))
821 (unless pkg-desc
822 (error "Package `%s' is not available for installation"
823 (symbol-name name)))
824 (package-download-transaction
825 (package-compute-transaction (list name)
826 (package-desc-reqs (cdr pkg-desc)))))
827 ;; Try to activate it.
828 (package-initialize))
829
830 (defun package-strip-rcs-id (v-str)
831 "Strip RCS version ID from the version string.
832 If the result looks like a dotted numeric version, return it.
833 Otherwise return nil."
834 (if v-str
835 (if (string-match "^[ \t]*[$]Revision:[ \t]\([0-9.]+\)[ \t]*[$]$" v-str)
836 (match-string 1 v-str)
837 (if (string-match "^[0-9.]*$" v-str)
838 v-str))))
839
840 (defun package-buffer-info ()
841 "Return a vector describing the package in the current buffer.
842 The vector has the form
843
844 [FILENAME REQUIRES DESCRIPTION VERSION COMMENTARY]
845
846 FILENAME is the file name, a string, sans the \".el\" extension.
847 REQUIRES is a requires list, or nil.
848 DESCRIPTION is the package description, a string.
849 VERSION is the version, a string.
850 COMMENTARY is the commentary section, a string, or nil if none.
851
852 If the buffer does not contain a conforming package, signal an
853 error. If there is a package, narrow the buffer to the file's
854 boundaries."
855 (goto-char (point-min))
856 (unless (re-search-forward "^;;; \\([^ ]*\\)\\.el --- \\(.*\\)$" nil t)
857 (error "Packages lacks a file header"))
858 (let ((file-name (match-string-no-properties 1))
859 (desc (match-string-no-properties 2))
860 (start (line-beginning-position)))
861 (unless (search-forward (concat ";;; " file-name ".el ends here"))
862 (error "Package lacks a terminating comment"))
863 ;; Try to include a trailing newline.
864 (forward-line)
865 (narrow-to-region start (point))
866 (require 'lisp-mnt)
867 ;; Use some headers we've invented to drive the process.
868 (let* ((requires-str (lm-header "package-requires"))
869 (requires (if requires-str
870 (package-read-from-string requires-str)))
871 ;; Prefer Package-Version; if defined, the package author
872 ;; probably wants us to use it. Otherwise try Version.
873 (pkg-version
874 (or (package-strip-rcs-id (lm-header "package-version"))
875 (package-strip-rcs-id (lm-header "version"))))
876 (commentary (lm-commentary)))
877 (unless pkg-version
878 (error
879 "Package lacks a \"Version\" or \"Package-Version\" header"))
880 ;; Turn string version numbers into list form.
881 (setq requires
882 (mapcar
883 (lambda (elt)
884 (list (car elt)
885 (version-to-list (car (cdr elt)))))
886 requires))
887 (vector file-name requires desc pkg-version commentary))))
888
889 (defun package-tar-file-info (file)
890 "Find package information for a tar file.
891 FILE is the name of the tar file to examine.
892 The return result is a vector like `package-buffer-info'."
893 (unless (string-match "^\\(.+\\)-\\([0-9.]+\\)\\.tar$" file)
894 (error "Invalid package name `%s'" file))
895 (let* ((pkg-name (file-name-nondirectory (match-string-no-properties 1 file)))
896 (pkg-version (match-string-no-properties 2 file))
897 ;; Extract the package descriptor.
898 (pkg-def-contents (shell-command-to-string
899 ;; Requires GNU tar.
900 (concat "tar -xOf " file " "
901 pkg-name "-" pkg-version "/"
902 pkg-name "-pkg.el")))
903 (pkg-def-parsed (package-read-from-string pkg-def-contents)))
904 (unless (eq (car pkg-def-parsed) 'define-package)
905 (error "No `define-package' sexp is present in `%s-pkg.el'" pkg-name))
906 (let ((name-str (nth 1 pkg-def-parsed))
907 (version-string (nth 2 pkg-def-parsed))
908 (docstring (nth 3 pkg-def-parsed))
909 (requires (nth 4 pkg-def-parsed))
910 (readme (shell-command-to-string
911 ;; Requires GNU tar.
912 (concat "tar -xOf " file " "
913 pkg-name "-" pkg-version "/README"))))
914 (unless (equal pkg-version version-string)
915 (error "Package has inconsistent versions"))
916 (unless (equal pkg-name name-str)
917 (error "Package has inconsistent names"))
918 ;; Kind of a hack.
919 (if (string-match ": Not found in archive" readme)
920 (setq readme nil))
921 ;; Turn string version numbers into list form.
922 (if (eq (car requires) 'quote)
923 (setq requires (car (cdr requires))))
924 (setq requires
925 (mapcar (lambda (elt)
926 (list (car elt)
927 (version-to-list (cadr elt))))
928 requires))
929 (vector pkg-name requires docstring version-string readme))))
930
931 ;;;###autoload
932 (defun package-install-from-buffer (pkg-info type)
933 "Install a package from the current buffer.
934 When called interactively, the current buffer is assumed to be a
935 single .el file that follows the packaging guidelines; see info
936 node `(elisp)Packaging'.
937
938 When called from Lisp, PKG-INFO is a vector describing the
939 information, of the type returned by `package-buffer-info'; and
940 TYPE is the package type (either `single' or `tar')."
941 (interactive (list (package-buffer-info) 'single))
942 (save-excursion
943 (save-restriction
944 (let* ((file-name (aref pkg-info 0))
945 (requires (aref pkg-info 1))
946 (desc (if (string= (aref pkg-info 2) "")
947 "No description available."
948 (aref pkg-info 2)))
949 (pkg-version (aref pkg-info 3)))
950 ;; Download and install the dependencies.
951 (let ((transaction (package-compute-transaction nil requires)))
952 (package-download-transaction transaction))
953 ;; Install the package itself.
954 (cond
955 ((eq type 'single)
956 (package-unpack-single file-name pkg-version desc requires))
957 ((eq type 'tar)
958 (package-unpack (intern file-name) pkg-version))
959 (t
960 (error "Unknown type: %s" (symbol-name type))))
961 ;; Try to activate it.
962 (package-initialize)))))
963
964 ;;;###autoload
965 (defun package-install-file (file)
966 "Install a package from a file.
967 The file can either be a tar file or an Emacs Lisp file."
968 (interactive "fPackage file name: ")
969 (with-temp-buffer
970 (insert-file-contents-literally file)
971 (cond
972 ((string-match "\\.el$" file)
973 (package-install-from-buffer (package-buffer-info) 'single))
974 ((string-match "\\.tar$" file)
975 (package-install-from-buffer (package-tar-file-info file) 'tar))
976 (t (error "Unrecognized extension `%s'" (file-name-extension file))))))
977
978 (defun package-delete (name version)
979 (let ((dir (package--dir name version)))
980 (if (string-equal (file-name-directory dir)
981 (file-name-as-directory
982 (expand-file-name package-user-dir)))
983 (progn
984 (delete-directory dir t t)
985 (message "Package `%s-%s' deleted." name version))
986 ;; Don't delete "system" packages
987 (error "Package `%s-%s' is a system package, not deleting"
988 name version))))
989
990 (defun package-archive-url (name)
991 "Return the archive containing the package NAME."
992 (let ((desc (cdr (assq (intern-soft name) package-archive-contents))))
993 (cdr (assoc (aref desc (- (length desc) 1)) package-archives))))
994
995 (defun package--download-one-archive (archive file)
996 "Download an archive file FILE from ARCHIVE, and cache it locally."
997 (let* ((archive-name (car archive))
998 (archive-url (cdr archive))
999 (dir (expand-file-name "archives" package-user-dir))
1000 (dir (expand-file-name archive-name dir))
1001 (buffer (url-retrieve-synchronously (concat archive-url file))))
1002 (with-current-buffer buffer
1003 (package-handle-response)
1004 (re-search-forward "^$" nil 'move)
1005 (forward-char)
1006 (delete-region (point-min) (point))
1007 ;; Read the retrieved buffer to make sure it is valid (e.g. it
1008 ;; may fetch a URL redirect page).
1009 (when (listp (read buffer))
1010 (make-directory dir t)
1011 (setq buffer-file-name (expand-file-name file dir))
1012 (let ((version-control 'never))
1013 (save-buffer))))
1014 (kill-buffer buffer)))
1015
1016 (defun package-refresh-contents ()
1017 "Download the ELPA archive description if needed.
1018 This informs Emacs about the latest versions of all packages, and
1019 makes them available for download."
1020 (interactive)
1021 (unless (file-exists-p package-user-dir)
1022 (make-directory package-user-dir t))
1023 (dolist (archive package-archives)
1024 (condition-case nil
1025 (package--download-one-archive archive "archive-contents")
1026 (error (message "Failed to download `%s' archive."
1027 (car archive)))))
1028 (package-read-all-archive-contents))
1029
1030 (defvar package--initialized nil)
1031
1032 ;;;###autoload
1033 (defun package-initialize (&optional no-activate)
1034 "Load Emacs Lisp packages, and activate them.
1035 The variable `package-load-list' controls which packages to load.
1036 If optional arg NO-ACTIVATE is non-nil, don't activate packages."
1037 (interactive)
1038 (setq package-alist nil
1039 package-obsolete-alist nil)
1040 (package-load-all-descriptors)
1041 (package-read-all-archive-contents)
1042 (unless no-activate
1043 (dolist (elt package-alist)
1044 (package-activate (car elt) (package-desc-vers (cdr elt)))))
1045 (setq package--initialized t))
1046
1047 \f
1048 ;;;; Package description buffer.
1049
1050 ;;;###autoload
1051 (defun describe-package (package)
1052 "Display the full documentation of PACKAGE (a symbol)."
1053 (interactive
1054 (let* ((guess (function-called-at-point))
1055 packages val)
1056 (require 'finder-inf nil t)
1057 ;; Load the package list if necessary (but don't activate them).
1058 (unless package--initialized
1059 (package-initialize t))
1060 (setq packages (append (mapcar 'car package-alist)
1061 (mapcar 'car package-archive-contents)
1062 (mapcar 'car package--builtins)))
1063 (unless (memq guess packages)
1064 (setq guess nil))
1065 (setq packages (mapcar 'symbol-name packages))
1066 (setq val
1067 (completing-read (if guess
1068 (format "Describe package (default %s): "
1069 guess)
1070 "Describe package: ")
1071 packages nil t nil nil guess))
1072 (list (if (equal val "") guess (intern val)))))
1073 (if (or (null package) (not (symbolp package)))
1074 (message "No package specified")
1075 (help-setup-xref (list #'describe-package package)
1076 (called-interactively-p 'interactive))
1077 (with-help-window (help-buffer)
1078 (with-current-buffer standard-output
1079 (describe-package-1 package)))))
1080
1081 (defun describe-package-1 (package)
1082 (require 'lisp-mnt)
1083 (let ((package-name (symbol-name package))
1084 (built-in (assq package package--builtins))
1085 desc pkg-dir reqs version installable)
1086 (prin1 package)
1087 (princ " is ")
1088 (cond
1089 ;; Loaded packages are in `package-alist'.
1090 ((setq desc (cdr (assq package package-alist)))
1091 (setq version (package-version-join (package-desc-vers desc)))
1092 (if (setq pkg-dir (package--dir package-name version))
1093 (insert "an installed package.\n\n")
1094 ;; This normally does not happen.
1095 (insert "a deleted package.\n\n")))
1096 ;; Available packages are in `package-archive-contents'.
1097 ((setq desc (cdr (assq package package-archive-contents)))
1098 (setq version (package-version-join (package-desc-vers desc))
1099 installable t)
1100 (if built-in
1101 (insert "a built-in package.\n\n")
1102 (insert "an uninstalled package.\n\n")))
1103 (built-in
1104 (setq desc (cdr built-in)
1105 version (package-version-join (package-desc-vers desc)))
1106 (insert "a built-in package.\n\n"))
1107 (t
1108 (insert "an orphan package.\n\n")))
1109
1110 (insert " " (propertize "Status" 'font-lock-face 'bold) ": ")
1111 (cond (pkg-dir
1112 (insert (propertize "Installed"
1113 'font-lock-face 'font-lock-comment-face))
1114 (insert " in `")
1115 ;; Todo: Add button for uninstalling.
1116 (help-insert-xref-button (file-name-as-directory pkg-dir)
1117 'help-package-def pkg-dir)
1118 (if built-in
1119 (insert "',\n shadowing a "
1120 (propertize "built-in package"
1121 'font-lock-face 'font-lock-builtin-face)
1122 ".")
1123 (insert "'.")))
1124 (installable
1125 (if built-in
1126 (insert (propertize "Built-in." 'font-lock-face 'font-lock-builtin-face)
1127 " Alternate version available -- ")
1128 (insert "Available -- "))
1129 (let ((button-text (if (display-graphic-p) "Install" "[Install]"))
1130 (button-face (if (display-graphic-p)
1131 '(:box (:line-width 2 :color "dark grey")
1132 :background "light grey"
1133 :foreground "black")
1134 'link)))
1135 (insert-text-button button-text 'face button-face 'follow-link t
1136 'package-symbol package
1137 'action 'package-install-button-action)))
1138 (built-in
1139 (insert (propertize "Built-in." 'font-lock-face 'font-lock-builtin-face)))
1140 (t (insert "Deleted.")))
1141 (insert "\n")
1142 (and version (> (length version) 0)
1143 (insert " "
1144 (propertize "Version" 'font-lock-face 'bold) ": " version "\n"))
1145
1146 (setq reqs (if desc (package-desc-reqs desc)))
1147 (when reqs
1148 (insert " " (propertize "Requires" 'font-lock-face 'bold) ": ")
1149 (let ((first t)
1150 name vers text)
1151 (dolist (req reqs)
1152 (setq name (car req)
1153 vers (cadr req)
1154 text (format "%s-%s" (symbol-name name)
1155 (package-version-join vers)))
1156 (cond (first (setq first nil))
1157 ((>= (+ 2 (current-column) (length text))
1158 (window-width))
1159 (insert ",\n "))
1160 (t (insert ", ")))
1161 (help-insert-xref-button text 'help-package name))
1162 (insert "\n")))
1163 (insert " " (propertize "Summary" 'font-lock-face 'bold)
1164 ": " (if desc (package-desc-doc desc)) "\n\n")
1165
1166 (if built-in
1167 ;; For built-in packages, insert the commentary.
1168 (let ((fn (locate-file (concat package-name ".el") load-path
1169 load-file-rep-suffixes))
1170 (opoint (point)))
1171 (insert (or (lm-commentary fn) ""))
1172 (save-excursion
1173 (goto-char opoint)
1174 (when (re-search-forward "^;;; Commentary:\n" nil t)
1175 (replace-match ""))
1176 (while (re-search-forward "^\\(;+ ?\\)" nil t)
1177 (replace-match ""))))
1178 (let ((readme (expand-file-name (concat package-name "-readme.txt")
1179 package-user-dir)))
1180 ;; For elpa packages, try downloading the commentary. If that
1181 ;; fails, try an existing readme file in `package-user-dir'.
1182 (cond ((let ((buffer (ignore-errors
1183 (url-retrieve-synchronously
1184 (concat (package-archive-url package)
1185 package-name "-readme.txt"))))
1186 response)
1187 (when buffer
1188 (with-current-buffer buffer
1189 (setq response (url-http-parse-response))
1190 (if (or (< response 200) (>= response 300))
1191 (setq response nil)
1192 (setq buffer-file-name
1193 (expand-file-name readme package-user-dir))
1194 (delete-region (point-min) (1+ url-http-end-of-headers))
1195 (save-buffer)))
1196 (when response
1197 (insert-buffer-substring buffer)
1198 (kill-buffer buffer)
1199 t))))
1200 ((file-readable-p readme)
1201 (insert-file-contents readme)
1202 (goto-char (point-max))))))))
1203
1204 (defun package-install-button-action (button)
1205 (let ((package (button-get button 'package-symbol)))
1206 (when (y-or-n-p (format "Install package `%s'? " package))
1207 (package-install package)
1208 (revert-buffer nil t)
1209 (goto-char (point-min)))))
1210
1211 \f
1212 ;;;; Package menu mode.
1213
1214 (defvar package-menu-mode-map
1215 (let ((map (copy-keymap special-mode-map))
1216 (menu-map (make-sparse-keymap "Package")))
1217 (set-keymap-parent map button-buffer-map)
1218 (define-key map "\C-m" 'package-menu-describe-package)
1219 (define-key map "n" 'next-line)
1220 (define-key map "p" 'previous-line)
1221 (define-key map "u" 'package-menu-mark-unmark)
1222 (define-key map "\177" 'package-menu-backup-unmark)
1223 (define-key map "d" 'package-menu-mark-delete)
1224 (define-key map "i" 'package-menu-mark-install)
1225 (define-key map "r" 'package-menu-refresh)
1226 (define-key map "~" 'package-menu-mark-obsolete-for-deletion)
1227 (define-key map "x" 'package-menu-execute)
1228 (define-key map "h" 'package-menu-quick-help)
1229 (define-key map "?" 'package-menu-describe-package)
1230 (define-key map [follow-link] 'mouse-face)
1231 (define-key map [mouse-2] 'mouse-select-window)
1232 (define-key map [menu-bar package-menu] (cons "Package" menu-map))
1233 (define-key menu-map [mq]
1234 '(menu-item "Quit" quit-window
1235 :help "Quit package selection"))
1236 (define-key menu-map [s1] '("--"))
1237 (define-key menu-map [mn]
1238 '(menu-item "Next" next-line
1239 :help "Next Line"))
1240 (define-key menu-map [mp]
1241 '(menu-item "Previous" previous-line
1242 :help "Previous Line"))
1243 (define-key menu-map [s2] '("--"))
1244 (define-key menu-map [mu]
1245 '(menu-item "Unmark" package-menu-mark-unmark
1246 :help "Clear any marks on a package and move to the next line"))
1247 (define-key menu-map [munm]
1248 '(menu-item "Unmark backwards" package-menu-backup-unmark
1249 :help "Back up one line and clear any marks on that package"))
1250 (define-key menu-map [md]
1251 '(menu-item "Mark for deletion" package-menu-mark-delete
1252 :help "Mark a package for deletion and move to the next line"))
1253 (define-key menu-map [mi]
1254 '(menu-item "Mark for install" package-menu-mark-install
1255 :help "Mark a package for installation and move to the next line"))
1256 (define-key menu-map [s3] '("--"))
1257 (define-key menu-map [mg]
1258 '(menu-item "Update package list" revert-buffer
1259 :help "Update the list of packages"))
1260 (define-key menu-map [mr]
1261 '(menu-item "Refresh package list" package-menu-refresh
1262 :help "Download the ELPA archive"))
1263 (define-key menu-map [s4] '("--"))
1264 (define-key menu-map [mt]
1265 '(menu-item "Mark obsolete packages" package-menu-mark-obsolete-for-deletion
1266 :help "Mark all obsolete packages for deletion"))
1267 (define-key menu-map [mx]
1268 '(menu-item "Execute actions" package-menu-execute
1269 :help "Perform all the marked actions"))
1270 (define-key menu-map [s5] '("--"))
1271 (define-key menu-map [mh]
1272 '(menu-item "Help" package-menu-quick-help
1273 :help "Show short key binding help for package-menu-mode"))
1274 (define-key menu-map [mc]
1275 '(menu-item "View Commentary" package-menu-view-commentary
1276 :help "Display information about this package"))
1277 map)
1278 "Local keymap for `package-menu-mode' buffers.")
1279
1280 (defvar package-menu-sort-button-map
1281 (let ((map (make-sparse-keymap)))
1282 (define-key map [header-line mouse-1] 'package-menu-sort-by-column)
1283 (define-key map [header-line mouse-2] 'package-menu-sort-by-column)
1284 (define-key map [follow-link] 'mouse-face)
1285 map)
1286 "Local keymap for package menu sort buttons.")
1287
1288 (put 'package-menu-mode 'mode-class 'special)
1289
1290 (define-derived-mode package-menu-mode special-mode "Package Menu"
1291 "Major mode for browsing a list of packages.
1292 Letters do not insert themselves; instead, they are commands.
1293 \\<package-menu-mode-map>
1294 \\{package-menu-mode-map}"
1295 (setq truncate-lines t)
1296 (setq buffer-read-only t)
1297 (set (make-local-variable 'revert-buffer-function) 'package-menu-revert)
1298 (setq header-line-format
1299 (mapconcat
1300 (lambda (pair)
1301 (let ((column (car pair))
1302 (name (cdr pair)))
1303 (concat
1304 ;; Insert a space that aligns the button properly.
1305 (propertize " " 'display (list 'space :align-to column)
1306 'face 'fixed-pitch)
1307 ;; Set up the column button.
1308 (propertize name
1309 'column-name name
1310 'help-echo "mouse-1: sort by column"
1311 'mouse-face 'highlight
1312 'keymap package-menu-sort-button-map))))
1313 ;; We take a trick from buff-menu and have a dummy leading
1314 ;; space to align the header line with the beginning of the
1315 ;; text. This doesn't really work properly on Emacs 21, but
1316 ;; it is close enough.
1317 '((0 . "")
1318 (2 . "Package")
1319 (20 . "Version")
1320 (32 . "Status")
1321 (43 . "Description"))
1322 "")))
1323
1324 (defun package-menu-refresh ()
1325 "Download the Emacs Lisp package archive.
1326 This fetches the contents of each archive specified in
1327 `package-archives', and then refreshes the package menu."
1328 (interactive)
1329 (unless (eq major-mode 'package-menu-mode)
1330 (error "The current buffer is not a Package Menu"))
1331 (package-refresh-contents)
1332 (package--generate-package-list))
1333
1334 (defun package-menu-revert (&optional arg noconfirm)
1335 "Update the list of packages.
1336 This function is the `revert-buffer-function' for Package Menu
1337 buffers. The arguments are ignored."
1338 (interactive)
1339 (unless (eq major-mode 'package-menu-mode)
1340 (error "The current buffer is not a Package Menu"))
1341 (package--generate-package-list))
1342
1343 (defun package-menu-describe-package ()
1344 "Describe the package in the current line."
1345 (interactive)
1346 (let ((name (package-menu-get-package)))
1347 (if name
1348 (describe-package (intern name))
1349 (message "No package on this line"))))
1350
1351 (defun package-menu-mark-internal (what)
1352 (unless (eobp)
1353 (let ((buffer-read-only nil))
1354 (beginning-of-line)
1355 (delete-char 1)
1356 (insert what)
1357 (forward-line))))
1358
1359 ;; fixme numeric argument
1360 (defun package-menu-mark-delete (num)
1361 "Mark a package for deletion and move to the next line."
1362 (interactive "p")
1363 (if (string-equal (package-menu-get-status) "installed")
1364 (package-menu-mark-internal "D")
1365 (forward-line)))
1366
1367 (defun package-menu-mark-install (num)
1368 "Mark a package for installation and move to the next line."
1369 (interactive "p")
1370 (if (string-equal (package-menu-get-status) "available")
1371 (package-menu-mark-internal "I")
1372 (forward-line)))
1373
1374 (defun package-menu-mark-unmark (num)
1375 "Clear any marks on a package and move to the next line."
1376 (interactive "p")
1377 (package-menu-mark-internal " "))
1378
1379 (defun package-menu-backup-unmark ()
1380 "Back up one line and clear any marks on that package."
1381 (interactive)
1382 (forward-line -1)
1383 (package-menu-mark-internal " ")
1384 (forward-line -1))
1385
1386 (defun package-menu-mark-obsolete-for-deletion ()
1387 "Mark all obsolete packages for deletion."
1388 (interactive)
1389 (save-excursion
1390 (goto-char (point-min))
1391 (forward-line 2)
1392 (while (not (eobp))
1393 (if (looking-at ".*\\s obsolete\\s ")
1394 (package-menu-mark-internal "D")
1395 (forward-line 1)))))
1396
1397 (defun package-menu-quick-help ()
1398 "Show short key binding help for package-menu-mode."
1399 (interactive)
1400 (message "n-ext, i-nstall, d-elete, u-nmark, x-ecute, r-efresh, h-elp"))
1401
1402 (define-obsolete-function-alias
1403 'package-menu-view-commentary 'package-menu-describe-package "24.1")
1404
1405 ;; Return the name of the package on the current line.
1406 (defun package-menu-get-package ()
1407 (save-excursion
1408 (beginning-of-line)
1409 (if (looking-at ". \\([^ \t]*\\)")
1410 (match-string-no-properties 1))))
1411
1412 ;; Return the version of the package on the current line.
1413 (defun package-menu-get-version ()
1414 (save-excursion
1415 (beginning-of-line)
1416 (if (looking-at ". [^ \t]*[ \t]*\\([0-9.]*\\)")
1417 (match-string 1))))
1418
1419 (defun package-menu-get-status ()
1420 (save-excursion
1421 (if (looking-at ". [^ \t]*[ \t]*[^ \t]*[ \t]*\\([^ \t]*\\)")
1422 (match-string 1)
1423 "")))
1424
1425 (defun package-menu-execute ()
1426 "Perform marked Package Menu actions.
1427 Packages marked for installation are downloaded and installed;
1428 packages marked for deletion are removed."
1429 (interactive)
1430 (let (install-list delete-list cmd)
1431 (save-excursion
1432 (goto-char (point-min))
1433 (while (not (eobp))
1434 (setq cmd (char-after))
1435 (cond
1436 ((eq cmd ?\s) t)
1437 ((eq cmd ?D)
1438 (push (cons (package-menu-get-package)
1439 (package-menu-get-version))
1440 delete-list))
1441 ((eq cmd ?I)
1442 (push (package-menu-get-package) install-list)))
1443 (forward-line)))
1444 ;; Delete packages, prompting if necessary.
1445 (when delete-list
1446 (if (yes-or-no-p
1447 (if (= (length delete-list) 1)
1448 (format "Delete package `%s-%s'? "
1449 (caar delete-list)
1450 (cdr (car delete-list)))
1451 (format "Delete these %d packages (%s)? "
1452 (length delete-list)
1453 (mapconcat (lambda (elt)
1454 (concat (car elt) "-" (cdr elt)))
1455 delete-list
1456 ", "))))
1457 (dolist (elt delete-list)
1458 (condition-case err
1459 (package-delete (car elt) (cdr elt))
1460 (error (message (cadr err)))))
1461 (error "Aborted")))
1462 (when install-list
1463 (if (yes-or-no-p
1464 (if (= (length install-list) 1)
1465 (format "Install package `%s'? " (car install-list))
1466 (format "Install these %d packages (%s)? "
1467 (length install-list)
1468 (mapconcat 'identity install-list ", "))))
1469 (dolist (elt install-list)
1470 (package-install (intern elt)))))
1471 ;; If we deleted anything, regenerate `package-alist'. This is done
1472 ;; automatically if we installed a package.
1473 (and delete-list (null install-list)
1474 (package-initialize))
1475 (if (or delete-list install-list)
1476 (package-menu-revert)
1477 (message "No operations specified."))))
1478
1479 (defun package-print-package (package version key desc)
1480 (let ((face
1481 (cond ((string= key "built-in") 'font-lock-builtin-face)
1482 ((string= key "available") 'default)
1483 ((string= key "held") 'font-lock-constant-face)
1484 ((string= key "disabled") 'font-lock-warning-face)
1485 ((string= key "installed") 'font-lock-comment-face)
1486 (t ; obsolete, but also the default.
1487 'font-lock-warning-face))))
1488 (insert (propertize " " 'font-lock-face face))
1489 (insert-text-button (symbol-name package)
1490 'face 'link
1491 'follow-link t
1492 'package-symbol package
1493 'action (lambda (button)
1494 (describe-package
1495 (button-get button 'package-symbol))))
1496 (indent-to 20 1)
1497 (insert (propertize (package-version-join version) 'font-lock-face face))
1498 (indent-to 32 1)
1499 (insert (propertize key 'font-lock-face face))
1500 ;; FIXME: this 'when' is bogus...
1501 (when desc
1502 (indent-to 43 1)
1503 (let ((opoint (point)))
1504 (insert (propertize desc 'font-lock-face face))
1505 (upcase-region opoint (min (point) (1+ opoint)))))
1506 (insert "\n")))
1507
1508 (defun package-list-maybe-add (package version status description result)
1509 (unless (assoc (cons package version) result)
1510 (push (list (cons package version) status description) result))
1511 result)
1512
1513 (defvar package-menu-package-list nil
1514 "List of packages to display in the Package Menu buffer.
1515 A value of nil means to display all packages.")
1516
1517 (defvar package-menu-sort-key nil
1518 "Sort key for the current Package Menu buffer.")
1519
1520 (defun package--generate-package-list ()
1521 "Populate the current Package Menu buffer."
1522 (let ((inhibit-read-only t)
1523 info-list name desc hold builtin)
1524 (erase-buffer)
1525 ;; List installed packages
1526 (dolist (elt package-alist)
1527 (setq name (car elt))
1528 (when (or (null package-menu-package-list)
1529 (memq name package-menu-package-list))
1530 (setq desc (cdr elt)
1531 hold (cadr (assq name package-load-list)))
1532 (setq info-list
1533 (package-list-maybe-add
1534 name (package-desc-vers desc)
1535 ;; FIXME: it turns out to be tricky to see if this
1536 ;; package is presently activated.
1537 (if (stringp hold) "held" "installed")
1538 (package-desc-doc desc)
1539 info-list))))
1540
1541 ;; List built-in packages
1542 (dolist (elt package--builtins)
1543 (setq name (car elt))
1544 (when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
1545 (or (null package-menu-package-list)
1546 (memq name package-menu-package-list)))
1547 (setq desc (cdr elt))
1548 (setq info-list
1549 (package-list-maybe-add
1550 name (package-desc-vers desc)
1551 "built-in"
1552 (package-desc-doc desc)
1553 info-list))))
1554
1555 ;; List available and disabled packages
1556 (dolist (elt package-archive-contents)
1557 (setq name (car elt)
1558 desc (cdr elt)
1559 hold (assq name package-load-list))
1560 (when (or (null package-menu-package-list)
1561 (memq name package-menu-package-list))
1562 (setq info-list
1563 (package-list-maybe-add name
1564 (package-desc-vers desc)
1565 (if (and hold (null (cadr hold)))
1566 "disabled"
1567 "available")
1568 (package-desc-doc (cdr elt))
1569 info-list))))
1570 ;; List obsolete packages
1571 (mapc (lambda (elt)
1572 (mapc (lambda (inner-elt)
1573 (setq info-list
1574 (package-list-maybe-add (car elt)
1575 (package-desc-vers
1576 (cdr inner-elt))
1577 "obsolete"
1578 (package-desc-doc
1579 (cdr inner-elt))
1580 info-list)))
1581 (cdr elt)))
1582 package-obsolete-alist)
1583
1584 (setq info-list
1585 (sort info-list
1586 (cond ((string= package-menu-sort-key "Package")
1587 'package-menu--name-predicate)
1588 ((string= package-menu-sort-key "Version")
1589 'package-menu--version-predicate)
1590 ((string= package-menu-sort-key "Description")
1591 'package-menu--description-predicate)
1592 (t ; By default, sort by package status
1593 'package-menu--status-predicate))))
1594
1595 (dolist (elt info-list)
1596 (package-print-package (car (car elt))
1597 (cdr (car elt))
1598 (car (cdr elt))
1599 (car (cdr (cdr elt)))))
1600 (goto-char (point-min))
1601 (set-buffer-modified-p nil)
1602 (current-buffer)))
1603
1604 (defun package-menu--version-predicate (left right)
1605 (let ((vleft (or (cdr (car left)) '(0)))
1606 (vright (or (cdr (car right)) '(0))))
1607 (if (version-list-= vleft vright)
1608 (package-menu--name-predicate left right)
1609 (version-list-< vleft vright))))
1610
1611 (defun package-menu--status-predicate (left right)
1612 (let ((sleft (cadr left))
1613 (sright (cadr right)))
1614 (cond ((string= sleft sright)
1615 (package-menu--name-predicate left right))
1616 ((string= sleft "available") t)
1617 ((string= sright "available") nil)
1618 ((string= sleft "installed") t)
1619 ((string= sright "installed") nil)
1620 ((string= sleft "held") t)
1621 ((string= sright "held") nil)
1622 ((string= sleft "built-in") t)
1623 ((string= sright "built-in") nil)
1624 ((string= sleft "obsolete") t)
1625 ((string= sright "obsolete") nil)
1626 (t (string< sleft sright)))))
1627
1628 (defun package-menu--description-predicate (left right)
1629 (let ((sleft (car (cddr left)))
1630 (sright (car (cddr right))))
1631 (if (string= sleft sright)
1632 (package-menu--name-predicate left right)
1633 (string< sleft sright))))
1634
1635 (defun package-menu--name-predicate (left right)
1636 (string< (symbol-name (caar left))
1637 (symbol-name (caar right))))
1638
1639 (defun package-menu-sort-by-column (&optional e)
1640 "Sort the package menu by the column of the mouse click E."
1641 (interactive "e")
1642 (let* ((pos (event-start e))
1643 (obj (posn-object pos))
1644 (col (if obj
1645 (get-text-property (cdr obj) 'column-name (car obj))
1646 (get-text-property (posn-point pos) 'column-name)))
1647 (buf (window-buffer (posn-window (event-start e)))))
1648 (with-current-buffer buf
1649 (when (eq major-mode 'package-menu-mode)
1650 (setq package-menu-sort-key col)
1651 (package--generate-package-list)))))
1652
1653 (defun package--list-packages (&optional packages)
1654 "Generate and pop to the *Packages* buffer.
1655 Optional PACKAGES is a list of names of packages (symbols) to
1656 list; the default is to display everything in `package-alist'."
1657 (require 'finder-inf nil t)
1658 (let ((buf (get-buffer-create "*Packages*")))
1659 (with-current-buffer buf
1660 (package-menu-mode)
1661 (set (make-local-variable 'package-menu-package-list) packages)
1662 (set (make-local-variable 'package-menu-sort-key) nil)
1663 (package--generate-package-list))
1664 ;; The package menu buffer has keybindings. If the user types
1665 ;; `M-x list-packages', that suggests it should become current.
1666 (switch-to-buffer buf)))
1667
1668 ;;;###autoload
1669 (defun list-packages ()
1670 "Display a list of packages.
1671 Fetches the updated list of packages before displaying.
1672 The list is displayed in a buffer named `*Packages*'."
1673 (interactive)
1674 ;; Initialize the package system if necessary.
1675 (unless package--initialized
1676 (package-initialize t))
1677 (package-refresh-contents)
1678 (package--list-packages))
1679
1680 ;;;###autoload
1681 (defalias 'package-list-packages 'list-packages)
1682
1683 (defun package-list-packages-no-fetch ()
1684 "Display a list of packages.
1685 Does not fetch the updated list of packages before displaying.
1686 The list is displayed in a buffer named `*Packages*'."
1687 (interactive)
1688 (package--list-packages))
1689
1690 (provide 'package)
1691
1692 ;;; package.el ends here