dotfiles/config/nvim/lua/fschauen/util/autoformat.lua

54 lines
1.2 KiB
Lua

local M = {}
M._augroup = nil
---Whether autoformatting is enabled.
---@return boolean
local is_enabled = function() return M._augroup ~= nil end
---Disable autoformatting.
M.disable = function()
if not is_enabled() then return end
vim.api.nvim_del_augroup_by_id(M._augroup)
M._augroup = nil
end
---Enable autoformatting.
M.enable = function()
if 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 is_enabled() then
M.disable()
else
M.enable()
end
end
---Create a lualine component that shows an icon when autoformatting is enabled.
---@return table component
M.lualine = function()
local icon = require("fschauen.util.icons").ui.Format
return {
function() return icon end,
cond = is_enabled,
}
end
return M