2023-01-10 10:08:51 +01:00
|
|
|
local Util = require("lazy.core.util")
|
|
|
|
|
2022-12-30 17:30:52 +01:00
|
|
|
local M = {}
|
|
|
|
|
|
|
|
M.autoformat = true
|
|
|
|
|
|
|
|
function M.toggle()
|
2023-02-07 23:15:10 +01:00
|
|
|
if vim.b.autoformat == false then
|
|
|
|
vim.b.autoformat = nil
|
|
|
|
M.autoformat = true
|
|
|
|
else
|
|
|
|
M.autoformat = not M.autoformat
|
|
|
|
end
|
2023-01-10 10:08:51 +01:00
|
|
|
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
|
|
|
|
|
2023-04-16 10:47:36 +02:00
|
|
|
---@param opts? {force?:boolean}
|
|
|
|
function M.format(opts)
|
2022-12-30 23:35:27 +01:00
|
|
|
local buf = vim.api.nvim_get_current_buf()
|
2023-04-16 10:47:36 +02:00
|
|
|
if vim.b.autoformat == false and not (opts and opts.force) then
|
2023-02-07 23:15:10 +01:00
|
|
|
return
|
|
|
|
end
|
2022-12-30 23:35:27 +01:00
|
|
|
local ft = vim.bo[buf].filetype
|
2023-04-28 11:47:22 +02:00
|
|
|
local have_nls = package.loaded["null-ls"]
|
|
|
|
and (#require("null-ls.sources").get_available(ft, "NULL_LS_FORMATTING") > 0)
|
2022-12-30 23:35:27 +01:00
|
|
|
|
2023-01-13 22:46:16 +01:00
|
|
|
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,
|
2023-01-13 22:46:16 +01:00
|
|
|
}, require("lazyvim.util").opts("nvim-lspconfig").format or {}))
|
2022-12-30 17:30:52 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
function M.on_attach(client, buf)
|
2023-02-12 11:43:26 +01:00
|
|
|
-- dont format if client disabled it
|
2023-02-12 12:31:43 +01:00
|
|
|
if
|
|
|
|
client.config
|
|
|
|
and client.config.capabilities
|
|
|
|
and client.config.capabilities.documentFormattingProvider == false
|
|
|
|
then
|
2023-02-12 11:43:26 +01:00
|
|
|
return
|
|
|
|
end
|
|
|
|
|
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", {
|
2023-01-01 13:15:12 +01:00
|
|
|
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
|