1

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.

1
  • 5
    What's the error message? Did you define the g:Variable? Commented Jul 5, 2012 at 2:32

2 Answers 2

4

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"

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I was actually using b:Variable inside the file and BufEnter is executed after the Buffer is entered. Hence, I was getting the errors. What I actually wanted was something along the lines of BufEnterPre. Replaced BufEnter in the autocmd with BufReadPre and now everything is humming along quietly :)
0

Actually, BufReadPre doesn't cover all the cases - it triggers only for existing files, when those are read into the buffer. To have autocmd trigger also for new files, one can compose BufReadPre with BufNew like this:

augroup ale_linters
    autocmd!
    autocmd BufNew,BufReadPre * if !exists('b:ale_linters') | let b:ale_linters = 'all' | endif
augroup end

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.