which-key.nvim
which-key.nvim copied to clipboard
bug: Mapping vim.cmd functions with arguments will run the function when nvim starts
Did you check docs and existing issues?
- [X] I have read all the which-key.nvim docs
- [X] I have searched the existing issues of which-key.nvim
- [X] I have searched the existing issues of plugins related to this issue
Neovim version (nvim -v)
0.9.5
Operating system/version
Ubuntu 23.10
Describe the bug
Adding mappings that call vim.cmd.*('...')
functions with arguments in parenthesis will cause those functions to be run on nvim startup, when register happens. This doesn't happen if vim.cmd.*
doesn't have parenthesis.
I'm new to nvim and lua, so maybe this is expected behaviour? But I didn't see any of this in the README, sorry.
Edit: This also doesn't happen if the command is defined using a string with '<cmd>...'
. Thought that'd be more obvious but worth noting.
Steps To Reproduce
- Register a mapping for any key to `vim.cmd.echo('"Hello"')
- Close and reopen nvim
- "Hello" will be printed on the status line on startup.
- Delete the previous mapping and create one for
vim.cmd.edit
- Close and reopen nvim, notice that the command is not automatically run.
- Delete the previous mapping and create one for
vim.cmd.edit('test_file')
- Close and reopen nvim, notice that nvim automatically goes into edit mode in a new file 'test_file'
Expected Behavior
Mappings to vim.cmd.*('...')
functions can be made without them running on startup.
I have a similar issue: I have the following function:
local function diffOpen()
local user_input = vim.fn.input("Revision to Open: ")
return "<cmd>DiffviewOpen<CR>" .. user_input .. "<CR>"
end
-- Key maps
require("which-key").register({
g = {
name = "Git", -- optional group name
t = { "<cmd>DiffviewToggleFiles<CR>", "Toggle DiffView Explorer" },
o = { diffOpen, "Open DiffView"},
},
}, { prefix = "<leader>" })
If I pass diffOpen()
to which key it executes when registering. Which I understand.
But If I just pass as the function without calling it. It doesn't execute the returned command string.
Is there a lua command that runs strings as nvim commands?
Edit: The following worked.
local function diffOpen()
local user_input = vim.fn.input("Revision to Open: ")
vim.cmd("DiffviewOpen" .. user_input)
end
@FedeAbella Can you share how you're registering the mapping with Which-key?
If your issue is similar to mine, I can help.
@FedeAbella if you call the function, it is called when that expression is evaluated, this is expected. You need to pass a function /to be called/, not the result of a function call that has already been done.
No: vim.keymap.set("n", "<F1>", vim.cmd("echo 'hi'"))
Yes: vim.keymap.set("n", "<F1>", function() vim.cmd("echo 'hi'") end)
Also yes:
local function my_function()
-- I will be called when my key is used
vim.print("Hi from my_function")
end
vim.keymap.set("n", "<F1>", my_function) -- if we used my_function() here it would be weird and wrong