justbur / emacs-which-key

Emacs package that displays available keybindings in popup
GNU General Public License v3.0
1.74k stars 87 forks source link

Docstring of lambdas #279

Open astoff opened 3 years ago

astoff commented 3 years ago

The docstring of anonymous commands is never shown in which-key's popup. If I set

(global-set-key (kbd "C-λ f") 'find-file)

(global-set-key (kbd "C-λ λ") (lambda ()
                                "My little interactive lambda."
                                (interactive)
                                (if (eq (count-windows) 1)
                                    (switch-to-buffer nil)
                                  (other-window 1))))

and type C-λ C-h d, this is what I see:

image

I would in fact suggest that for anonymous commands showing the docstring instead of the uninformative lambda should be the default behavior.

It's maybe not a very common practice to bind keys to lambdas, but I do this for a number of little enhancements to the default commands. The above is my enhanced C-x o. So this is not coming completely out of the blue :-).

justbur commented 3 years ago

This may change in the future, but this is a limitation of how which-key parses keymaps at the moment. When there is a named command, like find-file, I can back out the documentation string by interning the symbol, but there is no way to do that for an unnamed lambda.

You may not be aware that defun returns the symbol name, so you can actually do the following in your example if you wish.

(global-set-key (kbd "C-λ λ") (defun my-lambda ()
                                "My little interactive lambda."
                                (interactive)
                                (if (eq (count-windows) 1)
                                    (switch-to-buffer nil)
                                  (other-window 1))))
astoff commented 3 years ago

Both of the following forms return "test", so I think it should be possible (and easy).

(documentation (lambda () "test"))
(documentation '(lambda () "test"))
justbur commented 3 years ago

It's possible, yes, but it's not easy, because it requires an overhaul of how which-key discovers keys. which-key uses describe-buffer-bindings to discover key bindings, which produces symbol names as strings. I can see that a binding is to a lambda expression, but not which lambda expression.

marczz commented 2 years ago

The following replacement can be used:

(global-set-key (kbd "C-λ λ") '("My little interactive lambda." . (lambda ()
                                "My little interactive lambda."
                                (interactive)
                                (if (eq (count-windows) 1)
                                    (switch-to-buffer nil)
                                  (other-window 1)))))