Using autocommands with the new neovim api

Table of Contents

Tags:

Define autocommands

Hint

As always, for help and more infos, see:

1:help nvim_create_autocmd()

or neovims online docs:

To define a new autocommand, we simply use the vim.api.nvim_create_autocmd():

 1-- the first parameter represents a list of events we want to bind our command to:
 2-- https://neovim.io/doc/user/autocmd.html#autocmd-events
 3vim.api.nvim_create_autocmd({"BufWritePre", nil}, {
 4    -- pattern allows us to restrict our callback to certain files,
 5    -- https://neovim.io/doc/user/autocmd.html#autocmd-pattern
 6    -- here we restrict the execution to markdown and mdx files:
 7    pattern = {"*.md", "*.mdx"},
 8    -- callback function will be executed once one of the events in the event list occurs
 9    callback = function ()  end,
10})

Run a command before saving a file

1-- run the following just before saving
2vim.api.nvim_create_autocmd("BufWritePre", {
3  pattern = "*.*",
4  callback = function () print("hello world") end,
5  -- you wont see any output due to neovim
6  -- overwriting the output with the written file output
7})

Run Prettier before saving a file

If you followed the configure-coc-nvim guide, you already have the Prettier command defined. We want to run :Prettier on every save for every file type we open. This can be archived by using the nvim_create_autocmd function together with the vim.cmd interface:

1vim.api.nvim_create_autocmd("BufWritePre", {
2  pattern = "*.*",
3  callback = function () vim.cmd(":Prettier") end,
4})