Skip to content

feat: restore buffer keymaps #522

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
55 changes: 55 additions & 0 deletions lua/diffview/vcs/file.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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[]
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down