How do I visually select the next occurrence of my last search pattern?
Answer
gn
Explanation
The gn motion searches forward for the next match of the last search pattern and visually selects it. This makes it an operator-pending motion, meaning you can combine it with any operator like d, c, or y to act on search matches directly — and because the search is baked into the motion, the entire operation is repeatable with ..
How it works
/pattern<CR>sets your last search patterngnmoves to the next match and visually selects itgNdoes the same but searches backward- When used with an operator, the search-and-select is part of the change, making
.repeat both the search and the operation
Example
Given the text:
foo bar foo baz foo
Search for foo with /foo<CR>. Now press gn — Vim jumps to the next foo and visually selects it. Press <Esc> to cancel the selection.
The real power is with operators. Press dgn to delete the next foo, then press . to delete the next one, and . again for the last:
bar baz
Or use cgn to change the next match: cgnbar<Esc> replaces the next foo with bar, then . repeats the replacement on subsequent matches.
Tips
cgn+.is often called the "dot formula" — it's the most efficient way to do selective search-and-replace without:s- Unlike
n.n.n., thecgnapproach doesn't require pressingnbetween repetitions because the search is part of the change - Use
dgnto delete matches one at a time with. - Combine with
*for a fast workflow: place cursor on a word, press*, thencgnto change the next occurrence gnworks in visual mode too — pressinggnwhile already in visual mode extends the selection to include the next match- If you want to skip a match, press
nto move past it, then.to act on the following one gnrespects thewrapscanoption — if enabled, it wraps around the end of the file