From bde3bee1773c96212b6c49f009e05174f932c23a Mon Sep 17 00:00:00 2001 From: Steven Arcangeli Date: Wed, 19 Jun 2024 09:22:27 -0400 Subject: fix: LSP fallback behavior when formatters not availble The bug would present itself when there were formatters configured for a filetype that were not available (not installed, or some other issue). This would also happen if the filetype configured an empty list of formatters. The fix was to make sure that we fall back to LSP formatting _either_ if the filetype had no formatters configured, _or_ if none of the configured formatters are available. --- lua/conform/init.lua | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) (limited to 'lua') diff --git a/lua/conform/init.lua b/lua/conform/init.lua index 181953b..0bab347 100644 --- a/lua/conform/init.lua +++ b/lua/conform/init.lua @@ -166,6 +166,12 @@ M.setup = function(opts) end, { desc = "Show information about Conform formatters" }) end +---@param obj any +---@return boolean +local function is_empty_table(obj) + return type(obj) == "table" and vim.tbl_isempty(obj) +end + ---Get the configured formatter filetype for a buffer ---@param bufnr? integer ---@return nil|string filetype or nil if no formatter is configured @@ -177,7 +183,9 @@ local function get_matching_filetype(bufnr) table.insert(filetypes, "_") for _, filetype in ipairs(filetypes) do local ft_formatters = M.formatters_by_ft[filetype] - if ft_formatters then + -- Sometimes people put an empty table here, and that should not count as configuring formatters + -- for a filetype. + if ft_formatters and not is_empty_table(ft_formatters) then return filetype end end @@ -425,12 +433,13 @@ M.format = function(opts, callback) end end + -- check if formatters were configured for this buffer's filetype specifically (i.e. not the "_" + -- or "*" formatters) AND that at least one of the configured formatters is available + local any_formatters = has_filetype_formatters(opts.bufnr) and not vim.tbl_isempty(formatters) + if has_lsp - and ( - opts.lsp_format == "prefer" - or (opts.lsp_format ~= "never" and not has_filetype_formatters(opts.bufnr)) - ) + and (opts.lsp_format == "prefer" or (opts.lsp_format ~= "never" and not any_formatters)) then -- LSP formatting only log.debug("Running LSP formatter on %s", vim.api.nvim_buf_get_name(opts.bufnr)) -- cgit v1.2.3-70-g09d2