If you have made a substitution in either normal mode :s/A/B/g
(the current line) or visual mode :'<,>'s/A/B/g
(lines included in the current selection) and you want to repeat that last substitution, you can:
Move to another line (normal mode) and simply press &
, or if you like, :
-&
-<CR>
(looks like :&
), to affect the current line without highlighting, or
Highlight a range (visual mode) and press :
-&
-<CR>
(looks like :'<,'>&
) to affect the range of lines in the selection.
With my limited knowledge of Vim, this solves several problems. For one, the last visual substitution :'<,'>s/A/B/g
is available as the last command (:
-<UP>
) from both normal and visual mode, but always produces an error from normal mode. (It still refers to the last selection from visual mode - not to the empty selection at the cursor like I assumed - and my example substitution exhausts every match in one pass.) Meanwhile, the last normal mode substitution starts with :s
, not :'<,'>s
, so you would need to modify it to use in visual mode. Finally, &
is available directly from normal mode and so it accepts repetitions and other alternatives to selections, like 2&
for the next two lines, and as user ruohola said, g&
for the entire file.
In both versions, pressing :
then &
works as if you had pressed :
and then retyped s/A/B/
, so the mode you were in last time is irrelevant and only the current cursor line or selection determines the line(s) to be affected. (Note that the trailing flags like g
are cleared too, but come next in this syntax too, as in :&g
/: '<,'>&g
. This is a mixed blessing in my opinion, as you can/must re-specify flags here, and standalone &
doesn't seem to take flags at all. I must be missing something.)
I welcome suggestions and corrections. Most of this comes from experimentation just now so I'm sure there's a lot more to it, but hopefully it helps anyway.