Easier Auto Command Groups In Neovim
The nvim_create_augroup
and nvim_create_autocmd
APIs in Neovim work
great for creating auto commands, however they sometimes are a bit
cumbersome to use compared to the old Vimscript style augroup
command
where auto commands inside the augroup
block were automatically grouped.
Let’s recreate this same type of experience in Lua!
--- Creates an autocmd group that will automatically group and clear the
--- autocmds created within it.
--- @param name string
--- @param func fun(autocmd: fun(event: any, opts: vim.api.keyset.create_autocmd))
local function augroup(name, func)
local group = vim.api.nvim_create_augroup(name, {})
--- @param event any
--- @param opts vim.api.keyset.create_autocmd
local function autocmd(event, opts)
vim.api.nvim_create_autocmd(
event,
vim.tbl_extend("force", opts, { group = group })
)
end
func(autocmd)
end
We can use our new augroup
function like this:
augroup("mskelton_command_line", function(autocmd)
autocmd("RecordingEnter", { callback = command_line.del })
autocmd("RecordingLeave", { callback = command_line.set })
end)