nvim: enable format on write and add key map to toggle it

This commit is contained in:
Fernando Schauenburg 2024-07-20 00:21:29 +02:00
parent 24fe53f1cc
commit b3c8886304

View file

@ -21,6 +21,34 @@ local shfmt = function()
} }
end end
local toggle_format_on_write = (function()
local augroup_id = nil
local verbose = false -- Don't notify on first call.
return function()
if augroup_id then
vim.api.nvim_del_augroup_by_id(augroup_id)
augroup_id = nil
if verbose then
vim.notify("Format on write DISABLED", vim.log.levels.WARN)
end
else
augroup_id = vim.api.nvim_create_augroup("fschauen.format_on_write", { clear = true })
vim.api.nvim_create_autocmd("BufWritePost", {
desc = "Format files on write.",
group = augroup_id,
pattern = "*",
command = ":FormatWrite",
})
if verbose then
vim.notify("Format on write enabled", vim.log.levels.INFO)
end
end
verbose = true -- Notify from second call on.
end
end)()
toggle_format_on_write() -- Enable by default.
return { return {
"mhartington/formatter.nvim", "mhartington/formatter.nvim",
@ -33,14 +61,15 @@ return {
keys = { keys = {
-- stylua: ignore start -- stylua: ignore start
{ "<leader>F", "<cmd>Format<cr>", desc = "󰉼 Format file" }, { "<leader>FT", toggle_format_on_write, desc = "󰉼 [F]ormat on write [T]oggle" },
{ "<leader>F", "<cmd>'<,'>Format<cr>", mode = "v", desc = "󰉼 Format selection" }, { "<leader>FF", "<cmd>Format<cr>", desc = "󰉼 [F]ormat [F]ile" },
{ "<c-f>", "<cmd>Format<cr>", mode = "i", desc = "󰉼 [f]ormat file" },
-- stylua: ignore end -- stylua: ignore end
}, },
opts = function(_, opts) opts = function()
local builtin = require("formatter.filetypes") local builtin = require("formatter.filetypes")
return vim.tbl_deep_extend("force", opts or {}, { return {
filetype = { filetype = {
-- stylua: ignore start -- stylua: ignore start
c = { builtin.c.clangformat }, c = { builtin.c.clangformat },
@ -55,6 +84,6 @@ return {
zsh = { builtin.zsh.beautysh }, zsh = { builtin.zsh.beautysh },
-- stylua: ignore end -- stylua: ignore end
}, },
}) }
end, end,
} }