How do I create a Visual selection for the previous search match instead of the next one?
Answer
gN
Explanation
Most users know gn for selecting the next search match, but its counterpart gN is the real power move when you need to work backward through matches. It creates a Visual selection for the previous match of your current search pattern, letting you apply the same operator in reverse order. This is useful when a forward pass would break surrounding context or when you are reviewing edits from bottom to top.
How it works
gnselects the next match for the current@/search patterngNselects the previous match instead- Once selected, you can apply operators like
c,d,gU,gu, or=to that match - Repeat with
.if your first change used an operator+gNpattern that remains valid
Example
Imagine your cursor is near the end of a file and your search pattern is foo.
foo_one
foo_two
foo_three
From the bottom, use gN to select foo_three, then c to replace it, and continue upward with gN for controlled reverse-order edits.
foo_one
foo_two
bar_three
This directionality helps when later matches depend on earlier untouched text.
Tips
- Pair with
Nto move the cursor backward through matches before usinggN. - Use
:set hlsearchso you can visually confirm the active pattern. - If selection width seems unexpected, check whether your search pattern includes boundaries (
\<,\>) or capture groups.