make_add_to_json.lua 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. local h = require("cspell.helpers")
  2. ---@class AddToJSONAction
  3. ---@field diagnostic Diagnostic
  4. ---@field word string
  5. ---@field params GeneratorParams
  6. ---@field cspell CSpellConfigInfo|nil
  7. ---@param opts AddToJSONAction
  8. ---@return CodeAction
  9. return function(opts)
  10. ---@type CSpellSourceConfig
  11. local code_action_config = opts.params:get_config()
  12. local on_success = code_action_config.on_success
  13. local encode_json = code_action_config.encode_json or vim.json.encode
  14. return {
  15. title = 'Add "' .. opts.word .. '" to cspell json file',
  16. action = function()
  17. local cspell = opts.cspell or h.create_cspell_json(opts.params)
  18. if not cspell.config.words then
  19. cspell.config.words = {}
  20. end
  21. table.insert(cspell.config.words, opts.word)
  22. local encoded = encode_json(cspell.config) or ""
  23. local lines = {}
  24. for line in encoded:gmatch("[^\r\n]+") do
  25. table.insert(lines, line)
  26. end
  27. vim.fn.writefile(lines, cspell.path)
  28. -- replace word in buffer to trigger cspell to update diagnostics
  29. h.set_word(opts.diagnostic, opts.word)
  30. if on_success then
  31. on_success(cspell.path, opts.params, "add_to_json")
  32. end
  33. end,
  34. }
  35. end