aboutsummaryrefslogtreecommitdiff
path: root/plugins/autoinsert.lua
diff options
context:
space:
mode:
authorrxi <rxi@users.noreply.github.com>2020-06-13 10:32:07 +0100
committerrxi <rxi@users.noreply.github.com>2020-06-13 23:35:01 +0100
commit349aae592e75924089c0700387017529a494f1cc (patch)
treefdee06cf4b64be5e4e3431f7bf4fe96484287c20 /plugins/autoinsert.lua
parent61decc3456e609c9e2ec7132ac58d80e7af5f916 (diff)
downloadlite-xl-plugins-349aae592e75924089c0700387017529a494f1cc.tar.gz
lite-xl-plugins-349aae592e75924089c0700387017529a494f1cc.zip
Added plugin `autoinsert`
Diffstat (limited to 'plugins/autoinsert.lua')
-rw-r--r--plugins/autoinsert.lua75
1 files changed, 75 insertions, 0 deletions
diff --git a/plugins/autoinsert.lua b/plugins/autoinsert.lua
new file mode 100644
index 0000000..a3c8f98
--- /dev/null
+++ b/plugins/autoinsert.lua
@@ -0,0 +1,75 @@
+local core = require "core"
+local config = require "core.config"
+local DocView = require "core.docview"
+local command = require "core.command"
+local keymap = require "core.keymap"
+
+
+config.autoinsert_map = {
+ ["["] = "]",
+ ["{"] = "}",
+ ["("] = ")",
+ ['"'] = '"',
+}
+
+
+local function is_closer(chr)
+ for _, v in pairs(config.autoinsert_map) do
+ if v == chr then
+ return true
+ end
+ end
+end
+
+
+local on_text_input = DocView.on_text_input
+
+function DocView:on_text_input(text)
+ local mapping = config.autoinsert_map[text]
+
+ -- prevents plugin from operating on `CommandView`
+ if getmetatable(self) ~= DocView then
+ return on_text_input(self, text)
+ end
+
+ -- wrap selection if we have a selection
+ if mapping and self.doc:has_selection() then
+ local l1, c1, l2, c2, swap = self.doc:get_selection(true)
+ self.doc:insert(l2, c2, mapping)
+ self.doc:insert(l1, c1, text)
+ self.doc:set_selection(l1, c1, l2, c2 + 2, swap)
+ return
+ end
+
+ -- skip inserting closing text
+ local chr = self.doc:get_char(self.doc:get_selection())
+ if text == chr and is_closer(chr) then
+ self.doc:move_to(1)
+ return
+ end
+
+ -- auto insert closing bracket
+ if mapping and (chr:find("%s") or is_closer(chr) and chr ~= '"') then
+ on_text_input(self, text)
+ on_text_input(self, mapping)
+ self.doc:move_to(-1)
+ return
+ end
+
+ on_text_input(self, text)
+end
+
+
+command.add("core.docview", {
+ ["autoinsert:backspace"] = function()
+ local doc = core.active_view.doc
+ local l, c = doc:get_selection()
+ local chr = doc:get_char(l, c)
+ if config.autoinsert_map[doc:get_char(l, c - 1)] and is_closer(chr) then
+ doc:delete_to(1)
+ end
+ command.perform "doc:backspace"
+ end,
+})
+
+keymap.add { ["backspace"] = "autoinsert:backspace" }