formatters.lua 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. local M = {}
  2. local null_ls = require "null-ls"
  3. local services = require "lvim.lsp.null-ls.services"
  4. local Log = require "lvim.core.log"
  5. local is_registered = function(name)
  6. local query = {
  7. name = name,
  8. method = require("null-ls").methods.FORMATTING,
  9. }
  10. return require("null-ls.sources").is_registered(query)
  11. end
  12. function M.list_registered(filetype)
  13. local null_ls_methods = require "null-ls.methods"
  14. local formatter_method = null_ls_methods.internal["FORMATTING"]
  15. local registered_providers = services.list_registered_providers_names(filetype)
  16. return registered_providers[formatter_method] or {}
  17. end
  18. function M.list_supported(filetype)
  19. local s = require "null-ls.sources"
  20. local supported_formatters = s.get_supported(filetype, "formatting")
  21. table.sort(supported_formatters)
  22. return supported_formatters
  23. end
  24. function M.list_configured(formatter_configs)
  25. local formatters, errors = {}, {}
  26. for _, fmt_config in ipairs(formatter_configs) do
  27. local name = fmt_config.exe:gsub("-", "_")
  28. local formatter = null_ls.builtins.formatting[name]
  29. if not formatter then
  30. Log:error("Not a valid formatter: " .. fmt_config.exe)
  31. errors[name] = {} -- Add data here when necessary
  32. elseif is_registered(fmt_config.exe) then
  33. Log:trace "Skipping registering the source more than once"
  34. else
  35. local formatter_cmd = services.find_command(formatter._opts.command)
  36. if not formatter_cmd then
  37. Log:warn("Not found: " .. formatter._opts.command)
  38. errors[name] = {} -- Add data here when necessary
  39. else
  40. Log:debug("Using formatter: " .. formatter_cmd)
  41. table.insert(
  42. formatters,
  43. formatter.with {
  44. command = formatter_cmd,
  45. extra_args = fmt_config.args,
  46. filetypes = fmt_config.filetypes,
  47. }
  48. )
  49. end
  50. end
  51. end
  52. return { supported = formatters, unsupported = errors }
  53. end
  54. function M.setup(formatter_configs)
  55. if vim.tbl_isempty(formatter_configs) then
  56. return
  57. end
  58. local formatters = M.list_configured(formatter_configs)
  59. null_ls.register { sources = formatters.supported }
  60. end
  61. return M