I've noticed that after I use :vs <file> or :sp <file> I have no buffer variables defined for this buffer. So I get E121: Undefined variable: b:Var after :echo b:Var there. But in the first opened buffer I have no errors. What am I doing wrong?

  • 1
    I realize that I may have answered a bit too fast: when you do :vs <file> do you mean that you do that on a file you had not open before (in this case my answer is still valid) or do you mean that you opened a buffer with this file in it before, set a buffer variable for this buffer and then use the command with a file which was already in a buffer (in this case I can not reproduce your problem and my answer is not interesting for you)? – statox Dec 12 '17 at 14:03

The important thing to understand is that buffer variables are not inherited from the buffer from where you load/create the new buffer.

Buffer variables can be created manually, but the typical scenario is that a buffer related autocommand will create the variable. In other words, most of the time it's done automatically in ftplugins or in project management plugins.

Corollary: never define buffer local variable in plugin/ files, or in your .vimrc -- unless it's done from a function triggered from a buffer related autocommand. This is the same with buffer local mappings, commands, abbreviations...

| improve this answer | |

The doc (:h b:var) says:

A variable name that is preceded with "b:" is local to the current buffer. Thus you can have several "b:foo" variables, one for each buffer.

When you create a variable prefixed with b: it is local to a buffer so if you create a new buffer the variable will not exist.

If you need a variable accessible from every buffer you can use g: or s: if you are in a script. See :h internal-variables for a description of the different possible scopes:

There are several name spaces for variables.  Which one is to be used is
specified by what is prepended:

                (nothing) In a function: local to a function; otherwise: global
buffer-variable    b:     Local to the current buffer.
window-variable    w:     Local to the current window.
tabpage-variable   t:     Local to the current tab page.
global-variable    g:     Global.
local-variable     l:     Local to a function.
script-variable    s:     Local to a |:source|'ed Vim script.
function-argument  a:     Function argument (only inside a function).
vim-variable       v:     Global, predefined by Vim.
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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