Repeat the last substitution
Developing efficient workflows in Vim is all about repetition, first and foremost by using .
to repeat the last command. But Vim can also repeat your last substitution. Here’s a few options with subtle differences:
- :& – Repeats last substitution but resets the flags. Also works with just :s.
- :&& – Repeat last substitution with the same flags.
- :%& – Repeat last substitution on entire file, reset flags.
- :%&& – Repeat last substitution on entire file, keep flags.
And here’s a bonus tip that works from normal mode, so even less typing:
- & – From normal mode, this repeats the last substitution but resets flags.
Why would you want to reset the flags when re-running a substitution? After all, the most common flag is /g which is necessary to change all the references on a line at the same time.
Here’s a great reason: You may have read our previous tip about counting occurrences without changing them. We can combine these two tips together to first count the number of occurrences of a pattern and then change them:
:%s/something/newthing/gn
:%&g
In the screencast below, we demonstrate this process. First, we make a substitution but only count the number of occurrences rather than make the replacements. Then we repeat it and actually make the replacements. Finally, we go to another file and repeat the substitution with :%&&
.
