0

I’m doing something like this:

let l:new = substitute(l:old, l:word, l:repl, ‘’)

l:repl comes from an external source and often has an ampersand in it. Is there a way to prevent vim from interpreting the & as a sub-replace-special? The docs say that with nomagic, & is just &, but I can’t find a way to make nomagic apply to the replacement text.

I suppose one way would be to do an additional substitute() to replace & with \&, but that seems… stupid.

Example tests, using l:old = “Hello friends”, l:word = “friends”, and l:repl = Alice & Bob:

  • echo substitute(l:old, l:word, l:repl, ‘’)Hello Alice friends Bob
  • echo substitute(l:old, ‘\M’.l:word, l:repl, ‘’)Hello Alice friends Bob
  • echo substitute(l:old, ‘\V’.l:word, l:repl, ‘’)Hello Alice friends Bob
  • echo substitute(l:old, ‘\V’.l:word, substitute(l:repl, ‘&’, ‘\\&’, ‘’), ‘’)Hello Alice & Bob

So the last one works but is annoying and involves extra function calls.

I’ve also tried using the ex version, but with the same results.

1
  • You might want to make sure you use straight quotes (' and ") instead of the curlies :)
    – D. Ben Knoble
    Aug 6, 2021 at 16:16

1 Answer 1

3

:h 'magic' only applies to :h :s command. :h substitute() function always works as if :set magic (and this is for sure written on its help page).

Therefore one must escape his stuff before invoking substitute(). The preferred option is

:echo substitute(l:old, l:word, escape(l:repl, '&\'), 'g')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.