Switfly Operating On Search Matches in Vim and VSCodeVim
In earlier articles of this series you learned how you can repeat searches with n
and repeat the last change with .
. Using a combination of n
and .
you could apply the same change on every single search match with just two keystrokes. Two keystrokes. That’s fast.
But what if I told you there’s a faster way?
Before we get into that, let’s illustrate the n
and .
combo with an example. That’ll give us some fresh background on what we’re trying to achieve and will let us highlight how the new approach improves of this one.
For instance, let’s say we are in the market for destroying cucumbers. We are deadly, rugged cucumber head hunters and there are some cucumbers that need obliteration:
cucumber carrot lettuce
cabbage carrot lettuce cucumber
cucumber cucumber carrot
kale cucumber kale
A way to go about this would be to:
- Locate the cucumber with
/cucumber
- Destroy the cucumber with
daW
- Type
n
to go to the next target - Terminate it by repeating the last change with the
.
command - Repeat from step
3
until all cucumbers have been terminated - Collect reward
It turns out that there’s an even more effective way to perform operations on search matches: gn
and gN
. You can see these two motions as supercharged versions of n
and N
.
gn
works as follows:
- If you are on top of a search match, it selects the match in Visual mode.
- If you are in visual mode, it extends your current selection until the end of the next match.
- (and the best part) If you are in operator pending mode it operates on the next match.
What does this all mean? It means that by taking advantage of gn
we can operate on the next match by using just a keystroke. With gn
the .
command encapsulates the meaning of apply this change to the next match.
In practice, if we were to follow the same example above using the gn
command we would become much more efficient at terminating cucumbers:
- Search for cucumbers with
/cucumber
- Apply change to next match
dgn
- Repeat change to next match with
.
- Just press
.
until you’re done - Collect reward much faster
There’s no need to combine n
and .
because .
already includes the next match. Awesome!
Written by Jaime González García , dad, husband, software engineer, ux designer, amateur pixel artist, tinkerer and master of the arcane arts. You can also find him on Twitter jabbering about random stuff.