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?
2 Answers
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 vimrc
:
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.
Note:
- only works when
hidden
is set - the autocmd also fires when you reload a file (with
:e
) - is not executed for new files, as there is no file to read yet
-
I don't think that command works as you've described. That command will print a timestamp every time you visit a buffer, whether it has been entered or not.– TrevorMay 30, 2019 at 22:37
-
-
-
@wxyz I just retested it. Started Vim with 4 existing files and it works as I described. But it has drawbacks: If you reload a file (
:e
) it will fire again. Your own answer doesn't do that and also works with non-existing files.– RalfMay 31, 2019 at 4:48 -
1This answer only works as described if you have
hidden
set. Withnohidden
(Vim's default) the command triggers every time you switch buffer. May 31, 2019 at 6:13
BufReadPost
(akaBufRead
) might be an option.BufReadPost
andBufRead
are triggered every time a buffer is read, not just the first time.: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.