Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM Function Parameter Passing

Tags:

vim

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...

like image 376
David Mokon Bond Avatar asked Mar 07 '13 01:03

David Mokon Bond


2 Answers

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.

like image 53
Hui Zheng Avatar answered Oct 21 '22 05:10

Hui Zheng


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  
like image 29
Peixu Zhu Avatar answered Oct 21 '22 03:10

Peixu Zhu