I am trying to create a simple vim script function and I am having trouble. This function needs to take two input strings and run the search and replace all instances of them. I have the following right now:
function! FindAndReplaceAll(from, to)
echo a:from
:%s/a:from/a:to/gc
endfunction
When I do:
:call FindAndReplaceAll("test", "test2")
The echo a:from works correctly but the :%s... is acting on the from and to literals instead. I noticed my vim syntax high lighting isn't even highlighting those as variables so I seem to have a basic syntax problem.
My questions are:
Anyway to allow for this to be called as
:call FindAndReplaceAll(test, test2)
So I don't have to add quotes...
You need change
:%s/a:from/a:to/gc
to:
exe '%s/' . a:from . '/' . a:to . '/gc'
Your statement is interpreted literally. i.e. it will replace string "a:from" with string "a:to" in the current buffer.
But what you intend is to replace string evaluated by a:from
with string evaluated by a:to
. That can be achieved by built-in exe[cute]
function(you can get help by typing: :h exe
in command-line mode).
As for your second question, you have to use quotes otherwise they will be taken as variables.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With