David Mokon Bond
David Mokon Bond

Reputation: 1656

VIM Function Parameter Passing

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:

  1. What is the correct syntax with this? I would appreciate an explanation of why rather than just the answer. Why is the above incorrect?
  2. Anyway to allow for this to be called as

    :call FindAndReplaceAll(test, test2)

So I don't have to add quotes...

Upvotes: 13

Views: 8226

Answers (2)

Hui Zheng
Hui Zheng

Reputation: 10224

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.

Upvotes: 20

Peixu Zhu
Peixu Zhu

Reputation: 2151

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  

Upvotes: 2

Related Questions