Vim whole word search - but faster
I know that to search for a whole word in vim you need to type:
/\<word\><CR>
Now, what I would like to do is to map this behaviour to ? (as I never search backwards, and if needed I could search forward and then NN). I.e. I'd like to type:
?word<CR>
and have the same result as above (vim searches the whole word). I've been fiddling开发者_开发技巧 around with vim commands and mappings for some weeks now, but I'm not sure about how to accomplish this one. Thank you for any help.
Update: (insead of ? I use \ now).
I tend to use *
and #
(as suggested by Brian Agnew), but if you want a method that involves typing
?word<CR>
you could do something like this:
function! SearchWord(word)
let @/ = '\<' . a:word . '\>'
normal n
endfunction
command! -nargs=1 SearchWord call SearchWord(<f-args>)
nmap ? :SearchWord
Note there is a space after SearchWord
on the last line.
Explanation:
The mapping will make ?
open up a command prompt and type SearchWord
(including the space). The command makes SearchWord myword
do the equivalent of call SearchWord('myword')
(i.e. it puts the quotes round the argument in order to make it into a string). The function sets the search register @/
equal to your word surrounded by \<
and \>
and then does a normal-mode n
to find the next instance of the contents of the search register.
Of course you lose the benefits of incremental searching if you do this, but hopefully it's useful anyway.
You can search for words under the cursor using *
and #
(forwards and back). g*
and g#
will do the same but finding words containing what's under your cursor initially.
Obviously (!) you need to have found the first instance already for this to work, but it's very effective for successive searches.
Al's solution is very nice, but wouldn't it be simpler to just enter the \<\>
pattern, then move the cursor back twice? This works for me:
nmap ? /\<\><Left><Left>
This way you still get incremental search (kinda).
精彩评论