I know that the autocommand
autocmd BufEnter will be triggered every time a buffer is entered. Is there a way to define an
autocmd that will be triggered only the first time a buffer is entered?
One solution is to create a buffer-local variable the first time a buffer is entered, and then check to see if that variable exists the following times that buffer is entered:
autocmd BufEnter * if !exists('b:has_been_entered') | \ let b:has_been_entered = 1 | call input('First time entered!') | endif
*note: this answer is based on this comment
Based on your comment
My workflow usually involves having several buffers open, and switching between them using :bn and :bp. So I'm looking for a way to execute a command when I enter a buffer that I haven't entered before.
If you start Vim with several files, they are not read into memory immediately at startup. The file is only read when you enter the buffer.
So you can use the autocmd event "BufReadPost".
Add the following to your
autocmd BufReadPost * echo strftime("%c")
Then open Vim with multiple existing files.
This will print a timestamp immediately on startup, as you entered the first buffer.
Then it will print a timestamp on every
:bn, as you are entering a yet unvisited buffer (and it's file is read). If you use
:bp to return to a file you already visited, no timestamp will be printed.
Also no timestamp when you reached the end of the list and
:bn brings you to the first file.
- only works when
- the autocmd also fires when you reload a file (with
- is not executed for new files, as there is no file to read yet