How to automatically install Emacs packages by specifying a list of package names?
I am using package
to manage my Emacs extensions. In order to synchronize my Emacs settings on different computers, I'd like a way to specify a list of package names in .emacs
file and then package
could automatically search and install the packages, so that I don't need to install them manually by calling M-x package-list-packages
. How to do that?
; list the packages you want
(setq package-list '(package1 package2))
; list the repositories containing them
(setq package-archives '(("elpa" . "http://tromey.com/elpa/")
("gnu" . "http://elpa.gnu.org/packages/")
("marmalade" . "http://marmalade-repo.org/packages/")))
; activate all the packages (in particular autoloads)
(package-initialize)
; fetch the list of packages available
(unless package-archive-contents
(package-refresh-contents))
; install the missing packages
(dolist (package package-list)
(unless (package-installed-p package)
(package-install package)))
Based on comments by Profpatsch and answers below:
(defun ensure-package-installed (&rest packages)
"Assure every package is installed, ask for installation if it’s not.
Return a list of installed packages or nil for every skipped package."
(mapcar
(lambda (package)
;; (package-installed-p 'evil)
(if (package-installed-p package)
nil
(if (y-or-n-p (format "Package %s is missing. Install it? " package))
(package-install package)
package)))
packages))
;; make sure to have downloaded archive description.
;; Or use package-archive-contents as suggested by Nicolas Dudebout
(or (file-exists-p package-user-dir)
(package-refresh-contents))
(ensure-package-installed 'iedit 'magit) ; --> (nil nil) if iedit and magit are already installed
;; activate installed packages
(package-initialize)
Emacs 25.1+ will automatically keep track of user-installed packages in the customizable package-selected-packages
variable. package-install
will update the customize variable, and you can install all selected packages with the package-install-selected-packages
function.
Another convenient advantage of this approach is that you can use package-autoremove
to automatically remove packages that are not included in package-selected-packages
(though it will preserve dependencies).
(package-initialize)
(unless package-archive-contents
(package-refresh-contents))
(package-install-selected-packages)
Source: http://endlessparentheses.com/new-in-package-el-in-emacs-25-1-user-selected-packages.html