6

In vim when searching or replacing an exact word you need to type:

\<word\>

to match it exactly, this is cumbersome to type, and I find myself wanting to search/replace exact words a lot more often by default than part of a word. Is there a way to let vim use exact words by default, and then turn this option off/on when necessary?

3
  • 1
    I'm not sure why you thing Vim doesn't match the exact word but I suspect that you mean it doesn't respect the case of your pattern. If that's what you're talking about have a look at :h 'ignorecase' and :h 'smartcase' which change the behavior of the searches and the handling of case in patterns.
    – statox
    Commented May 17, 2016 at 19:10
  • 2
    what I mean is if I search for head it will match header too, this is not what I want most of the time, and to just match head I need \<head\>
    – fYre
    Commented May 17, 2016 at 19:14
  • Oh ok I see. I'm not sure there is a built-in way to change that, let's hope someone can help you.
    – statox
    Commented May 17, 2016 at 19:20

2 Answers 2

7

There isn't an option to treat the whole pattern as word bounded as far as I know. Since you want to replace, that means the text is already in the buffer. You could use * or # on the word in normal mode which performs the \<word\> search for you. Then, cgn to replace the next occurrence, and . to repeat it.

Alternatively, once a search has been made with *, you could use it to start a substitution pattern: :%s//something/g.

This can be made into a key map: nnoremap <leader>r *:%s//. It's used the same way as * except it will also begin a substitution in the command line that you can finish yourself.

3
  • 5
    Also note, that * on a word does \<word\> while g* does word searches. Same workflow applies using <c-r> but now you can chose which type of search and replace you perform.
    – jecxjo
    Commented May 17, 2016 at 20:08
  • 5
    You don't need <C-R>/. Just :%s//replacement/g with an empty search pattern will use the current search pattern, the one you created with *. See :help last-pattern.
    – garyjohn
    Commented May 18, 2016 at 0:25
  • @garyjohn Didn't know that! My life just got a little bit easier. I'll update the answer for posterity.
    – Tommy A
    Commented May 18, 2016 at 2:03
2

You could simply do

:nnoremap / /\<\><left><left>

To make the search key / naturally expand into /\<\> and place the cursor within the search pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.