Skip to content

feat: help closes on <Esc> and api.tree.toggle_help mappings #2909

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

Merged
merged 2 commits into from
Sep 14, 2024
Merged
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
30 changes: 23 additions & 7 deletions lua/nvim-tree/help.lua
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
local keymap = require "nvim-tree.keymap"
local api = {} -- circular dependency

local PAT_MOUSE = "^<.*Mouse"
local PAT_CTRL = "^<C%-"
Expand Down Expand Up @@ -79,18 +80,19 @@ local function sort_lhs(a, b)
end

--- Compute all lines for the buffer
---@param map table keymap.get_keymap
---@return table strings of text
---@return table arrays of arguments 3-6 for nvim_buf_add_highlight()
---@return number maximum length of text
local function compute()
local function compute(map)
local head_lhs = "nvim-tree mappings"
local head_rhs1 = "exit: q"
local head_rhs2 = string.format("sort by %s: s", M.config.sort_by == "key" and "description" or "keymap")

-- formatted lhs and desc from active keymap
local mappings = vim.tbl_map(function(map)
return { lhs = tidy_lhs(map.lhs), desc = tidy_desc(map.desc) }
end, keymap.get_keymap())
local mappings = vim.tbl_map(function(m)
return { lhs = tidy_lhs(m.lhs), desc = tidy_desc(m.desc) }
end, map)

-- sorter function for mappings
local sort_fn
Expand Down Expand Up @@ -165,8 +167,11 @@ local function open()
-- close existing, shouldn't be necessary
close()

-- fetch all mappings
local map = keymap.get_keymap()

-- text and highlight
local lines, hl, width = compute()
local lines, hl, width = compute(map)

-- create the buffer
M.bufnr = vim.api.nvim_create_buf(false, true)
Expand Down Expand Up @@ -206,12 +211,21 @@ local function open()
open()
end

local keymaps = {
-- hardcoded
local help_keymaps = {
q = { fn = close, desc = "nvim-tree: exit help" },
["<Esc>"] = { fn = close, desc = "nvim-tree: exit help" }, -- hidden
s = { fn = toggle_sort, desc = "nvim-tree: toggle sorting method" },
}

for k, v in pairs(keymaps) do
-- api help binding closes
for _, m in ipairs(map) do
if m.callback == api.tree.toggle_help then
help_keymaps[m.lhs] = { fn = close, desc = "nvim-tree: exit help" }
end
end

for k, v in pairs(help_keymaps) do
vim.keymap.set("n", k, v.fn, {
desc = v.desc,
buffer = M.bufnr,
Expand Down Expand Up @@ -240,6 +254,8 @@ end
function M.setup(opts)
M.config.cursorline = opts.view.cursorline
M.config.sort_by = opts.help.sort_by

api = require "nvim-tree.api"
end

return M
Loading