autoreload.lua 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. local core = require "core"
  2. local config = require "core.config"
  3. local Doc = require "core.doc"
  4. local times = setmetatable({}, { __mode = "k" })
  5. local function update_time(doc)
  6. local info = system.get_file_info(doc.filename)
  7. times[doc] = info.modified
  8. end
  9. local function reload_doc(doc)
  10. local fp = io.open(doc.filename, "r")
  11. local text = fp:read("*a")
  12. fp:close()
  13. local sel = { doc:get_selection() }
  14. doc:remove(1, 1, math.huge, math.huge)
  15. doc:insert(1, 1, text:sub(1, -2))
  16. doc:set_selection(table.unpack(sel))
  17. update_time(doc)
  18. doc:clean()
  19. core.log_quiet("Auto-reloaded doc %q", doc.filename)
  20. end
  21. core.add_thread(function()
  22. while true do
  23. -- check all doc modified times
  24. for _, doc in ipairs(core.docs) do
  25. local info = system.get_file_info(doc.filename or "")
  26. if info and times[doc] ~= info.modified then
  27. reload_doc(doc)
  28. end
  29. coroutine.yield()
  30. end
  31. -- wait for next scan
  32. coroutine.yield(config.project_scan_rate)
  33. end
  34. end)
  35. -- patch `Doc.save|load` to store modified time
  36. local load = Doc.load
  37. local save = Doc.save
  38. Doc.load = function(self, ...)
  39. local res = load(self, ...)
  40. update_time(self)
  41. return res
  42. end
  43. Doc.save = function(self, ...)
  44. local res = save(self, ...)
  45. update_time(self)
  46. return res
  47. end