Go to next match and select
In Vim, the previous action can be repeated with the dot command. This is how Vim power users can get so much done so quickly: Structuring their operations into commands that can simply be repeated with a tap of the .
character. The gn
command is one oft-overlooked Vim command (added in version 7.4) that can help build repeatable replacement operations.
To find a matching pattern in Vim, we simply use the /
command. Type /foo
and Vim will find the next reference to “foo” in your text and move your cursor there. From here, we can perform any kind of replacement. For example we could change the word with cw
by typing cwbar<Esc>
to change the word to “bar”. Now, we can press n
to go to the next “foo” match and press .
to repeat the same change.
But gn
gives us an even better way. Read the :help gn
docs for the full details but here’s the short summary: Pressing gn
will jump forward to the next match of the last used search pattern and visually select it. We can prepend this with c
for “change” to get cgn
which will find the next match of the previously used search pattern, select it, and enter insert mode. Then we can type our replacement and press <Esc>
. To repeat this, we only have to press .
instead of n
and .
— shortening our action to a single key press.
Watch the demo to see this in action. Here’s what I do:
/ million
– Finds the first match of ” million”cgn
– Changes the next match of my patternM USD<Esc>
– My replacement pattern- Then I just press
.
to repeat it
There is another variation of this, gN
, which does the same thing in reverse. So if you want to change progressively backwards from your cursor position through the file, use that gN
.
You can combine gn
with all kinds of other commands, too. Try dgn
to delete the next match — repeatable, of course, with just a dot.
I’ve seen this feature before and for some reason always had a disconnect about using it SO never got in the habit of using it. I believe this tip may have fixed that. Thanks.