micro/runtime/plugins/autoclose/autoclose.lua

76 lines
2.4 KiB
Lua
Raw Normal View History

2020-02-02 04:54:38 +00:00
VERSION = "1.0.0"
2019-08-02 21:48:59 +00:00
local uutil = import("micro/util")
local utf8 = import("utf8")
2016-09-25 17:05:58 +00:00
local autoclosePairs = {"\"\"", "''", "``", "()", "{}", "[]"}
local autoNewlinePairs = {"()", "{}", "[]"}
2019-08-02 21:48:59 +00:00
function charAt(str, i)
-- lua indexing is one off from go
return uutil.RuneAt(str, i-1)
end
2019-08-02 21:48:59 +00:00
function onRune(bp, r)
for i = 1, #autoclosePairs do
2016-06-23 01:03:40 +00:00
if r == charAt(autoclosePairs[i], 2) then
2019-08-02 21:48:59 +00:00
local curLine = bp.Buf:Line(bp.Cursor.Y)
2019-08-02 21:48:59 +00:00
if charAt(curLine, bp.Cursor.X+1) == charAt(autoclosePairs[i], 2) then
bp:Backspace()
bp:CursorRight()
break
end
2019-08-02 21:48:59 +00:00
if bp.Cursor.X > 1 and (uutil.IsWordChar(charAt(curLine, bp.Cursor.X-1)) or charAt(curLine, bp.Cursor.X-1) == charAt(autoclosePairs[i], 1)) then
break
end
end
2016-06-23 01:03:40 +00:00
if r == charAt(autoclosePairs[i], 1) then
2019-08-02 21:48:59 +00:00
local curLine = bp.Buf:Line(bp.Cursor.Y)
2020-05-20 22:04:00 +00:00
if bp.Cursor.X == uutil.CharacterCountInString(curLine) or not uutil.IsWordChar(charAt(curLine, bp.Cursor.X+1)) then
2019-08-02 21:48:59 +00:00
-- the '-' here is to derefence the pointer to bp.Cursor.Loc which is automatically made
-- when converting go structs to lua
-- It needs to be dereferenced because the function expects a non pointer struct
2019-08-02 21:48:59 +00:00
bp.Buf:Insert(-bp.Cursor.Loc, charAt(autoclosePairs[i], 2))
bp:CursorLeft()
break
end
end
end
2019-12-29 03:39:57 +00:00
return true
end
2019-08-02 21:48:59 +00:00
function preInsertNewline(bp)
local curLine = bp.Buf:Line(bp.Cursor.Y)
local curRune = charAt(curLine, bp.Cursor.X)
local nextRune = charAt(curLine, bp.Cursor.X+1)
local ws = uutil.GetLeadingWhitespace(curLine)
for i = 1, #autoNewlinePairs do
2016-06-23 01:03:40 +00:00
if curRune == charAt(autoNewlinePairs[i], 1) then
if nextRune == charAt(autoNewlinePairs[i], 2) then
2019-08-02 21:48:59 +00:00
bp:InsertNewline()
bp:InsertTab()
bp.Buf:Insert(-bp.Cursor.Loc, "\n" .. ws)
bp:StartOfLine()
bp:CursorLeft()
2016-08-19 22:24:42 +00:00
return false
end
end
end
2016-08-19 22:14:34 +00:00
2016-08-19 22:24:42 +00:00
return true
end
2019-08-02 21:48:59 +00:00
function preBackspace(bp)
for i = 1, #autoclosePairs do
2019-08-02 21:48:59 +00:00
local curLine = bp.Buf:Line(bp.Cursor.Y)
if charAt(curLine, bp.Cursor.X+1) == charAt(autoclosePairs[i], 2) and charAt(curLine, bp.Cursor.X) == charAt(autoclosePairs[i], 1) then
bp:Delete()
end
end
2016-07-24 20:19:41 +00:00
return true
end