Passing VIM Function Parameters

I am trying to create a simple vim script function and am having problems. This function should take two input strings and run a search and replace all their instances. I have the following right now:

function! FindAndReplaceAll(from, to) echo a:from :%s/a:from/a:to/gc endfunction 

When I do this:

 :call FindAndReplaceAll("test", "test2") 

Echo a: from works correctly, but:% s ... acts instead of the letters from and to. I noticed that my vim syntax simulator does not even highlight these variables, so I seem to have a basic syntax problem.

My questions:

  • What is the correct syntax with this? I would appreciate an explanation of why, not just an answer. Why is this wrong?
  • In any case, so that it is called as

    : call FindAndReplaceAll (test, test2)

Therefore, I do not need to add quotes ...

+6
source share
2 answers

You need to change

:%s/a:from/a:to/gc

in

exe '%s/' . a:from . '/' . a:to . '/gc'

Your expression is interpreted literally. that is, it will replace the string "a: from" with the string "a: to" in the current buffer.

But you intend to replace the string evaluated with a:from with the string evaluated with a:to . This can be achieved using the built-in function exe[cute] (you can get help by typing :h exe in command line mode).

As for your second question, you need to use quotation marks, otherwise they will be considered variables.

+13
source

The command line should be called with `execute 'instead of direct text:

  function! FindAndReplaceAll(from, to) echo a:from execute "%s/" . a:from . "/" . a:to . "/gc" endfunction 
+1
source

All Articles