Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(state): recursion in hydra mode when mapping does not exist #884

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion lua/which-key/state.lua
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ local M = {}
M.state = nil
M.recursion = 0
M.recursion_timer = uv.new_timer()
M.hydra_mode = nil

---@return boolean safe, string? reason
function M.safe(mode_change)
Expand Down Expand Up @@ -235,6 +236,15 @@ function M.execute(state, key, node)
end
Util.debug("feedkeys", tostring(state.mode), keystr)
local feed = vim.api.nvim_replace_termcodes(keystr, true, true, true)

if M.hydra_mode then
-- prevent recursion in hydra mode when keying non-existing keymap
if not Util.has_mapping(state.mode.mode, feed) then
Util.debug(" mapping not found!")
return
end
end

vim.api.nvim_feedkeys(feed, "mit", false)
end

Expand Down Expand Up @@ -273,6 +283,7 @@ function M.start(opts)
end)

opts = opts or {}
M.hydra_mode = opts.loop
opts.update = true
local mode = Buf.get(opts)
opts.update = nil
Expand All @@ -294,7 +305,8 @@ function M.start(opts)
M.recursion = 0
end)

if M.recursion > 50 then
recursion_threshold = M.hydra_mode and 200 or 50
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

increasing the threshold for hydra mode to fix the problem # 1 as described in the pr

if M.recursion > recursion_threshold then
Util.error({
"Recursion detected.",
"Are you manually loading which-key in a keymap?",
Expand Down
15 changes: 15 additions & 0 deletions lua/which-key/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ function M.norm(lhs)
return M.cache.norm[lhs]
end

--- checks if lhs has a mapping
---@param mode string
---@param lhs string
function M.has_mapping(mode, lhs)
local maps = vim.api.nvim_get_keymap(mode)
for _, value in ipairs(maps) do
if
vim.api.nvim_replace_termcodes(value.lhs, true, true, true)
== vim.api.nvim_replace_termcodes(lhs, true, true, true)
then
return value
end
end
end

-- Default register
function M.reg()
-- this will be set to 2 if there is a non-empty clipboard
Expand Down