Skip to content

Commit 03047ec

Browse files
committed
fix(surround): adjust s-><Nop> mapping to respect buf+global mappings
Details: - Although using `vim.fn.maparg()` is concise, it is not a reliable source of data about whether or not there is a global mapping. In case there is a buffer-local mapping, it can not return information about the global mapping. Resort to manual iteration through `nvim_get_keymap()` array to deduce if there is a mapping with a target LHS.
1 parent ee4a4a4 commit 03047ec

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

lua/mini/surround.lua

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2265,10 +2265,17 @@ H.map = function(mode, lhs, rhs, opts)
22652265
if lhs == '' then return end
22662266
opts = vim.tbl_deep_extend('force', { silent = true }, opts or {})
22672267
vim.keymap.set(mode, lhs, rhs, opts)
2268-
local no_global_s_mapping = vim.fn.maparg('s', mode, false, true).buffer ~= 0
2268+
local no_global_s_mapping = not H.has_global_mapping(mode, 's')
22692269
if no_global_s_mapping and lhs:find('^s.') ~= nil then vim.keymap.set(mode, 's', '<Nop>') end
22702270
end
22712271

2272+
H.has_global_mapping = function(mode, lhs)
2273+
for _, map in ipairs(vim.api.nvim_get_keymap(mode)) do
2274+
if map.lhs == lhs then return true end
2275+
end
2276+
return false
2277+
end
2278+
22722279
H.get_line_cols = function(line_num) return vim.fn.getline(line_num):len() end
22732280

22742281
H.string_find = function(s, pattern, init)

tests/test_surround.lua

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,8 +248,22 @@ T['setup()']['properly handles `config.mappings`'] = function()
248248
end
249249
-- - NOTE: `nvim_get_keymap()` return `rhs=''` if it is mapped to `<Nop>`
250250
-- For absent mapping it would have been `nil`
251+
eq(get_global_mapping('n', 's').rhs, '')
251252
eq(get_global_mapping('x', 's').rhs, '')
252-
eq(get_global_mapping('x', 's').rhs, '')
253+
254+
-- - Should work when there are both buffer-local and global mappings
255+
make_clean_state()
256+
child.cmd('nmap s <Cmd>echo 1<CR>')
257+
child.cmd('nmap <buffer> s <Cmd>echo 10<CR>')
258+
child.cmd('xmap s <Cmd>echo 2<CR>')
259+
child.cmd('xmap <buffer> s <Cmd>echo 20<CR>')
260+
261+
load_module()
262+
263+
eq(child.fn.maparg('s', 'n'), '<Cmd>echo 10<CR>')
264+
eq(child.fn.maparg('s', 'x'), '<Cmd>echo 20<CR>')
265+
eq(get_global_mapping('n', 's').rhs, '<Cmd>echo 1<CR>')
266+
eq(get_global_mapping('x', 's').rhs, '<Cmd>echo 2<CR>')
253267
end
254268

255269
T['update_n_lines()'] = new_set({

0 commit comments

Comments
 (0)