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

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

  • gn selects the next match for the current @/ search pattern
  • gN selects 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+gN pattern 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 N to move the cursor backward through matches before using gN.
  • Use :set hlsearch so you can visually confirm the active pattern.
  • If selection width seems unexpected, check whether your search pattern includes boundaries (\<, \>) or capture groups.

Next

How do I preview a fuzzy tag match in the preview window without immediately switching buffers?