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

How do I use gn as a text object to delete or yank the next search match?

Answer

dgn

Explanation

The gn motion is a versatile text object that selects the next occurrence of the last search pattern. Most Vim users know cgn for changing matches, but gn pairs with any operator — d, y, =, >, and more — enabling a consistent dot-repeatable workflow for bulk operations.

How it works

  • After setting a search pattern (e.g., /todo), gn selects the next match as a text object
  • Prefix any operator to act on that selection:
    • dgn — delete the next match
    • ygn — yank the next match into the unnamed register
    • =gn — auto-indent the next match (useful for code blocks)
    • >gn — indent the next match
  • After dgn, pressing . deletes the next match, and so on

Example

Search for a word:

Buffer: TODO: fix login   TODO: fix signup   TODO: clean up
Search: /TODO: fix

With cursor before the first TODO: fix:

dgn

Result:

Buffer:  login   TODO: fix signup   TODO: clean up

Now press . to delete the next TODO: fix:

Buffer:  login    signup   TODO: clean up

Tips

  • gn works even when the cursor is on a match — it moves to and selects the next one
  • Combine with n to skip a match: n jumps past, then . applies the operator to the next
  • Use gN to operate on the previous match in reverse: dgN
  • The dot-repeat with dgn mirrors the beloved cgn workflow, just for deletion instead of change

Next

What is the difference between the inner word (iw) and inner WORD (iW) text objects in Vim?