I would like to execute a certain function every time I leave a buffer associated with C++, and another function every time I enter a C++ buffer. I came up with this so far:
" Buffer Leave
augroup myBufferLeave
autocmd BufLeave *.cpp,*.c,*.h call s:ExecuteLeave()
augroup END
" Buffer Enter
augroup myBufferEnter
autocmd BufEnter *.cpp,*.c,*.h call s:ExecuteEnter()
augroup END
Another alternative is to hook into the global BufEnter
event and set a buffer variable or check the current &ft
and execute the appropriate function:
autocmd BufEnter * if &ft = 'cpp' |
\ call s:ExecuteEnter() |
\ endif
autocmd BufLeave * if &ft = 'cpp' |
\ call s:ExecuteLeave() |
\ endif
Is there a cleaner way to do this? Ideally, without tapping into the *
global buffer events. Ideally, I would like to use something like this:
autocmd BufLeave cpp call s:ExecuteLeave()
autocmd BufEnter cpp call s:ExecuteEnter()
Is there a way to pack the *.cpp,*.c,*.h
condition into one single definition such as cpp
? The cpp
definition is a FileType
, but file-types are not triggered on BufEnter
and BufLeave
. If one needs to add another file extension, such as *.CXX
for example, the list will become bloated eventually *.cpp,*.c,*.h, *.CXX, *.C,
and a bit hard to maintain.
:h :map-local
), buffer commands (See:h :command-buffer
), or buffer local settings (See:h setlocal
)?autocmd
pattern you are trying to craft (Spoiler: yourautocmd * if &ft
method is the correct way to do this). My question to you is what are yourExecuteEnter()
/ExecuteLeave()
supposed to be doing? More than likely you are trying to add buffer specific mappings/commands/settings, of which there are better ways methods.