o", vim.v.coun" /> o", vim.v.coun" /> o", vim.v.coun"/>

How to use vim.keymap.set with vim.v.count in Neovim

540 Views Asked by At

I'm trying to add a count to one of my key-map bindings. However, the following does not work as expected:

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

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 can one correctly use vim.v.count with vim.keymap.set?

If I use vim.keymap.set("n", "<leader>o", 5 .. 'o<Esc>') it works as expected. 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

There are 1 best solutions below

0
Kyle F. Hartzenberg On

You need to use a map-expression (see h: map-expression):

-- Insert 'n' lines below current line staying in normal mode (e.g. use 5<leader>o)
vim.keymap.set("n", "<leader>o", function()
    return "m`" .. vim.v.count .. "o<Esc>``"
end, { expr = true })

-- Insert 'n' lines above current line staying in normal mode (e.g. use 5<leader>O)
vim.keymap.set("n", "<leader>O", function()
    return "m`" .. vim.v.count .. "O<Esc>``"
end, { expr = true })

-- oo and OO are another good LHS mapping,
-- they roll off the fingers a bit better than <leader>o and <leader>O I think

This forces the right-hand side of the mapping to evaluate first which correctly captures the input count. Now you can type some count, followed by <leader>o or <leader>O, and it will insert the input number of lines either below or above the current line, respectively.

Note: a mark has to be set with "m`" prior to the rest of the command otherwise strange behaviour occurs. I also added "``" to jump back to this mark so the cursor doesn't move when adding new blank lines. If you want it to jump to the last of the inserted blank lines, simply remove the "``".