vimscript call vs. execute

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)
    

  • :call: Call a function.
  • :exec: Executes a string as an Ex command. It has the similar meaning of eval(in javascript, python, etc)

For example:

function! Hello()
   echo "hello, world"
endfunction

call Hello()

exec "call Hello()"

Tags:

Vim

Viml