Search for Selection in Emacs Evil Mode
Here's the beginning of highlighting my Emacs configuration, and some of the things I've learned by trying to dive deeper into the Emacs mythos.
One thing I've missed from "current" editors is the ability to highlight something, then press CTRL+f to search, and whatever was highlighted is used for the search term. The closest keybinding in Vim is *
, which searches for the current word under the cursor. You could also use some vim-fu to get the desired behavior (e.g. viwyq/p
), but I wanted it to be simpler.
After some searching through evil-search.el
, I decided to copy and modify the function normally used for *
: evil-ex-start-word-search
.
Here's the modified function.
(defun +evil-ex-start-selected-search (direction count)
"Search for the current selection.
The search matches the COUNT-th occurrence of the string. The
DIRECTION argument should be either `forward' or `backward',
determining the search direction."
(let ((search-string (buffer-substring-no-properties (region-beginning) (+ (region-end) 1))))
(let ((regex (regexp-quote search-string)))
(setq evil-ex-search-count count
evil-ex-search-direction direction
evil-ex-search-pattern
(let (evil-ex-search-vim-style-regexp)
(evil-ex-make-search-pattern regex))
evil-ex-search-offset nil
evil-ex-last-was-search t)
(unless (equal regex (car evil-ex-search-history))
(push regex evil-ex-search-history))
(evil-push-search-history regex (eq direction 'forward))
(evil-ex-delete-hl 'evil-ex-search)
(evil-ex-search-next count))))
It's essentially the same as evil-ex-start-word-search
, except for the search-string
definition near the top. It also drops the unbound parameter, since restricting the visual selection to word boundaries didn't really make sense.
Then I copied the motion for *
, in case we wanted to use a count prefix.
(evil-define-motion +evil-ex-search-selection-forward (count)
"Search for the next occurrence of selection."
:jump t
:type exclusive
(interactive (list (prefix-numeric-value current-prefix-arg)))
(+evil-ex-start-selected-search 'forward count)
(evil-exit-visual-state))
And finally, I bound the new motion to *
when in visual mode.
(:general
...
(:states '(visual)
...
"*" #'+evil-ex-search-selection-forward)
Et voilà, search for selection in Emacs Evil. Related configuration here: https://github.com/donniebreve/dotfiles/blob/master/.emacs.d/init/init-evil.el