Working with Neovim's Auto-Groups

Thinking back to user-commands, when user-commands are defined they are assigned a name, which is used as a unique identifier for that command. If another user-command is defined with the same name, or if the file that defines the user-command is sourced multiple times, the original definition is simply overwritten.

When auto-commands are created, on the other hand, they attach an event listener that calls the auto-command each time the event occurs. If the auto-command is created multiple times, for example if the file that defines it is sourced multiple times, the auto-command will attach multiple event listeners, causing the auto-command to execute multiple times each time the associated event occurs. While this may be desirable in some cases, it is generally not the intended behavior.

For this reason, Vim has a complementary concept called "auto-groups", which perform two main functions. First, they allow multiple auto-commands to be bundled together so that they can be managed together as a group. Second, the auto-group can be uniquely identified which its associated auto-commands can be managed.

Creating Auto-Groups

vim.api.nvim_create_augroup(
{name}, -- string
{opts} -- optional table
)

where {opts} has a single key:

-- opts
{
clear = true
}

When clear is true (the default) then each time the group is created it will first clear (remove) all auto-commands associated with it, then create them again. By doing so, each auto-command will be attached once. When clear is false, auto-commands can be attached multiple times.

When called, this function creates the auto-group, if it does not already exist, and returns its id. Going forward, the auto-group can be referenced using either this id or its name.

Deleting Auto-Groups

As with other types of commands, auto-groups can be deleted permanently by simply deleting the code creating them from your configuration files and restarting Neovim. But, there are times where deleting the auto-group from the current session is necessary, so let's take a look at how to do that.

As we mentioned earlier, we can address an auto-group by name or by id. Neovim's API allows us to use either to delete an auto-group:

vim.api.nvim_del_augroup_by_id({id})

vim.api.nvim_del_augroup_by_name({name})

When either of these commands are called the auto-group will be deleted, as will all auto-commands associated with it.