How do I jump to relative line number with gj/gk

I have relative line numbers enabled (wo.number = true and wo.relativenumber = true). I also use gj and gk to move visually (map j to gj).

Now I want to jump to a different line. If there is a wrapped line of text, the jump falls short.

Example:

 3 this is a very long
   line. yes, it is very
   very long
 2 apple
 1 pear
77 nobody
 1 there

I am at line 77 nobody and want to jump three lines up (to 3 this is a very long). I type 3k. I jump to very long instead.


I am using the latest Neovim with a lua config.


E: Maybe what I am actually looking for is a way to use gj/gk normally and j/k only when jumping to a line

E2: Or a way to have the relative line numbers take into account line wraps.

vim.keymap.set({ "n", "x" }, "j", function()
	return vim.v.count > 0 and "j" or "gj"
end, { noremap = true, expr = true })
vim.keymap.set({ "n", "x" }, "k", function()
	return vim.v.count > 0 and "k" or "gk"
end, { noremap = true, expr = true })
1 Like

Thanks for replying! This is a function that maps j to either j if called as 3j and gj otherwise?


E: I am getting an attempt to index field 'keymap' (a nil value) error. I guess I am doing something wrong.

Ah, yes, keymap is a recently added feature and does not work with the current stable version(v0.6.1).

If you are fine with vim script, this will work.

nnoremap <expr> j v:count ? 'j' : 'gj'
nnoremap <expr> k v:count ? 'k' : 'gk'

Or you can use the Lua api that has been available before

vim.api.nvim_set_keymap("n", "j", "v:count ? 'j' : 'gj'", { noremap = true, expr = true })
vim.api.nvim_set_keymap("n", "k", "v:count ? 'k' : 'gk'", { noremap = true, expr = true })

Perfect. I guess then I am not on latest :smiley: My bad. And I almost got the Lua version myself, except I had it as vim.v.count > 0… so thank you, I learned a lot.

1 Like