Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 870
Nick Redmark Avatar asked Nov 28 '22 18:11

Nick Redmark


1 Answers

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.

like image 102
DrAl Avatar answered Dec 04 '22 22:12

DrAl