我将 coc.nvim 与建议的默认配置(在 lua 文件中)一起使用:
-- Use `[g` and `]g` to navigate diagnostics
-- Use `:CocDiagnostics` to get all diagnostics of current buffer in location list
keyset("n", "[g", "<Plug>(coc-diagnostic-prev)", {silent = true})
keyset("n", "]g", "<Plug>(coc-diagnostic-next)", {silent = true})
我想知道是否有一种方法可以使这些动作可以用“.”重复。
我看到 tpope 的插件 vim-repeat 似乎允许这样做。确实,它说的是:
Adding support to a plugin is generally as simple as the following command at the end of your map functions.
silent! call repeat#set("\<Plug>MyWonderfulMap", v:count)
但我不知道如何使用“keyset”命令实际放置这行代码。
你知道如何去做吗?
感谢您阅读(和帮助)我!
与 https://github.com/tpope/vim-repeat/issues/92#issuecomment-1826910664
交叉发布vim.keymap.set("n", "[g", "<Plug>(coc-diagnostic-prev)", {silent = true})
vim.keymap.set("n", "]g", "<Plug>(coc-diagnostic-next)", {silent = true})
你可以这样做:
local t = function(keycode) return vim.api.nvim_replace_termcodes(keycode, true, true, true) end
vim.keymap.set("n", "[g", function()
vim.api.nvim_feedkeys(t '<Plug>(coc-diagnostic-prev)', "n")
vim.fn["repeat#set"](t '<Plug>(coc-diagnostic-prev)')
end, {silent = true})
与
]g
类似。您可能想要创建一些辅助函数来减少重复的类似行。
feedkeys
的使用在这里相当老套且脆弱,所以下面我会建议一些方法来自动创建内部包装器映射,使事情可重复。
您可以使用以下包装器方便地包装要传递给
rhs
的 vim.keymap.set
:
---Register a global internal keymap that wraps `rhs` to be repeatable.
---@param mode string|table keymap mode, see vim.keymap.set()
---@param lhs string lhs of the internal keymap to be created, should be in the form `<Plug>(...)`
---@param rhs string|function rhs of the keymap, see vim.keymap.set()
---@return string The name of a registered internal `<Plug>(name)` keymap. Make sure you use { remap = true }.
local make_repeatable_keymap = function (mode, lhs, rhs)
vim.validate {
mode = { mode, { 'string', 'table' } },
rhs = { rhs, { 'string', 'function' },
lhs = { name = 'string' } }
}
if not vim.startswith(lhs, "<Plug>") then
error("`lhs` should start with `<Plug>`, given: " .. lhs)
end
vim.keymap.set(mode, lhs, function()
rhs()
vim.fn['repeat#set'](vim.api.nvim_replace_termcodes(lhs, true, true, true))
end)
return lhs
end
(注意:这并没有实现
opts
,例如buffer
,nowait
,silent
等,但它应该很容易扩展)
示例:如果您想让键盘映射
<leader>tc
映射到lua函数(或任何键盘映射序列字符串)可重复:
vim.keymap.set('n', '<leader>tc', make_repeatable_keymap('n', '<Plug>(ToggleComment)', function()
-- the actual body (rhs) goes here: some complex logic that you want to repeat
end, { remap = true })
这将:
<Plug>(ToggleComment)
,它可以使内部键盘映射可重复。<leader>tc
映射到 <Plug>(ToggleComment)
,这将执行所需的主体 (rhs)。{ remap = true }
。因此,为了使 vim-repeat 工作,通常应该有一个键盘映射(或命令),例如:
<Plug>(MyKeymap)
。repeat#set("<Plug>(MyKeymap)")
标记要按 .
重复的 keymap序列。
feedkeys
在后台实现的——所以需要使用 nvim_replace_termcodes
;也不能使用匿名函数。<Plug>
来创建 内部映射,因为这将使按键重复很多,更容易编写和理解。