Creating Auto-Commands

While user-commands allow functions to be written then executed manually as needed, auto-commands allow functions to execute automatically as a result of various events, such as creating a new buffer or pressing a key.

Auto-commands can be created using the Lua API as follows:

vim.api.nvim_create_autocmd(
{event}, -- string or list
{opts} -- table
)

where event is a string or list of strings containing the names of the events that should trigger this auto-command, and opts is a table that accepts a variety of keys and values:

-- opts
{
group, -- optional string or integer
pattern, -- string or list of strings
buffer, -- optional integer
desc, -- optional string,
-- optional lua function
callback = function(args)
-- implement command logic here
end,
command, -- optional string
once, -- bool (default false),
nested -- bool (default false)
}

callback and command are mutually-exclusive, only one can be used at a time. When callback is defined it can be defined as an anonymous function, as shown in the example, or it can be defined elsewhere and passed by reference.

When called, the callback function is passed a table of information:

-- args
{
id, -- integer
event, -- string
group, -- integer or nil
match, -- string
buf, -- integer or nil
file, -- string or nil
}

where:

  • id is the auto-command id
  • event is the name of the event that triggered this auto-command
  • group is the auto-group id or nil
  • match is the name of the entity that matched to trigger this auto-command
  • buf is the number of the buffer that triggered this event or nil
  • file is the name of the buffer that triggered this event or nil