use-package icon indicating copy to clipboard operation
use-package copied to clipboard

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

Open hongyi-zhao opened this issue 3 years ago • 7 comments

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

hongyi-zhao avatar Jun 16 '21 13:06 hongyi-zhao

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.

thomasf avatar Jun 16 '21 19:06 thomasf

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.

hongyi-zhao avatar Jun 16 '21 23:06 hongyi-zhao

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

doolio avatar Oct 31 '21 17:10 doolio

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?

hongyi-zhao avatar Nov 01 '21 02:11 hongyi-zhao

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

doolio avatar Nov 01 '21 08:11 doolio

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

hongyi-zhao avatar Nov 01 '21 09:11 hongyi-zhao

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.

doolio avatar Nov 01 '21 09:11 doolio

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

skangas avatar Nov 13 '22 19:11 skangas