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).
: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: Construct a string and evaluate it. This is often used to pass arguments to commands: execute 'source' fnameescape('l:path')
You can always execute Vimscript by running each command in command mode (the one you prefix with : ), or by executing the file with commands using a :source command. Historically, Vim scripts have a . vim extension. Here, :so is a short version of :source , and % refers to the currently open file.
Plain old :echo will print output, but it will often disappear by the time your script is done. Using :echom will save the output and let you run :messages to view it later.
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:
Construct a string and evaluate it. This is often used to pass arguments to commands:
execute 'source' fnameescape('l:path')
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With