20

& repeats the last :s

But it doesn't repeat with flags, e.g. a global sub:

:s/"/'/g

won't replace in the same way on consecutive lines with &, running :s/"/'/g on the first line here and then & on the second

["first", "second"]
["third", "fourth"]

produces

['first', 'second']
['third", "fourth"]

the global option has been forgotten about when using & on the second line

How can I quickly repeat last substitute command with flags?

(not @: because I may have other commands run after :s)

minseong
  • 2,313
  • 1
  • 19
  • 38

2 Answers2

22

This is exactly what :&& does:

                            *:&&*
[&] Must be the first one: Keep the flags from the previous substitute
    command.  Examples: >
        :&&
        :s/this/that/&
<   Note that `:s` and `:&` don't keep the flags.

There are also the & and g& commands:

                                *&*
&           Synonym for `:s` (repeat last substitute).  Note
            that the flags are not remembered, thus it might
            actually work differently.  You can use `:&&` to keep
            the flags.
                            *g&amp;*

g& Synonym for :%s//~/&amp; (repeat last substitute with last search pattern on all lines with the same flags). For example, when you first do a substitution with :s/pattern/repl/flags and then /search for something else, g&amp; will do :%s/search/repl/flags. Mnemonic: global substitute.

And you could map & to be more like :&&:

nnoremap & :&&<CR>
xnoremap & :&&<CR>
D. Ben Knoble
  • 26,070
  • 3
  • 29
  • 65
Naumann
  • 2,759
  • 1
  • 11
  • 16
  • 4
    Remember that if you already accidentally pressed &, it becomes the last substitution and the flags are gone – doraemon Nov 29 '18 at 04:09
  • 5
    This is correct, but if you add more info the answer will be better. I propose to guide the reader to the relevant help sections, where this is explained immediately. E.g. :help :&. This may also guide readers to learn about things like the mappings & and g&. – Karl Yngve Lervåg Nov 29 '18 at 08:16
  • 5
    I also think that the answers should be full sentences. – Karl Yngve Lervåg Nov 29 '18 at 08:16
0

I usually use a range operation for substitutions. From the example:

["first", "second"]
["third", "fourth"]

Replacing " with ', while cursor is on first line:

:.,+1s/"/'/g

Or from start of file to end of file:

:1,$s/"/'/g

. = current line of file, $ = last line of file, +x = delta line (positive offset), -x = delta line (negative offset), g = globally (all occurrences on line)

RexBarker
  • 101
  • 2