Search code examples
vim

Setting buffer specific variables in Vim


I'm trying to set a buffer-local variable to a global variable if the local variable is not defined using the following autocmd

au BufEnter * if !exists('b:Variable') | let b:Variable = g:Variable | endif

However, b:Variable is not getting defined. What am I doing incorrect here?

EDIT: To rephrase/clarify, b:Variable is being used in the file. The error is that b:Variable is not defined.


Solution

  • First of all, your autocommand is correct. It should work.

    I see some reasons why it could fail:

    • g:Variable is not defined
    • Events are disabled, see :help eventignore (this is unlikely)
    • The autocommand-feature is not supported by your vim version (this is unlikely too). :version must list +autocmd.
    • My favorite: The autocommand is not sourced. Are you sure that your autocommand is active?

    What does

    :verbose autocmd BufEnter

    say? If your autocommand is not listed, it is not active.

    Or try something that is simpler and that gives direct feedback to see if autocommands with BufEnter generally work. For example

    :au BufEnter * echom "Buffer Entered"