2 local setmetatable
= setmetatable
8 local util
= require("util")
14 -- Weak table of argects and their buffers
16 setmetatable(buffers
, { __mode
= "k" })
18 -- Modifiers to ignore
19 ignore_modifiers
= { "Mod2", "Lock" }
21 -- Return cloned, sorted & filtered modifier mask table.
22 function filter_mods(mods
, remove_shift
)
23 -- Clone & sort new modifiers table
24 local mods
= util
.table.clone(mods
)
27 -- Filter out ignored modifiers
28 mods
= util
.table.difference(mods
, ignore_modifiers
)
31 mods
= util
.table.difference(mods
, { "Shift" })
37 -- Create new key binding
38 function key(mods
, key
, func
, opts
)
39 local mods
= filter_mods(mods
, #key
== 1)
40 return { mods
= mods
, key
= key
, func
= func
, opts
= opts
}
43 -- Create new buffer binding
44 function buf(pattern
, func
, opts
)
45 return { pattern
= pattern
, func
= func
, opts
= opts
}
48 -- Create new command binding
49 function cmd(commands
, func
, opts
)
50 return { commands
= commands
, func
= func
, opts
= opts
}
53 -- Check if there exists a key binding in the `binds` table which matches the
54 -- pressed key and modifier mask and execute it.
55 function match_key(binds
, mods
, key
, arg
)
56 for _
, b
in ipairs(binds
) do
57 if b
.key
== key
and util
.table.isclone(b
.mods
, mods
) then
64 -- Check if there exists a buffer binding in the `binds` table which matches
65 -- the given buffer and execute it.
66 function match_buf(binds
, buffer
, arg
)
67 for _
, b
in ipairs(binds
) do
68 if b
.pattern
and string.match(buffer
, b
.pattern
) then
69 b
.func(arg
, buffer
, b
.opts
)
75 -- Check if there exists a buffer binding in the `binds` table which matches
76 -- the given buffer and execute it.
77 function match_cmd(binds
, buffer
, arg
)
78 -- The command is the first word in the buffer string
79 local command
= string.match(buffer
, "^([^%s]+)")
80 -- And the argument is the entire string thereafter
81 local argument
= string.match(buffer
, "^[^%s]+%s+(.+)")
83 for _
, b
in ipairs(binds
) do
85 if b
.commands
and util
.table.hasitem(b
.commands
, command
) then
86 b
.func(arg
, argument
, b
.opts
)
89 elseif b
.pattern
and string.match(buffer
, b
.pattern
) then
90 b
.func(arg
, buffer
, b
.opts
)
96 -- Check if a bind exists with the given key & modifier mask then call the
97 -- binds function with `arg` as the first argument.
98 function hit(binds
, mods
, key
, buffer
, enable_buffer
, arg
)
99 -- Filter modifers table
100 local mods
= filter_mods(mods
, #key
== 1)
102 if (not buffer
or not enable_buffer
) or #mods
~= 0 or #key
~= 1 then
103 if match_key(binds
, mods
, key
, arg
) then
108 if not enable_buffer
or #mods
~= 0 then
111 elseif #key
== 1 then
112 buffer
= (buffer
or "") .. key
113 if match_buf(binds
, buffer
, arg
) then
119 return true, buffer
:sub(1, 10)
124 -- vim: ft=lua:et:sw=4:ts=8:sts=4:tw=80