问题
I am pretty new to elisp, and i was trying to define a function to set highlight behavior while searching. The goal is: after i-search
, I want to be able to clear the highlight with C-g
, but I want the highlight to remain if I press enter.
So i defined a function in my init.el
as:
(defun keyboard-quit-cleanup ()
"clean up highligh after keyboard quit"
(keyboard-quit)
(lazy-highlight-cleanup))
(global-set-key (kbd "C-g") '(keyboard-quit-cleanup))
how-ever, it doesn't work. What's wrong here?
thanks!
回答1:
Lots of things, I'm afraid :)
Your
global-set-key
is broken:(global-set-key (kbd "C-g") 'keyboard-quit-cleanup)
not:
(global-set-key (kbd "C-g") '(keyboard-quit-cleanup))
(where did you see that??)
Your custom function is not an interactive command, so you cannot bind it to a key. It needs to be:
(defun keyboard-quit-cleanup () "Clean up highlights after keyboard quit." (interactive) ...)
You probably want to use the
FORCE
argument tolazy-highlight-cleanup
You're binding the wrong thing.
C-g is bound to
isearch-abort
in theisearch-mode-map
keymap.(edit: and as per tripleee's comment, messing with the global binding is surely a bad idea. There's definitely some special behaviour associated with it, and you don't want to risk breaking it.)
As you're looking to add an additional behaviour to a standard behaviour, you probably want to use a hook (by preference) or some advice. In this case there's a convenient hook we can use.
See C-hv
isearch-mode-end-hook
RET(add-hook 'isearch-mode-end-hook 'my-isearch-end) (defun my-isearch-end () "Custom behaviours for `isearch-mode-end-hook'." (when isearch-mode-end-hook-quit (lazy-highlight-cleanup t)))
(I assume you have lazy-highlight-cleanup
set to nil
normally, as otherwise the clean-up happens by default.)
来源:https://stackoverflow.com/questions/16804131/define-a-new-function-for-keyboard-quit-and-highlight-clearup