refactor(lsp): simplified lsp code

This commit is contained in:
Folke Lemaitre 2022-12-30 23:35:27 +01:00
parent 75d8aff979
commit 9ab118aade
No known key found for this signature in database
GPG key ID: 41F8B1FBACAE2040
2 changed files with 22 additions and 34 deletions

View file

@ -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