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),gnselects the next match as a text object - Prefix any operator to act on that selection:
dgn— delete the next matchygn— 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
gnworks even when the cursor is on a match — it moves to and selects the next one- Combine with
nto skip a match:njumps past, then.applies the operator to the next - Use
gNto operate on the previous match in reverse:dgN - The dot-repeat with
dgnmirrors the belovedcgnworkflow, just for deletion instead of change