How do I scope a Vimscript variable to a specific buffer, window, tab, or script to avoid conflicts?
Answer
b: w: t: s:
Explanation
Vimscript variables are prefixed with a one-letter scope identifier followed by a colon. Using the right scope prevents name collisions and ensures variables are automatically cleaned up when their container (buffer, window, tab, or script) is gone.
How it works
| Prefix | Scope | Lifetime |
|---|---|---|
b: |
Buffer-local | Deleted when buffer is wiped |
w: |
Window-local | Deleted when window is closed |
t: |
Tab-local | Deleted when tab is closed |
g: |
Global | Until explicitly deleted or Vim exits |
s: |
Script-local | Limited to the current .vim script file |
l: |
Function-local | Limited to the current function call |
a: |
Function argument | Read-only inside the function |
Example
" In a ftplugin or autocmd:
let b:my_compiler = 'gcc'
" In a plugin script:
let s:plugin_root = expand('<sfile>:h')
" In a function:
function! MyFunc()
let l:tmp = tempname()
" ...
endfunction
Tips
- Always use
s:for variables in plugin scripts — it prevents clashing with user variables and other plugins. b:is ideal for per-filetype state (e.g., storing the last test run command for the current buffer).w:survives buffer switches within the same window, useful for window-level toggles.- Variables with no prefix default to
g:(global), which is rarely what you want in a plugin or function.