4

I want to automatically install packages that I don't have locally installed when I initialize Emacs. I use the following code to install some packages.

(package-initialize)
(mapc #'(lambda (pkg)
           (if (not (package-installed-p pkg))
                     (package-install pkg)))
            (list
             'json-mode
             ; ...

However, when loading Emacs, Emacs says the package is not available for installation. However, it exists on the packages buffer.

error: Package `json-mode' is not available for installation

Does anyone know what I am doing wrong?

Scott Weldon
  • 2,695
  • 1
  • 17
  • 31
David
  • 197
  • 3
  • What is your value for `package-archives`? If you haven't MELPA to it yet, you might need to do that first before calling the code in your question: `(add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/") t)` – waymondo May 28 '15 at 14:58
  • @waymondo I have melpa, elpa, and marmalade set before this snippet – David May 28 '15 at 15:00
  • [Related question](http://emacs.stackexchange.com/q/408/115), [related solution](http://emacs.stackexchange.com/a/3239/115). – Kaushal Modi May 28 '15 at 15:23

1 Answers1

6

You most likely need a package-refresh-contents call to download the list of available packages first:

(defvar my-useful-packages
  '(ace-jump-mode ace-jump-buffer ... ))

(defun my-check-and-maybe-install (pkg)
  "Check and potentially install `PKG'."
  (when (not (package-installed-p pkg))
    (when (not (require pkg nil t))
      (package-install pkg))))

(defun my-packages-reset()
  "Reset package manifest to the defined set."
  (interactive)
  (package-refresh-contents)
  (mapc 'my-check-and-maybe-install my-useful-packages))
Kaushal Modi
  • 25,203
  • 3
  • 74
  • 179
stsquad
  • 4,626
  • 28
  • 45