macro.lua 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. local core = require "core"
  2. local command = require "core.command"
  3. local keymap = require "core.keymap"
  4. local handled_events = {
  5. ["keypressed"] = true,
  6. ["keyreleased"] = true,
  7. ["textinput"] = true,
  8. }
  9. local state = "stopped"
  10. local event_buffer = {}
  11. local modkeys = {}
  12. local on_event = core.on_event
  13. core.on_event = function(type, ...)
  14. local res = on_event(type, ...)
  15. if state == "recording" and handled_events[type] then
  16. table.insert(event_buffer, { type, ... })
  17. end
  18. return res
  19. end
  20. local function clone(t)
  21. local res = {}
  22. for k, v in pairs(t) do res[k] = v end
  23. return res
  24. end
  25. local function predicate()
  26. return state ~= "playing"
  27. end
  28. command.add(predicate, {
  29. ["macro:toggle-record"] = function()
  30. if state == "stopped" then
  31. state = "recording"
  32. event_buffer = {}
  33. modkeys = clone(keymap.modkeys)
  34. core.log("Recording macro...")
  35. else
  36. state = "stopped"
  37. core.log("Stopped recording macro (%d events)", #event_buffer)
  38. end
  39. end,
  40. ["macro:play"] = function()
  41. state = "playing"
  42. core.log("Playing macro... (%d events)", #event_buffer)
  43. local mk = keymap.modkeys
  44. keymap.modkeys = clone(modkeys)
  45. for _, ev in ipairs(event_buffer) do
  46. on_event(table.unpack(ev))
  47. core.root_view:update()
  48. end
  49. keymap.modkeys = mk
  50. state = "stopped"
  51. end,
  52. })
  53. keymap.add {
  54. ["ctrl+shift+;"] = "macro:toggle-record",
  55. ["ctrl+;"] = "macro:play",
  56. }