LoginSignup
10

More than 5 years have passed since last update.

Emacs 起動時にパッケージを自動でインストールする方法

Posted at

イカした Emacs Lisp をご紹介したい。

とはいっても私が書いたわけではなくここにあるものを脳死でコピペしただけなのだが。

使い方

(require 'package)
(setq package-archives
  '(("gnu" . "https://elpa.gnu.org/packages/")
     ("melpa" . "https://melpa.org/packages/")
     ("org" . "http://orgmode.org/elpa/")))
(package-initialize)

(defun require-package (package &optional min-version no-refresh)
  "Install given PACKAGE, optionally requiring MIN-VERSION.
If NO-REFRESH is non-nil, the available package lists will not be
re-downloaded in order to locate PACKAGE."
  (if (package-installed-p package min-version)
    t
    (if (or (assoc package package-archive-contents) no-refresh)
      (if (boundp 'package-selected-packages)
        ;; Record this as a package the user installed explicitly
        (package-install package nil)
        (package-install package))
      (progn
        (package-refresh-contents)
        (require-package package min-version t)))))

(defun maybe-require-package (package &optional min-version no-refresh)
  "Try to install PACKAGE, and return non-nil if successful.
In the event of failure, return nil and print a warning message.
Optionally require MIN-VERSION.  If NO-REFRESH is non-nil, the
available package lists will not be re-downloaded in order to
locate PACKAGE."
  (condition-case err
    (require-package package min-version no-refresh)
    (error
      (message "Couldn't install optional package `%s': %S" package err)
      nil)))

init.el の最初らへんに追加して準備完了

使用例

multiple-cursors というパッケージを使いたいとする。

ただ追加するだけでいい場合は、

(require-package 'multiple-cursors)

これだけで、 emacs 起動時にパッケージが存在しなければダウンロードを試みてくれる。

追加した上で更に設定したい場合は、

(when (maybe-require-package 'multiple-cursors)
  (global-set-key (kbd "C-<") 'mc/mark-previous-like-this)
  (global-set-key (kbd "C->") 'mc/mark-next-like-this))

とすると multiple-cursors のダウンロードに成功した場合のみ下の global-set-key が呼ばれる。

素敵

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10