formatters.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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_registered_providers(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. table.sort(formatters)
  22. return 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 formatter_name = fmt_config.exe:gsub("-", "_")
  28. local formatter = null_ls.builtins.formatting[formatter_name]
  29. if not formatter then
  30. Log:error("Not a valid formatter: " .. fmt_config.exe)
  31. errors[fmt_config.exe] = {} -- Add data here when necessary
  32. else
  33. local formatter_cmd = services.find_command(formatter._opts.command)
  34. if not formatter_cmd then
  35. Log:warn("Not found: " .. formatter._opts.command)
  36. errors[fmt_config.exe] = {} -- Add data here when necessary
  37. else
  38. Log:debug("Using formatter: " .. formatter_cmd)
  39. formatters[fmt_config.exe] = formatter.with {
  40. command = formatter_cmd,
  41. extra_args = fmt_config.args,
  42. filetypes = fmt_config.filetypes,
  43. }
  44. end
  45. end
  46. end
  47. return { supported = formatters, unsupported = errors }
  48. end
  49. function M.setup(formatter_configs)
  50. if vim.tbl_isempty(formatter_configs) then
  51. return
  52. end
  53. local formatters_by_ft = M.list_configured(formatter_configs)
  54. null_ls.register { sources = formatters_by_ft.supported }
  55. end
  56. return M