Split out reload functionality to actual document, and added in a thread to check the document, in the cases where it wouldn't be covered by dirwatch.

This commit is contained in:
Adam Harrison 2022-04-28 21:30:55 -04:00 committed by jgmdev
parent d56f4e1ee5
commit 173370694e
3 changed files with 45 additions and 19 deletions

View File

@ -466,6 +466,10 @@ local commands = {
command.perform("doc:save-as")
end
end,
["doc:reload"] = function()
doc():reload()
end,
["file:rename"] = function()
local old_filename = doc().filename

View File

@ -80,6 +80,16 @@ function Doc:load(filename)
end
function Doc:reload()
if self.filename then
local sel = { self:get_selection() }
self:load(self.filename)
self:clean()
self:set_selection(table.unpack(sel))
end
end
function Doc:save(filename, abs_filename)
if not filename then
assert(self.filename, "no filename set to default to")

View File

@ -14,17 +14,8 @@ local function update_time(doc)
end
local function reload_doc(doc)
local fp = io.open(doc.filename, "r")
local text = fp:read("*a")
fp:close()
local sel = { doc:get_selection() }
doc:remove(1, 1, math.huge, math.huge)
doc:insert(1, 1, text:gsub("\r", ""):gsub("\n$", ""))
doc:set_selection(table.unpack(sel))
doc:reload()
update_time(doc)
doc:clean()
core.log_quiet("Auto-reloaded doc \"%s\"", doc.filename)
end
@ -41,20 +32,23 @@ local function check_prompt_reload()
end
end
local function check_if_modified(doc)
local info = system.get_file_info(doc.filename or "")
if info and times[doc] ~= info.modified then
if not doc:is_dirty() then
reload_doc(doc)
else
doc.deferred_reload = true
end
end
end
local on_check = dirwatch.check
function dirwatch:check(change_callback, ...)
on_check(self, function(dir)
for _, doc in ipairs(core.docs) do
if dir == common.dirname(doc.abs_filename) then
local info = system.get_file_info(doc.filename or "")
if info and times[doc] ~= info.modified then
if not doc:is_dirty() then
reload_doc(doc)
else
doc.deferred_reload = true
end
break
end
check_if_modified(doc)
end
end
change_callback(dir)
@ -62,10 +56,28 @@ function dirwatch:check(change_callback, ...)
check_prompt_reload()
end
local set_active_view = core.set_active_view
function core.set_active_view(view)
set_active_view(view)
check_prompt_reload()
if view.doc and view.doc.abs_filename then
local should_poll = true
for i,v in ipairs(core.project_directories) do
if view.doc.abs_filename:find(v.name, 1, true) == 1 and not v.files_limit then
should_poll = false
end
end
if should_poll then
local doc = core.active_view.doc
core.add_thread(function()
while core.active_view.doc == doc do
check_if_modified(doc)
coroutine.yield(0.25)
end
end)
end
end
end
-- patch `Doc.save|load` to store modified time