How do I register an autocommand that automatically removes itself after firing once?
Answer
autocmd ++once
Explanation
The ++once flag, added in Vim 8.1.1113 and Neovim, makes an autocommand self-destruct after its first execution. This is ideal for deferred initialization, one-time prompts, or actions that should happen on the next event only — without leaving a permanently active autocommand behind.
How it works
autocmd ++once BufEnter * call InitOnFirstEnter()
autocmd— defines an autocommand++once— flag instructing Vim to delete this autocommand after it fires onceBufEnter— the event to listen for*— matches any buffercall InitOnFirstEnter()— the action to run
Without ++once, the autocommand would fire on every subsequent BufEnter. With it, it fires exactly once and disappears.
Example
Showing a welcome message only on the very first buffer open:
autocmd ++once VimEnter * echo "Welcome! Run :help to get started."
A practical use case is lazy initialization — triggering expensive setup code only when a specific buffer is first entered:
autocmd ++once BufReadPost *.py call SetupPython()
Tips
- Combine with
augroupto avoid accumulating orphaned autocommands during re-sourcing your config ++oncecan be combined with++nestedto allow nested event firing on that single execution- Check if the flag is available with
has('autocmd-once')in Vimscript before using it in shared configs