formatters.lua 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. local M = {}
  2. local formatters_by_ft = {}
  3. local null_ls = require "null-ls"
  4. local services = require "lsp.null-ls.services"
  5. local logger = require("core.log"):get_default()
  6. local function list_names(formatters, options)
  7. options = options or {}
  8. local names = {}
  9. local filter = options.filter or "supported"
  10. for name, _ in pairs(formatters[filter]) do
  11. table.insert(names, name)
  12. end
  13. return names
  14. end
  15. function M.list_supported_names(filetype)
  16. if not formatters_by_ft[filetype] then
  17. return {}
  18. end
  19. return list_names(formatters_by_ft[filetype], { filter = "supported" })
  20. end
  21. function M.list_unsupported_names(filetype)
  22. if not formatters_by_ft[filetype] then
  23. return {}
  24. end
  25. return list_names(formatters_by_ft[filetype], { filter = "unsupported" })
  26. end
  27. function M.list_available(filetype)
  28. local formatters = {}
  29. for _, provider in pairs(null_ls.builtins.formatting) do
  30. -- TODO: Add support for wildcard filetypes
  31. if vim.tbl_contains(provider.filetypes or {}, filetype) then
  32. table.insert(formatters, provider.name)
  33. end
  34. end
  35. return formatters
  36. end
  37. function M.list_configured(formatter_configs)
  38. local formatters, errors = {}, {}
  39. for _, fmt_config in ipairs(formatter_configs) do
  40. local formatter = null_ls.builtins.formatting[fmt_config.exe]
  41. if not formatter then
  42. logger.error("Not a valid formatter:", fmt_config.exe)
  43. errors[fmt_config.exe] = {} -- Add data here when necessary
  44. else
  45. local formatter_cmd = services.find_command(formatter._opts.command)
  46. if not formatter_cmd then
  47. logger.warn("Not found:", formatter._opts.command)
  48. errors[fmt_config.exe] = {} -- Add data here when necessary
  49. else
  50. logger.info("Using formatter:", formatter_cmd)
  51. formatters[fmt_config.exe] = formatter.with { command = formatter_cmd, args = fmt_config.args }
  52. end
  53. end
  54. end
  55. return { supported = formatters, unsupported = errors }
  56. end
  57. function M.setup(filetype, options)
  58. if formatters_by_ft[filetype] and not options.force_reload then
  59. return
  60. end
  61. formatters_by_ft[filetype] = M.list_configured(lvim.lang[filetype].formatters)
  62. null_ls.register { sources = formatters_by_ft[filetype].supported }
  63. end
  64. return M