reddit / emacs

[Asking for ELisp Advice] Binding a local keybind when a minor-mode is on.

yep808 · 2022-02-16 02:24
I'm using evil-mode, lsp-mode, and lsp-ui-mode. I'd like to bind evil-mode's "K" key (originally "evil-lookup") to be "lsp-ui-doc-glance" whenever I am in a lsp-ui-mode enabled buffer. My idea is to run a condition check whenever I'm entering a new buffer, with the buffer-list-update-hook. My code snippet below seems to be working (having tested thoroughly though), but I wonder if there is a more elegant way to achieve this: (add-hook 'buffer-list-update-hook #'(lambda () (when (bound-and-true-p lsp-ui-mode) (define-key evil-motion-state-local-map (kbd "K") #'lsp-ui-doc-glance))))
00-11 · 2022-02-16 03:47
Doesn't the minor mode have a keymap? If it does, just bind your key in that map. (I'm probably not understanding what you're asking...)
yep808 · 2022-02-16 03:58
I see your point. The problem is that I'm using everything under evil-mode, and I want to bind literally the letter "K" to invoke lsp-ui-doc-glance when I'm in evil's normal mode. If I simply do (define-key lsp-ui-mode-map (kbd "K") #'lsp-ui-doc-glance), then I won't be able to type out "K" in evil's insert mode. In short, I am trying to bind this key in both lsp-ui-mode AND evil-mode.
[deleted] · 2022-02-16 04:58
[deleted]
7890yuiop · 2022-02-16 05:00
Untested: (with-eval-after-load "evil" (define-key evil-motion-state-local-map (kbd "K") `(menu-item "" nil :filter ,(lambda (_) (if (bound-and-true-p lsp-ui-mode) #'lsp-ui-doc-glance #'evil-lookup))))) `evil-motion-state-local-map` sounds buffer-local, so that might not be right. I don't know anything much about `evil` or its keymaps though.
yep808 · 2022-02-16 06:22
Thanks! This snippet works fine, I should've wrapped my original snippet with "with-eval-after-load" too. I'd love to read more about "menu-item", could you point me somewhere? I tried searching but didn't really find much. Except [this](https://lists.gnu.org/archive/html/bug-gnu-emacs/2020-12/msg01291.html) thread.
7890yuiop · 2022-02-16 08:09
`C-h i g (elisp)Extended Menu Items` Emacs menus are keymaps, and there's some functionality designed for menus which happens to be very useful for regular key bindings as well. In the case of `:filter` the function returns either the command to use, or `nil` to say "continue looking in other keymaps". Here we're unconditionally returning a command, but which one varies based on `lsp-ui-mode`.
yyoncho · 2022-02-16 12:34
`(evil-define-key 'normal 'lsp-ui-doc-mode-map "K" 'lsp-ui-doc-glance)`
yep808 · 2022-02-16 15:48
Thanks for the reply, but this doesn't seem to work. It'll enable lsp-ui-doc-glance even in non-lsp enabled buffers. Not sure if it's a problem with evil. So far the only snippet I got working reliably is: (with-eval-after-load 'evil (add-hook 'buffer-list-update-hook #'(lambda () (when (bound-and-true-p lsp-ui-mode) (define-key evil-motion-state-local-map (kbd "K") #'lsp-ui-doc-glance)))))