formatters.lua 2.1 KB

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