Earlier in the book, you learned how you can use repeaters to save keystrokes and perform actions faster. Type
n to repeat a search. Type
. to repeat the last change. Use a combination of both
. and you can 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
. 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 on 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
- Destroy the cucumber with
nto go to the next target
- Terminate it by repeating the last change with the
- Repeat from step
3until 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. You can see these two motions as supercharged versions of
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 using just one keystroke. With
. 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
- Apply change to next match
- Repeat change to next match with
- Just press
.until you’re done
- Collect reward much faster
gn there’s no need to combine
. already includes the next match. Awesome!
Written by Jaime González García , Dad, Husband, Front-end software engineer, UX designer, amateur pixel artist, tinkerer and master of the arcane arts. You should follow him on Twitter where he shares useful stuff! (and is funny too).Follow @vintharas