37

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

Xavier T.
  • 40,509
  • 10
  • 68
  • 97
noahlz
  • 10,202
  • 7
  • 56
  • 75

4 Answers4

29
  • :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()"
kev
  • 155,172
  • 47
  • 273
  • 272
  • In what scenarios would I want to use one vs. the other? Or is execute only for when you need to programmatically compose the command to execute? – noahlz Aug 12 '13 at 03:12
  • You can build a command dynamically, and `exec` it. However you can only call a function by name. – kev Aug 12 '13 at 03:21
  • 2
    You might want to show an example of building an ex command using exec and string concatenation. – FDinoff Aug 12 '13 at 03:29
27

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)
    
ib.
  • 27,830
  • 11
  • 80
  • 100
mhinz
  • 3,291
  • 20
  • 20
4

Short answer

You may see call as first evaluate the expression and then discard the result. So only the side effects are useful.

Long answer

Define:

function! Foo()
    echo 'echoed'
    return 'returned'
endfunction

Call:

:call Foo()

Output:

echoed

Execute:

:execute Foo()

Output:

echoed
EXXX: Not an editor command: returned

Execute:

:silent let foo = Foo()
:echo foo

Output:

returned
Cyker
  • 9,946
  • 8
  • 65
  • 93
0

See Switch to last-active tab in VIM

for example

:exe "tabn ".g:lasttab

Where g:lasttab is a global variable to store the current tab number and that number is concatenated with "tabnext" to switch e.g to tab number 3 (If g:lasttab e.g. contains '3' for example)

That whole string >"tabn ".g:lasttab< is evaluated and executed by VIM's exec command.

HTH?

Community
  • 1
  • 1