Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for word under cursor

Tags:

vim

When I use g* or * or g# it will trigger a search for the word under the cursor. However, the cursor moves to the next/previous occurrence of that word. Is there a way to search for the current word without having the cursor moving away?

It is annoying because often I want to press

  1. *
  2. :.,+5s/foo/bar/g

But this problem forces me to do

  1. *
  2. then shift+* (I want to skip this)
  3. my search and replace.
like image 773
Oskar Granlund Avatar asked Apr 30 '18 09:04

Oskar Granlund


People also ask

How to search current word in vim?

To search using Vim/vi, for the current word: In normal mode, you can search forward or backward. One can search forward in vim/vi by pressing / and then typing your search pattern/word. To search backward in vi/vim by pressing ? and then typing your search pattern/word.

How do I delete a word in Vim?

To delete a word, position the cursor at the beginning of the word and type dw . The word and the space it occupied are removed. To delete part of a word, position the cursor on the word to the right of the part to be saved. Type dw to delete the rest of the word.


2 Answers

Is there a way to search for the current word without having the cursor moving away?

The whole point of *, #, and friends is made pretty clear in the documentation: "search forward" or "search backward". Your problem seems to be that you use those commands not for their intended purpose but for a side effect, presumably highlighting all occurrences of the word under the cursor.

Since there's no built-in command for that you will need to map it yourself:

nnoremap <key> *``
nnoremap <anotherkey> #``
...
like image 176
romainl Avatar answered Oct 09 '22 23:10

romainl


Instead of pressing * to fill the search pattern copy the word directly to command line using CTRL-R CTRL-W. I.e.:

:.,+5s/<C-R><C-W>/bar/g
like image 6
phd Avatar answered Oct 10 '22 00:10

phd