Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do a search and replace inside a vim function?

Tags:

function

vim

I'm trying to a write a function that runs search and replace on a range.

I know that one can do :2,5 s/some pattern/something else/ to do this as a vim command, but I can't figure out how this would work inside a function definition. Initially, I tried

function! MyFunc() range
  a:firstline,a:lastline s/some pattern/something else/
endfunction

but when I try to load that function in, I get the error Missing :endfunction. I also tried with call, as I've noticed in other tutorials and examples that sometimes call is used in situations like this. I tried both call a:firstline,a:lastline s/some pattern/something else/ and a:firstline,a:lastline call s/some pattern/something else/. With this, the function loaded. But when I tried calling the function with doing :2,4 call MyFunc(), I get a Missing parenthesis error pointing at the search/replace line.

Can anyone help me with this? I have yet to find any examples of how to do search and replace in a function call.

Thanks

like image 348
metasoarous Avatar asked Jun 12 '26 15:06

metasoarous


1 Answers

You are getting the error Missing :endfunction because function definition is incomplete. Try the one given below, should work

function! MyFunc() range
  execute a:firstline . "," . a:lastline . 's/some pattern/something else/'
endfunction
like image 125
Amit Verma Avatar answered Jun 18 '26 00:06

Amit Verma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!