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

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 pattern
  • gn moves to the next match and visually selects it
  • gN does 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., the cgn approach doesn't require pressing n between repetitions because the search is part of the change
  • Use dgn to delete matches one at a time with .
  • Combine with * for a fast workflow: place cursor on a word, press *, then cgn to change the next occurrence
  • gn works in visual mode too — pressing gn while already in visual mode extends the selection to include the next match
  • If you want to skip a match, press n to move past it, then . to act on the following one
  • gn respects the wrapscan option — if enabled, it wraps around the end of the file

Next

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