Search code examples
emacsinstallationpackage

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?


Solution

  • 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)