vimtricks.wiki Concise Vim tricks, one at a time.

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 once
  • BufEnter — the event to listen for
  • * — matches any buffer
  • call 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 augroup to avoid accumulating orphaned autocommands during re-sourcing your config
  • ++once can be combined with ++nested to 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

Next

How do I safely use a filename containing special characters in a Vim Ex command?