jwiegley / use-package

A use-package declaration for simplifying your .emacs
https://jwiegley.github.io/use-package
GNU General Public License v3.0
4.38k stars 260 forks source link

Add convenience macro/arguments for only loading package if it's installed #995

Closed gsingh93 closed 1 year ago

gsingh93 commented 1 year ago

I've been using this macro in my config to only load a package if it's installed:

(defmacro use-package-optional (name &rest args)
  "A wrapper around use-package that will only load the package
if it's installed."
  (declare (indent 1))
  `(use-package ,name
     :if (package-installed-p ',name)
     ,@args))

And I use it like this:

(use-package-optional org-anki
  :after org
  :bind ([(meta shift c)] . 'org-anki-cloze-dwim))

This makes it easy for me to share config files between machines and launch emacs without running into issues when packages aren't installed and without installing a bunch of packages that are unnecessary on some of my machines (which is why I'm not using :ensure t for these packages). I also don't want to defer loading these to solve this issue, as when they are installed I don't want them to be deferred.

I've been finding this useful, so I was wondering if it would make sense to have something like this merged upstream? In this case, it would be better to have an :optional keyword instead of a new macro, I only created a new macro because it was easier for me to implement in my own config files.

skangas commented 1 year ago

Does using :after here cover your use case?

(eval-after-load 'org
  '(progn
     (require 'org-anki nil nil)
     (bind-keys :package org-anki
                ([(meta shift c)]
                 . org-anki-cloze-dwim))))

Which expands to:

(eval-after-load 'org
  '(progn
     (require 'org-anki nil nil)
     (bind-keys :package org-anki
                ([(meta shift c)]
                 . org-anki-cloze-dwim))))
skangas commented 1 year ago

You should just use :if (package-installed-p 'org-anki) in this case. This is documented in the new use-package manual that will be distributed as part of Emacs 29.

gsingh93 commented 1 year ago

It's kind of pointless and redundant to write this:

(use-package org-anki
  :if (package-installed-p 'org-anki)
  :after org
  :bind ([(meta shift c)] . 'org-anki-cloze-dwim))

Instead of this:

(use-package-optional org-anki
  :after org
  :bind ([(meta shift c)] . 'org-anki-cloze-dwim))

But that's fine, this was just a suggestion and I can leave this in my own config.