I was stumbling over a behaviour in Vim’s substitute-command that I can’t
really follow:
Given the following line of code that contains the && sequence I wanted to
substitute the && with && and a newline:
return a && b
In my first try I simply used s/&& /&&^M/g (^M was inserted via Ctrl-V).
<Enter>
This results in the following code:
return a && &&
b
How exactly is the substitution performed to insert the second &&<space>?
I expected the first (and only match) to be &&<space> and this complete match to be
substituted by &&^M?
The question is not about how to perform the correct substitution – I ended up
using the \zs token to reset the start of the match and only insert the
newline.
I just want to understand why exactly the duplication is introduced.
The problem you’re hitting is that the substitute command treats
&as a special token in the replacement to mean the matched text. You need to escape it.