null-ls.lua 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. local status, null_ls = pcall(require, "null-ls")
  2. if not status then
  3. vim.notify("没有找到 null-ls")
  4. return
  5. end
  6. local group = vim.api.nvim_create_augroup("lsp_format_on_save", { clear = false })
  7. local event = "BufWritePre" -- or "BufWritePost"
  8. local async = event == "BufWritePost"
  9. null_ls.setup({
  10. on_attach = function(client, bufnr)
  11. if client.supports_method("textDocument/formatting") then
  12. vim.keymap.set("n", "<Leader>f", function()
  13. vim.lsp.buf.format({ bufnr = vim.api.nvim_get_current_buf() })
  14. end, { buffer = bufnr, desc = "[lsp] format" })
  15. -- format on save
  16. vim.api.nvim_clear_autocmds({ buffer = bufnr, group = group })
  17. vim.api.nvim_create_autocmd(event, {
  18. buffer = bufnr,
  19. group = group,
  20. callback = function()
  21. vim.lsp.buf.format({ bufnr = bufnr, async = async })
  22. end,
  23. desc = "[lsp] format on save",
  24. })
  25. end
  26. if client.supports_method("textDocument/rangeFormatting") then
  27. vim.keymap.set("x", "<Leader>f", function()
  28. vim.lsp.buf.format({ bufnr = vim.api.nvim_get_current_buf() })
  29. end, { buffer = bufnr, desc = "[lsp] format" })
  30. end
  31. end,
  32. })