Search code examples
vimviml

vimscript call vs. execute


In vimscript, what is the difference between call and execute? In what scenarios / use cases should I use one vs the other?

(Disclaimer, I am aware of the extensive online help available within vim - I am seeking a concise answer to this specific question).


Solution

  • From the experience of writing my own plugins and reading the code of others:

    :call is for calling functions, e.g.:

    function! s:foo(id)
        execute 'buffer' a:id
    endfunction
    
    let target_id = 1
    call foo(target_id)
    

    :execute is used for two things:

    1. Construct a string and evaluate it. This is often used to pass arguments to commands:

      execute 'source' fnameescape('l:path')
      
    2. Evaluate the return value of a function (arguably the same):

      function! s:bar(id)
          return 'buffer ' . a:id
      endfunction
      
      let target_id = 1
      execute s:bar(target_id)