Following code switches off Vim syntax highlighting for buffers opened after its execution.

autocmd BufAdd * exe 'buffer ' . expand('<abuf>')

Why? Is it bug?

  • 2
    What are you trying to achieve? If you add a new buffer to the buffer list, Vim will switch to it anyway (except :badd etc). – Ralf Feb 9 at 8:58
  • I try to map added buffer with nmap <buffer> on autocmd BufAdd event. For this I need to switch to added buffer with exe 'buffer' . expand('<abuf>') because as said in vim help: "When this autocommand is executed, the current buffer "%" may be different from the buffer being created "<afile>"" – Kirill Bugaev Feb 10 at 4:40

In the comment you describe, that you want to do nmap <buffer> on BufAdd event.

The event BufAdd is very early in the processing, the use-cases for this event are limited. If you want to do buffer local mappings, you should do that with autocmd BufEnter or with autocmd FileType.

autocmd BufEnter *.c   nnoremap <buffer> ...
autocmd FileType c     nnoremap <buffer> ...

BTW: You should prefer noremap to map. See the answer to this question.

Back to your initial question:

Autocmds are blocked while another autocmd is running. In your case, you use an autocmd on BufAdd to immediately switch to the new buffer. Switching to a new buffer needs to read the file and would normally trigger the BufRead and BufEnter autocmds, that are used to determine the file type and hence the syntax highlighting.

As this switch to the buffer is done in the context of an autocmd, the BufRead and BufRead events are not triggered. So no file type detection and hence no syntax highlighting.

Don't use the following in your case, use another autocmd event as described above.

It is possible, to allow nested autocmds by adding the keyword nested, like:

autocmd BufAdd * nested ....

Then autocmds are triggered while the this autocmd is running.

You might want to read :help autocmd-nested for the details.

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.