summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFrank LENORMAND <lenormf@gmail.com>2015-07-30 18:43:57 +0300
committerFrank LENORMAND <lenormf@gmail.com>2015-07-30 18:43:57 +0300
commitcf149b798599fc9a1f53be07790501b460b82a74 (patch)
tree5adc65d1c8c1506777f60eff73561acc34366932
parent6b06d77490d873afb4e9a61405c1265a228b8b20 (diff)
Add an automatic backup restoration script that handles .kak.XXXXXX files
-rw-r--r--rc/autorestore.kak53
1 files changed, 53 insertions, 0 deletions
diff --git a/rc/autorestore.kak b/rc/autorestore.kak
new file mode 100644
index 00000000..ae9ace65
--- /dev/null
+++ b/rc/autorestore.kak
@@ -0,0 +1,53 @@
+## If set to true, backups will be removed as soon as they have been restored
+decl bool autorestore_purge_restored true
+
+def -hidden _autorestore-restore-buffer %{
+ nop %sh{
+ buffer_basename="${kak_bufname##*/}"
+ buffer_dirname=$(dirname "${kak_bufname}")
+
+ ## Find the name of the latest backup created for the buffer that was open
+ latest_backup_path=$(find "${buffer_dirname}" -type f -readable -name ".${buffer_basename}.kak.*" -printf '%A@/%p\n' 2>/dev/null \
+ | sort -n -t. -k1 | sed -nr 's/^.+\///;$p')
+ test ! -z "${latest_backup_path}" || exit
+
+ ## Replace the content of the buffer with the content of the backup file
+ echo "
+ exec -draft %{ %d!cat<space>${latest_backup_path}<ret>d }
+ echo -color Information Backup restored
+ "
+
+ ## If the backup file has to be removed, issue the command once
+ ## the current buffer has been saved
+ ## If the autorestore_purge_restored option has been unset right after the
+ ## buffer was restored, do not remove the backup
+ echo "
+ hook -group autorestore global BufWritePost (.+/)?${kak_bufname} %{
+ nop %sh{
+ echo \"\${kak_opt_autorestore_purge_restored}\" > /tmp/out
+ if [ \"\${kak_opt_autorestore_purge_restored,,}\" = yes \
+ -o \"\${kak_opt_autorestore_purge_restored,,}\" = true ]; then
+ rm -f '${latest_backup_path}'
+ fi
+ }
+ }
+ "
+ }
+}
+
+## Remove all the backups that have been created for the current buffer
+def autorestore-purge-backups %{
+ nop %sh{
+ buffer_basename="${kak_bufname##*/}"
+ buffer_dirname=$(dirname "${kak_bufname}")
+
+ find "${buffer_dirname}" -type f -readable -name ".${buffer_basename}.kak.*" -delete 2>/dev/null
+ }
+}
+
+## If for some reason, backup files need to be ignored
+def autorestore-disable %{
+ rmhooks global autorestore
+}
+
+hook -group autorestore global BufCreate .* %{ _autorestore-restore-buffer }