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

How do I search backward for the word under the cursor?

Answer

#

Explanation

The # command searches backward for the exact word under the cursor, jumping to the previous occurrence. It is the counterpart to *, which searches forward.

How it works

  • # takes the word under the cursor and performs a whole-word backward 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 continue backward or n to go forward
  • All matches are highlighted if hlsearch is enabled

Example

Given the text with the cursor on the last error:

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

Pressing # jumps the cursor backward to the error on the log(error) line. Pressing # again (or N) jumps to the first error in the if statement.

Tips

  • Use * to search forward for the word under the cursor instead
  • Use g# to search backward without word boundaries (partial matches allowed)
  • After pressing #, use n to search forward (opposite direction) and N to continue backward (same direction)
  • Combine with :%s//replacement/g to replace all occurrences — the search pattern from # is already set in the search register
  • Use #N to highlight all occurrences of the word without moving the cursor (search backward then jump back forward)

Next

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