5

When a vim file is source-ed is it like including the raw text of the file into the current script is it more like executing its contents and returning to the current file?

1 Answer 1

7

Different languages have different semantics for this, so I won't compare, but source in Vim is not exactly like either.

For one, Vim has script-local variables, which, in practice, mean file-local.

Take these examples:

foo.vim (practically lifted as-is from :h script-variable):

let s:counter = 0
function! StartCounting(incr)
    if a:incr
        function MyCounter()
            let s:counter = s:counter + 1
        endfunction
    else
        function MyCounter()
            let s:counter = s:counter - 1
        endfunction
    endif
endfunction
let b:bar=2

bar.vim:

let b:bar=1
source foo.vim
call StartCounting(1)
echo s:counter
echo b:bar
  • If it were simply including the raw text, I'd expect to see s:counter have a non-zero value.
  • If it were executing the contents and returning, I'd expect to see b:bar unchanged.

Instead, the output is:

Error detected while processing /tmp/bar.vim:
line    4:
E121: Undefined variable: s:counter
E15: Invalid expression: s:counter
2

So b:bar is changed by the sourced file, but a script-local variable defined in the sourced file is not directly accessible by the calling file.

3
  • Interesting. It looks like script scopes dynamically nest (like block scopes in Ruby or function scopes in ECMAScript, but dynamically, not lexically). Apr 10, 2017 at 16:41
  • Is there a command similar to source that is equivalent to include, ie treat the file as though this text was inserted here? eg. say you had a some set commands used in some particular session, would there be a command like #insert set_commands_1
    – vfclists
    Apr 11, 2017 at 22:18
  • @vfclists source is enough for set, since set is either global (affects everything in the current Vim session) or buffer-local (affects only the current buffer if used as setlocal). It is not aware of scripts.
    – muru
    Apr 12, 2017 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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