2

I want to write a function which takes two strings this and that as its arguments and replaces all instances of this with that.

So the function should look like:

function! ReplaceThisWithThat(this, that)
       "Main Stuff
.
.
.
endfunction

Can somebody please help?

  • 2
    That might be a dumb question but why do you want to create such a function? The substitute command isn't satisfying enough for you or it's just for vimscript training purpose? – statox Jun 6 '15 at 12:06
  • 2
    It's just for training purpose. – caffeinemachine Jun 6 '15 at 18:39
  • oh ok then have fun with that :) – statox Jun 7 '15 at 7:55
7

You can do it very simply with:

function! ReplaceThisWithThat(this, that)
    execute "%s/" . a:this . "/" . a:that . "/g"
endfunction

Which will substitute every occurrence of a:this with a:that in the whole buffer.

If you want to perform that substitution on the content of some variable or register, you can use substitute() in your function:

function! ReplaceThisWithThat(something, this, that)
    return substitute(a:something, a:this, a:that, "g")
endfunction

which doesn't make much sense.

That said, everything you need to know is in :help eval.txt.

1

Function arguments have a: prefix.

function! ReplaceThisWithThat(this, that)
       "Main Stuff
 echo a:this "named argument 'this'
 echo a:that

 echo a:0 " postioned first argument
endfunction
  • But echo is not going to make any replacements for me right? How do I do the search and replace thingy with variables? – caffeinemachine Jun 6 '15 at 8:29
  • @caffeinemachine your title queston only asks about how arguments work, which this answer covers. It isn't very clear from your question that you mostly care about the actual replacement. Perhaps consider re-wording your title and adding clarification to the question. – John O'M. Jun 6 '15 at 15:37
  • I agree. The title and the body of the question were rather different. But the problem is now solved. – caffeinemachine Jun 6 '15 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.