From f6ad4074c68103b854b6aa71733a3a7c213da047 Mon Sep 17 00:00:00 2001 From: Yung Thai <32729406+yungthai@users.noreply.github.com> Date: Sun, 14 Jul 2024 10:42:21 +1000 Subject: [PATCH] feat: restore buffer local keymaps --- lua/diffview/vcs/file.lua | 55 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/lua/diffview/vcs/file.lua b/lua/diffview/vcs/file.lua index 53e04ac5..7e1174d4 100644 --- a/lua/diffview/vcs/file.lua +++ b/lua/diffview/vcs/file.lua @@ -15,6 +15,9 @@ local pl = lazy.access(utils, "path") ---@type PathLib local api = vim.api local M = {} +-- keymaps to restore +local R = {} + local HAS_NVIM_0_10 = vim.fn.has("nvim-0.10") == 1 ---@alias git.FileDataProducer fun(kind: vcs.FileKind, path: string, pos: "left"|"right"): string[] @@ -350,8 +353,53 @@ function File:attach_buffer(force, opt) state.keymaps = config.extend_keymaps(conf.keymaps.view, state.keymaps) local default_map_opt = { silent = true, nowait = true, buffer = self.bufnr } + R = {} + for _, mapping in ipairs(state.keymaps) do local map_opt = vim.tbl_extend("force", default_map_opt, mapping[4] or {}, { buffer = self.bufnr }) + + local mode = mapping[1] -- string + local name_lhs = mapping[2] -- string + + local lhs_pat = string.format("%s", name_lhs) + -- escape special characters for search pattern + lhs_pat = string.gsub(lhs_pat, "%[", "%%%[") + lhs_pat = string.gsub(lhs_pat, "%]", "%%%]") + + local buf_mappings = api.nvim_buf_get_keymap(self.bufnr, mode) + + for _, buf_km in pairs(buf_mappings) do + if buf_km.lhs ~= nil then + local result = string.find(buf_km.lhs, lhs_pat) + + if result ~= nil then + local rhs = "" + if buf_km.rhs ~= nil then + rhs = buf_km.rhs + else + rhs = buf_km.callback + end + -- save original buffer keymap + local orig_km = { + mode = mode, + lhs = name_lhs, + rhs = rhs, + opts = { + buffer = self.bufnr, + desc = buf_km.desc, + silent = buf_km.silent, + noremap = buf_km.noremap, + }, + } + table.insert(R, orig_km) + -- found buffer keymap, so stop searching + do + break + end + end + end + end + vim.keymap.set(mapping[1], mapping[2], mapping[3], map_opt) end @@ -387,6 +435,13 @@ function File:detach_buffer() end end + -- restore original buffer keymaps + for _, km in pairs(R) do + if km.opts.buffer == self.bufnr then + vim.keymap.set(km.mode, km.lhs, km.rhs, km.opts) + end + end + -- Diagnostics if state.disable_diagnostics then if HAS_NVIM_0_10 then