command.lua 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. local core = require "core"
  2. local command = {}
  3. command.map = {}
  4. local always_true = function() return true end
  5. function command.add(predicate, map)
  6. predicate = predicate or always_true
  7. if type(predicate) == "string" then
  8. predicate = require(predicate)
  9. end
  10. if type(predicate) == "table" then
  11. local class = predicate
  12. predicate = function() return core.active_view:is(class) end
  13. end
  14. for name, fn in pairs(map) do
  15. assert(not command.map[name], "command already exists: " .. name)
  16. command.map[name] = { predicate = predicate, perform = fn }
  17. end
  18. end
  19. local function capitalize_first(str)
  20. return str:sub(1, 1):upper() .. str:sub(2)
  21. end
  22. function command.prettify_name(name)
  23. return name:gsub(":", ": "):gsub("-", " "):gsub("%S+", capitalize_first)
  24. end
  25. function command.get_all_valid()
  26. local res = {}
  27. for name, cmd in pairs(command.map) do
  28. if cmd.predicate() then
  29. table.insert(res, name)
  30. end
  31. end
  32. return res
  33. end
  34. local function perform(name)
  35. local cmd = command.map[name]
  36. if cmd and cmd.predicate() then
  37. cmd.perform()
  38. return true
  39. end
  40. return false
  41. end
  42. function command.perform(...)
  43. local ok, res = core.try(perform, ...)
  44. return not ok or res
  45. end
  46. function command.add_defaults()
  47. local reg = { "core", "root", "command", "doc", "findreplace" }
  48. for _, name in ipairs(reg) do
  49. require("core.commands." .. name)
  50. end
  51. end
  52. return command