feat(util): on_key handler

This commit is contained in:
Folke Lemaitre 2024-12-15 08:26:42 +01:00
parent 51a4b61445
commit 002d5eb5c2
No known key found for this signature in database
GPG key ID: 41F8B1FBACAE2040
2 changed files with 22 additions and 6 deletions

View file

@ -34,8 +34,6 @@ local defaults = {
}
local SCROLL_UP, SCROLL_DOWN = Snacks.util.keycode("<c-e>"), Snacks.util.keycode("<c-y>")
local SCROLL_WHEEL_DOWN, SCROLL_WHEEL_UP =
Snacks.util.keycode("<ScrollWheelDown>"), Snacks.util.keycode("<ScrollWheelUp>")
local mouse_scrolling = false
M.enabled = false
@ -99,10 +97,11 @@ function M.enable()
local group = vim.api.nvim_create_augroup("snacks_scroll", { clear = true })
-- track mouse scrolling
vim.on_key(function(key)
if key == SCROLL_WHEEL_DOWN or key == SCROLL_WHEEL_UP then
mouse_scrolling = true
end
Snacks.util.on_key("<ScrollWheelDown>", function()
mouse_scrolling = true
end)
Snacks.util.on_key("<ScrollWheelUp>", function()
mouse_scrolling = true
end)
-- initialize state for buffers entering windows

View file

@ -217,4 +217,21 @@ function M.var(buf, name, default)
return default
end
local keys = {} ---@type table<string, fun(key:string)[]>
local on_key_ns ---@type number?
---@param key string
---@param cb fun(key:string)
function M.on_key(key, cb)
local code = M.keycode(key)
keys[code] = keys[code] or {}
table.insert(keys[code], cb)
on_key_ns = on_key_ns
or vim.on_key(function(_, typed)
for _, c in ipairs(keys[typed] or {}) do
pcall(c, typed)
end
end)
end
return M