diff --git a/config/nvim/lua/fschauen/plugins/formatter.lua b/config/nvim/lua/fschauen/plugins/formatter.lua index ee0eb63..5cb5b51 100644 --- a/config/nvim/lua/fschauen/plugins/formatter.lua +++ b/config/nvim/lua/fschauen/plugins/formatter.lua @@ -21,6 +21,34 @@ local shfmt = function() } 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 { "mhartington/formatter.nvim", @@ -33,14 +61,15 @@ return { keys = { -- stylua: ignore start - { "F", "Format", desc = "󰉼 Format file" }, - { "F", "'<,'>Format", mode = "v", desc = "󰉼 Format selection" }, + { "FT", toggle_format_on_write, desc = "󰉼 [F]ormat on write [T]oggle" }, + { "FF", "Format", desc = "󰉼 [F]ormat [F]ile" }, + { "", "Format", mode = "i", desc = "󰉼 [f]ormat file" }, -- stylua: ignore end }, - opts = function(_, opts) + opts = function() local builtin = require("formatter.filetypes") - return vim.tbl_deep_extend("force", opts or {}, { + return { filetype = { -- stylua: ignore start c = { builtin.c.clangformat }, @@ -55,6 +84,6 @@ return { zsh = { builtin.zsh.beautysh }, -- stylua: ignore end }, - }) + } end, }