1

I'm trying to add a count to one of my keymap bindings.

vim.keymap.set("n", "<leader>o", vim.v.count .. 'o<Esc>') does not work as expected.

My intention for this keymap is to insert count empty lines and stay in normal mode.

If I use the key combination <leader>5o only one new line is added and the editor is in insert mode. Only after I hit the Esc key myself 4 extra lines appear and the editor switches to normal mode.

How to correctly use vim.v.count with vim.keymap.set?

Also, when using this keymap, should I press 5<leader>o or <leader>5o?

If I use vim.keymap.set("n", "<leader>o", 5 .. 'o<Esc>') it works as expected. After pressing <leader>o five new lines are added and the editor stays in normal mode.

I've also tried to wrap the commands into a function vim.keymap.set("n", "<leader>o", function() ... end) but it didn't change the behavior.

1 Answer 1

0

For you particular case I would do:

vim.keymap.set("n", "<leader>o", 'o<Esc>')

If you type 3leadero it will translate into: 3oEsc which is doing what you want to do (the o command supports count).

In Neovim you can associate a mapping to a Lua function. You could do something like:

vim.keymap.set("n", "<leader>o",
  function()
    for i=1,vim.v.count 
    do
      vim.cmd('normal! o')
    end
  end
)

The Vim mapping doesn't support the count per se. Vim is aware of the count and apply the count to the result of the mapping (like in the example).

Would the o command not support the count you could have done:

vim.keymap.set("n", "<leader>o", "@='o<C-v><Esc>'<CR>")

If you then type 3leadero it will translate into: 3@='oCtrl-vEsc'Enter

Since the macro support the count it will translate into: oCtrl-vEscoCtrl-vEscoCtrl-vEsc

If you need the count to be used not only as a mere duplication of then entire mapping you can define a custom command and map to the execution of that custom command (that command can make use of the count).

Here is an article that explain that in more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.