aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorcukmekerb <cukmekerb+git@gmail.com>2021-04-07 14:45:37 -0700
committerFrancesco Abbate <francesco.bbt@gmail.com>2021-04-09 12:45:36 +0200
commitb812cd913c94685411acfab7ddb07dfd10077d44 (patch)
tree70ee3b6e1809c86bd40ae463f4afeebb62477785
parent536a0ce054319d2ea92c665510afe8a388b043ca (diff)
downloadlite-xl-plugins-b812cd913c94685411acfab7ddb07dfd10077d44.tar.gz
lite-xl-plugins-b812cd913c94685411acfab7ddb07dfd10077d44.zip
added autosave plugin
-rw-r--r--README.md1
-rw-r--r--plugins/autosave.lua45
2 files changed, 46 insertions, 0 deletions
diff --git a/README.md b/README.md
index 0859664..e224d53 100644
--- a/README.md
+++ b/README.md
@@ -13,6 +13,7 @@ with the official version of lite, format the name in italic.*
Plugin | Description
-------|-----------------------------------------
[`autoinsert`](plugins/autoinsert.lua?raw=1) | Automatically inserts closing brackets and quotes
+*[`autosave`](plugins/autosave.lua?raw=1)* | Automatically saves files when they are changed
[`autowrap`](plugins/autowrap.lua?raw=1) | Automatically hardwraps lines when typing
*[`bigclock`](plugins/bigclock.lua?raw=1)* | Shows the current time and date in a view with large text *([screenshot](https://user-images.githubusercontent.com/3920290/82752891-3318df00-9db9-11ea-803f-261d80d5cf53.png))*
[`black`](https://git.sr.ht/~tmpod/black-lite)* | Integrates the [black](https://github.com/psf/black) Python formatter with lite
diff --git a/plugins/autosave.lua b/plugins/autosave.lua
new file mode 100644
index 0000000..11337f7
--- /dev/null
+++ b/plugins/autosave.lua
@@ -0,0 +1,45 @@
+local core = require "core"
+local config = require "core.config"
+local Doc = require "core.doc"
+local DocView = require "core.docview"
+local command = require "core.command"
+-- this is used to detect the wait time
+local last_keypress = os.time()
+-- this exists so that we don't end up with multiple copies of the loop running at once
+local looping = false
+local on_text_change = Doc.on_text_change
+-- the approximate amount of time, in seconds, that it takes to trigger an autosave
+config.autosave_timeout = 1
+
+
+local function loop_for_save()
+ if not looping then
+ looping = true
+ while looping do
+ if os.difftime(os.time(), last_keypress) >= config.autosave_timeout then
+ command.perform "doc:save"
+ -- stop loop
+ looping = false
+ end
+ -- dividing by five is completely arbitrary but it seemed to work well so idc
+ coroutine.yield(config.autosave_timeout)
+ end
+ end
+end
+
+
+local function updatepress()
+ -- set last keypress time to now
+ last_keypress = os.time()
+ -- put loop in coroutine so it doesn't lag out this script
+ core.add_thread(loop_for_save)
+end
+
+
+function Doc:on_text_change(type)
+ -- check if file is saved
+ if core.active_view:get_name() ~= "unsaved*" then
+ updatepress()
+ end
+ return on_text_change(type)
+end