Search code examples
neovimkey-bindings

How to execute an operator command + `{motion}` in keybind (n)vim


I am trying to get the following keybind working:

vim.keymap.set("n", "<C-Enter>", ":MoltenEvaluateOperator<CR> ib", { desc = "evaluate operator" })

For context, I setup molten-nvim according to https://github.com/benlubas/molten-nvim/blob/main/docs/Notebook-Setup.md, and everything seems to work nicely. When I type :MoltenEvaluateOperator followed by enter and ib it does exactly what I expect; :MoltenEvaluateOperator gets executed with the ib "motion".

So, I expected that I could also create a keybind to execute all of this for me, since I will always be using this command in combination with ib. You can see the keybinding I created above.

However, it does not work. It seems that the i makes nvim go into insert mode, which is then followed by b and subsequently also g@. This is completely unexpected, as nvim does not do this when I manually type the same sequence of keys.

I also tried:

vim.keymap.set("n", "<C-Enter>", ":MoltenEvaluateOperator<CR><Up>", { desc = "evaluate operator" })

but it would also just move the cursor up, and not actually execute :MoltenEvaluateOperator with the <Up> motion.

Does anyone have a clue what is going on here? How could I make this actually work?

EDIT: Since I can't edit my comment my comment below, here is my final solution:

vim.keymap.set("n", "<C-Enter>", ":MoltenEvaluateOperator<CR>:call feedkeys(\"ib\")<CR>", { desc = "evaluate operator" })

Solution

  • The problem is that the plugin calls feedkeys() internally.

    In Vim whole mapping gets appended into the input queue. Then Vim executes it advancing upto feedkeys() which appends its argument (g@) after the remaining part of the mapping (ib). And so you get ibg@ instead of g@ib that you would get if typed by hand.

    What to do? (1) Use feedkeys('ib') yourself to trick it; or (2) raise an issue, so they put i flag into feedkeys call ("insert" instead of "append"); or (3) stop using low quality plugins (imo, any plugin that uses feedkeys is already suspicious but if it does it incorrectly it goes straight to the trash bin).