Skip to content

Commit a4f38e6

Browse files
implement condition objects
1 parent 8f8d493 commit a4f38e6

File tree

1 file changed

+51
-2
lines changed

1 file changed

+51
-2
lines changed
Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,62 @@
11
local M = {}
22

3-
function M.line_begin(line_to_cursor, matched_trigger)
3+
-----------------------
4+
-- CONDITION OBJECTS --
5+
-----------------------
6+
local condition_mt = {
7+
-- logic operators
8+
-- not '~'
9+
__unm = function(o1)
10+
return function(...)
11+
return not o1(...)
12+
end
13+
end,
14+
-- or '+'
15+
__add = function(o1, o2)
16+
return function(...)
17+
return o1(...) or o2(...)
18+
end
19+
end,
20+
-- and '*'
21+
__mul = function(o1, o2)
22+
return function(...)
23+
return o1(...) and o2(...)
24+
end
25+
end,
26+
-- xor '^'
27+
__pow = function(o1, o2)
28+
return function(...)
29+
return o1(...) ~= o2(...)
30+
end
31+
end,
32+
-- xnor '=='
33+
__eq = function(o1, o2)
34+
return function(...)
35+
return o1(...) == o2(...)
36+
end
37+
end,
38+
-- use table like a function by overloading __call
39+
__call = function(tab, line_to_cursor, matched_trigger, captures)
40+
return tab.func(line_to_cursor, matched_trigger, captures)
41+
end,
42+
}
43+
function M.condition_factory(func)
44+
return setmetatable({func=func}, condition_mt)
45+
end
46+
47+
-----------------------
48+
-- PRESET CONDITIONS --
49+
-----------------------
50+
local function line_begin(line_to_cursor, matched_trigger)
451
-- +1 because `string.sub("abcd", 1, -2)` -> abc
552
return line_to_cursor:sub(1, -(#matched_trigger + 1)):match("^%s*$")
653
end
54+
M.line_begin = M.condition_factory(line_begin)
755

8-
function M.line_end(line_to_cursor)
56+
local function line_end(line_to_cursor)
957
local line = vim.api.nvim_get_current_line()
1058
return #line_to_cursor == #line
1159
end
60+
M.line_end = M.condition_factory(line_end)
1261

1362
return M

0 commit comments

Comments
 (0)