LazyVim.LazyVim/lua/lazyvim/plugins/lsp/format.lua

47 lines
1.1 KiB
Lua
Raw Normal View History

local Util = require("lazy.core.util")
2022-12-30 17:30:52 +01:00
local M = {}
M.autoformat = true
function M.toggle()
M.autoformat = not M.autoformat
if M.autoformat then
Util.info("Enabled format on save", { title = "Format" })
else
Util.warn("Disabled format on save", { title = "Format" })
end
2022-12-30 17:30:52 +01:00
end
function M.format()
2022-12-30 23:35:27 +01:00
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
vim.lsp.buf.format(vim.tbl_deep_extend("force", {
2022-12-30 23:35:27 +01:00
bufnr = buf,
filter = function(client)
if have_nls then
return client.name == "null-ls"
end
return client.name ~= "null-ls"
end,
}, require("lazyvim.util").opts("nvim-lspconfig").format or {}))
2022-12-30 17:30:52 +01:00
end
function M.on_attach(client, buf)
2022-12-30 23:35:27 +01:00
if client.supports_method("textDocument/formatting") then
2022-12-30 17:30:52 +01:00
vim.api.nvim_create_autocmd("BufWritePre", {
group = vim.api.nvim_create_augroup("LspFormat." .. buf, {}),
2022-12-30 23:35:27 +01:00
buffer = buf,
2022-12-30 17:30:52 +01:00
callback = function()
2022-12-30 23:35:27 +01:00
if M.autoformat then
M.format()
end
2022-12-30 17:30:52 +01:00
end,
})
end
end
return M