44 lines
984 B
Lua
44 lines
984 B
Lua
local M = {}
|
|
|
|
M._augroup = nil
|
|
|
|
---Whether autoformatting is enabled.
|
|
---@return boolean
|
|
M.is_enabled = function() return M._augroup ~= nil end
|
|
|
|
---Disable autoformatting.
|
|
M.disable = function()
|
|
if not M.is_enabled() then return end
|
|
vim.api.nvim_del_augroup_by_id(M._augroup)
|
|
M._augroup = nil
|
|
end
|
|
|
|
---Enable autoformatting.
|
|
M.enable = function()
|
|
if M.is_enabled() then return end
|
|
|
|
local ok, formatter = pcall(require, "formatter.format")
|
|
if not ok then
|
|
vim.notify("formatter.nvim not installed!", vim.log.levels.ERROR)
|
|
return
|
|
end
|
|
|
|
M._augroup = vim.api.nvim_create_augroup("fschauen.autoformat", { clear = true })
|
|
vim.api.nvim_create_autocmd("BufWritePost", {
|
|
desc = "Format files on write.",
|
|
group = M._augroup,
|
|
pattern = "*",
|
|
callback = function() formatter.format("", nil, 1, vim.fn.line("$")) end,
|
|
})
|
|
end
|
|
|
|
---Toggle autoformatting.
|
|
M.toggle = function()
|
|
if M.is_enabled() then
|
|
M.disable()
|
|
else
|
|
M.enable()
|
|
end
|
|
end
|
|
|
|
return M
|