Deleting Auto-Commands

In most cases auto-commands are created in configuration files, so the best way to delete them is often to simply delete them code that creates them and restart Neovim. However, there are times were deleting [[auto-commands] from the current session might be required.

Neovim's Lua API provides two functions for deleting auto-commands.

This first method deletes auto-commands by id:

vim.api.nvim_del_autocmd(id)

where id is the unique id of the auto-command. So how can we find that? There are two ways to do so. First, the auto-command id is returned when the auto-command is created. A pattern for using it might be like this:

local id = vim.api.nvim_create_autocmd({name}, {opts})

... -- other code here

vim.api.nvim_del_autocmd(id)

but that's not so useful in many scenarios, since creating an auto-command and deleting it in the same file doesn't make a lot of sense.

Another option that can be more useful is to list and filter the auto-commands using the vim.api.nvim_get_autocmds function we learned about in the previous section. After executing this command retrieving the list and verifying that the filters are targeting the correct auto-commands, one of two paths can be taken to delete the auto-commands:

  1. if additional logic is required to select specific auto-commands to delete, a loop can iterate over the results, the logic can be applied for each auto-command, then the id field can be used to delete individual auto-commands one by one, or

  2. The opts passed to vim.api.nvim_get_autocmds can be passed to vim.api.nvim_clear_autocmds and all matching auto-commands will get cleared.

Keep in mind that either of these methods will only delete the auto-command for the remainder of the current session; when Neovim starts and sources configuration and code that creates auto-commands will apply them again.