programmatically install packages with emacs27 and above

In the emacs community, this is often a frequent question how can you install packages, while M-x package-list and M-x package-install can be a lot of help, you do not want to do it every time you install emacs, a better way is to add your packages in init.el and let emacs programmatically download and install you most frequent used packages.

Here is a quick step on how you can achieve this with your init.el file is to use package-refresh-contents, but this will only work with the packages already present in your emacs library, basically this will just refresh those packages to their latest version and that’s it.

But how we can download packages which we need on a machine where we are setting emacs for the first time.

The first step is to add your elpa and melpa repositories, I do this by adding the following in my inti.el file, this add the repos and initialize them

;; load emacs package repostiroies.<br>(setq package-archives '(("gnu" . "")<br>("marmalade" . "")<br>("melpa" . "")<br>("elpy" . "")))

next, we initialize the package list code

(when (not package-archive-contents)

next, I have created my own variable for my packages where I keep all my packages

(defvar myPackages

and here the variable is called using package-install function already initialized with package-initialize command

(mapc #'(lambda (package)
    (unless (package-installed-p package)
      (package-install package)))

This provides me with the ability to avoid touching my main package installation code every time and I need to simply update my package list variable, which does package-install in my next emacs run, or I just call eval-buffer and reread the init.el file.

%d bloggers like this: