Barbarian Meets Coding

WebDev, UX & a Pinch of Fantasy

2 minutes readexploring-vim

Switfly Operating On Search Matches in Vim and VSCodeVim

Boost Your Coding Fu With Visual Studio Code and Vim The Book

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:

  1. Locate the cucumber with /cucumber
  2. Destroy the cucumber with daW
  3. Type n to go to the next target
  4. Terminate it by repeating the last change with the . command
  5. Repeat from step 3 until all cucumbers have been terminated
  6. 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:

  1. If you are on top of a search match, it selects the match in Visual mode.
  2. If you are in visual mode, it extends your current selection until the end of the next match.
  3. (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:

  1. Search for cucumbers with /cucumber
  2. Apply change to next match dgn
  3. Repeat change to next match with .
  4. Just press . until you’re done
  5. Collect reward much faster

There’s no need to combine n and . because . already includes the next match. Awesome!

Boost Your Coding Fu With Visual Studio Code and Vim The Book Cover image

Jaime González García

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.Jaime González García