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