diff --git a/lua/user/plugins/lsp/format.lua b/lua/user/plugins/lsp/format.lua index d257e58f..1c42b5c5 100644 --- a/lua/user/plugins/lsp/format.lua +++ b/lua/user/plugins/lsp/format.lua @@ -4,43 +4,34 @@ M.autoformat = true function M.toggle() M.autoformat = not M.autoformat - if M.autoformat then - vim.notify("enabled format on save") - else - vim.notify("disabled format on save") - end + vim.notify(M.autoformat and "Enabled format on save" or "Disabled format on save") end function M.format() - if M.autoformat then - vim.lsp.buf.format() - end -end + local buf = vim.api.nvim_get_current_buf() + local ft = vim.bo[buf].filetype + local have_nls = #require("null-ls.sources").get_available(ft, "NULL_LS_FORMATTING") > 0 -function M.nls_formatter(ft) - local sources = require("null-ls.sources") - local available = sources.get_available(ft, "NULL_LS_FORMATTING") - return #available > 0 + vim.lsp.buf.format({ + bufnr = buf, + filter = function(client) + if have_nls then + return client.name == "null-ls" + end + return client.name ~= "null-ls" + end, + }) end function M.on_attach(client, buf) - local ft = vim.api.nvim_buf_get_option(buf, "filetype") - - local enable = false - if M.nls_formatter(ft) then - enable = client.name == "null-ls" - else - enable = not (client.name == "null-ls") - end - - client.server_capabilities.documentFormattingProvider = enable - -- format on save - if client.server_capabilities.documentFormattingProvider then + if client.supports_method("textDocument/formatting") then vim.api.nvim_create_autocmd("BufWritePre", { group = vim.api.nvim_create_augroup("LspFormat", {}), - buffer = 0, + buffer = buf, callback = function() - M.format() + if M.autoformat then + M.format() + end end, }) end diff --git a/lua/user/plugins/lsp/init.lua b/lua/user/plugins/lsp/init.lua index 0211b583..e11d934e 100644 --- a/lua/user/plugins/lsp/init.lua +++ b/lua/user/plugins/lsp/init.lua @@ -1,4 +1,5 @@ local servers = require("user.plugins.lsp.servers") + local function on_attach(client, bufnr) require("user.plugins.lsp.format").on_attach(client, bufnr) require("user.plugins.lsp.keymaps").on_attach(client, bufnr) @@ -17,14 +18,10 @@ return { "hrsh7th/cmp-nvim-lsp", }, config = function() - ---@type _.lspconfig.options - local defaults = { - on_attach = on_attach, - capabilities = require("cmp_nvim_lsp").default_capabilities(vim.lsp.protocol.make_client_capabilities()), - } - + local capabilities = require("cmp_nvim_lsp").default_capabilities(vim.lsp.protocol.make_client_capabilities()) for server, opts in pairs(servers) do - opts = vim.tbl_deep_extend("force", {}, defaults, opts or {}) + opts.capabilities = capabilities + opts.on_attach = on_attach require("lspconfig")[server].setup(opts) end end,