formatters.lua 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. function M.list_supported_names(filetype)
  6. local null_ls_methods = require "null-ls.methods"
  7. local formatter_method = null_ls_methods.internal["FORMATTING"]
  8. local registered_providers = services.list_registered_providers_names(filetype)
  9. return registered_providers[formatter_method] or {}
  10. end
  11. function M.list_available(filetype)
  12. local formatters = {}
  13. local tbl = require "lvim.utils.table"
  14. for _, provider in pairs(null_ls.builtins.formatting) do
  15. if tbl.contains(provider.filetypes or {}, function(ft)
  16. return ft == "*" or ft == filetype
  17. end) then
  18. table.insert(formatters, provider.name)
  19. end
  20. end
  21. return formatters
  22. end
  23. function M.list_configured(formatter_configs)
  24. local formatters, errors = {}, {}
  25. for _, fmt_config in ipairs(formatter_configs) do
  26. local formatter_name = fmt_config.exe:gsub("-", "_")
  27. local formatter = null_ls.builtins.formatting[formatter_name]
  28. if not formatter then
  29. Log:error("Not a valid formatter: " .. fmt_config.exe)
  30. errors[fmt_config.exe] = {} -- Add data here when necessary
  31. else
  32. local formatter_cmd = services.find_command(formatter._opts.command)
  33. if not formatter_cmd then
  34. Log:warn("Not found: " .. formatter._opts.command)
  35. errors[fmt_config.exe] = {} -- Add data here when necessary
  36. else
  37. Log:debug("Using formatter: " .. formatter_cmd)
  38. formatters[fmt_config.exe] = formatter.with {
  39. command = formatter_cmd,
  40. extra_args = fmt_config.args,
  41. filetypes = fmt_config.filetypes,
  42. }
  43. end
  44. end
  45. end
  46. return { supported = formatters, unsupported = errors }
  47. end
  48. function M.setup(formatter_configs)
  49. if vim.tbl_isempty(formatter_configs) then
  50. return
  51. end
  52. local formatters_by_ft = M.list_configured(formatter_configs)
  53. null_ls.register { sources = formatters_by_ft.supported }
  54. end
  55. return M