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 forthewill not matchthereorother - The search pattern is set in the search register, so you can press
nto jump to the next match andNto jump to the previous one - All matches are highlighted if
hlsearchis 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*onthewill also matchthereandother - Use
g#for the backward equivalent ofg* - After pressing
*, use:%s//replacement/gto replace all occurrences — the search pattern from*is already set - Use
*Nto highlight all occurrences without moving the cursor (search forward then jump back) - Combine with
cgnfor a powerful workflow: press*to find the word, thencgnto change the next match, then.to repeat on subsequent matches