Search code examples
vimneovim

Why nvim (vim) adds \< and \> to search pattern and what they means?


I use the * command to fill the search register (/) with the current word (under cursor) so I don't have to paste it into the substitute command. To do a find and replace I can do it quickly like so:

:%s//MyNewValue/g

instead of

:%s/MyOldValue/MyNewValue/g

But sometimes I just want to change one character in the word (like a typo). So after I used * on the word, I do the following:

:%s//<c-r>//g

But I get this:

:%s//\<MyOldValue\>/g

because the / register contains \<MyOldValue\>.

So, here's my question:

How can I get rid of these \< and \>? Or is there a better way to edit all occurrences of a word in vim?

The only way I found, it's to yank the word and paste it twice in the substitute pattern.

yiw
:%s/<c-r>"/<c-r>"/g

Also, what do \< and \> mean and what are they use for?


Solution

  • The \< and \> are word boundaries, see :help \< or :help \>.

    This is similar to the "match whole word" checkbox in the search dialog of graphical editors.

    For example, it will do the following:

    Put the cursor on "foo" and press star.
    It will match foo in this line.
    But not foobar in this one.
    

    If you don't want this, use g* instead of *. It will not add the word boundaries.

    If you're using the :substitute command, you may as well use Ctrl+RCtrl+W (Ctrl+RCtrl+A for words-with-non-word-characters) to add the word under your cursor to the command line. In Vim, one would write it like this:

    :%s/<C-R><C-W>/MyNewValue/