Skip to content

Commit

Permalink
fix: show correct level and sort on keys / group
Browse files Browse the repository at this point in the history
  • Loading branch information
folke committed Apr 26, 2021
1 parent 970e79f commit a372c63
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 12 deletions.
15 changes: 14 additions & 1 deletion lua/which-key/keys.lua
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ end
function M.get_keymap(mode, prefix, buf)
local mappings = {}

local key_count = #M.parse_keys(prefix).nvim

local map = function(keymap)
prefix = M.t(prefix)
for _, mapping in pairs(keymap) do
Expand All @@ -52,7 +54,18 @@ function M.get_keymap(mode, prefix, buf)
-- buffer local mappings
if buf then map(vim.api.nvim_buf_get_keymap(buf, mode)) end

return mappings
local ret = {}
for _, value in pairs(mappings) do table.insert(ret, value) end

table.sort(ret, function(a, b)
if a.group == b.group then
return (a.keys.nvim[key_count + 1] or "") < (b.keys.nvim[key_count + 1] or "")
else
return (a.group and 1 or 0) < (b.group and 1 or 0)
end
end)

return ret
end

function M.parse_mappings(ret, value, prefix)
Expand Down
26 changes: 15 additions & 11 deletions lua/which-key/view.lua
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,9 @@ function M.hide()
end

---@param text Text
function M.render_mapping(text, mapping)
text:render(mapping.lhs, "")
function M.render_mapping(text, mapping, key_count)
local key = mapping.keys.nvim[key_count + 1]
text:render(key or "", "")
text:render("->", "Seperator")
if mapping.group == true then
text:render(mapping.label or mapping.rhs or "", "Group")
Expand All @@ -83,24 +84,27 @@ function M.on_keys(keys)
-- eat queued characters
M.eat(false)

local key_count = #Keys.parse_keys(M.keys).nvim

local mappings = Keys.get_keymap(vim.api.nvim_get_mode().mode, M.keys,
vim.api.nvim_get_current_buf())

local text = Text:new()
local count = 0
for _, mapping in pairs(mappings) do
-- Exact match found, trigger keymapping
if mapping.id == Keys.t(M.keys) then
if mapping.group ~= true then
M.hide()
vim.api.nvim_feedkeys(M.keys, "m", true)
return
else -- skip this exact prefix group
end
if mapping.id == Keys.t(M.keys) and mapping.group ~= true then
M.hide()
vim.api.nvim_feedkeys(M.keys, "m", true)
return
end
if #mapping.keys.nvim == key_count + 1 then
count = count + 1
M.render_mapping(text, mapping, key_count)
end
M.render_mapping(text, mapping)
end

if #text.lines == 0 then
if count == 0 then
-- no mappings found. Feed back the keys
M.hide()
vim.api.nvim_feedkeys(M.keys, "n", true)
Expand Down

0 comments on commit a372c63

Please sign in to comment.