vimtricks.wiki Concise Vim tricks, one at a time.

How do I search for the word under the cursor?

Answer

*

Explanation

The * command searches forward for the exact word under the cursor, jumping to the next occurrence. It is one of the fastest ways to find all uses of a variable, function name, or any other word in a file.

How it works

  • * takes the word under the cursor and performs a whole-word forward search
  • It automatically wraps the word with \< and \> word boundaries, so searching for the will not match there or other
  • The search pattern is set in the search register, so you can press n to jump to the next match and N to jump to the previous one
  • All matches are highlighted if hlsearch is enabled

Example

Given the text with the cursor on the first error:

if (error) {
    log(error);
    throw error;
}

Pressing * jumps the cursor to the second error on the log(error) line. Pressing n jumps to the third error on the throw line.

Tips

  • Use # to search backward for the word under the cursor instead
  • Use g* to search forward without word boundaries (partial matches allowed) — g* on the will also match there and other
  • Use g# for the backward equivalent of g*
  • After pressing *, use :%s//replacement/g to replace all occurrences — the search pattern from * is already set
  • Use *N to highlight all occurrences without moving the cursor (search forward then jump back)
  • Combine with cgn for a powerful workflow: press * to find the word, then cgn to change the next match, then . to repeat on subsequent matches

Next

How do I edit multiple lines at once using multiple cursors in Vim?