jwiegley / use-package

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

About the usage of `:commands` and `:hook`. #937

Closed hongyi-zhao closed 2 years ago

hongyi-zhao commented 3 years ago

I want to know if the following two settings are equivalent.

(use-package company-lsp :commands company-lsp)

and

(use-package company-lsp)
(require 'company-lsp)

Regards, HY

thomasf commented 3 years ago

If you are using the default use-package settings they are not equal.

(use-package company-lsp :commands company-lsp) does not require the package since :commands makes it lazy load when that command is invoked.

The corresponding basic plain Emacs LISP expression would be:

(unless
    (fboundp 'company-lsp)
  (autoload #'company-lsp "company-lsp" nil t))

The plain (use-package company-lsp) line already requires the company-lsp feature so the additional (require ...) does nothing.

hongyi-zhao commented 3 years ago

Thank you for clarification. Then how to simplify/enhance the following code snippet in order to take full advantage of use-package's capabilities and features:

(use-package company)
(add-hook 'after-init-hook 'global-company-mode)

(use-package yasnippet :commands yasnippet)
(add-hook 'prog-mode-hook #'yas-minor-mode)

NB. Although I've noticed the relevant comments, I'm still not quite clear how to convert them into the corresponding use-package snippet based on the :hook method.

doolio commented 3 years ago

The following forms should do what you want:

(use-package company
  :hook (after-init . global-company-mode))
(use-package yasnippet
  :commands yasnippet      ;; Only necessary if a package does not already define an autoload for the specific command
  :hook (prog-mode . yas-minor-mode))
hongyi-zhao commented 3 years ago

By saying something is a command, it means that it is defined by using interactive. But if this thing is not defined with interactive, can I still use :commands on it?

doolio commented 3 years ago

I believe you can but there would be little point in doing so in that case.

hongyi-zhao commented 3 years ago

Do you mean use-package will add the capability of interactive automatically?

doolio commented 3 years ago

No, my understanding is that :commands creates an autoload if one does not exist already. And an autoload speeds up the loading of the package when it is eventually loaded.

skangas commented 2 years ago

It seems like the support questions here were answered (thanks all). I'm therefore closing this issue now.