I almost always search in Vim with /
, and then continue searching forwards with n
and backwards with N
. Sometimes, however, I use ?
to jump to an item just a few lines above the line I'm currently at, and in that case, if I want to search the same item forwards, I have to use N
instead of n
, an annoying mental speed bump.
So my question is: is it possible to make n
always go forwards, and N
backwards?
P.S. Documentation seems to hint that it's not possible, since n
simply "Repeats the latest "/" or "?" [count] times", but who knows.
This was taken from ZyX's post on the vim mailing list.
noremap <expr> n 'Nn'[v:searchforward]
noremap <expr> N 'nN'[v:searchforward]
It maps n
to the original N or n based off of the variable v:searchforward
by indexing 'Nn'
as a list of two elements. This only works because the mapping is non-recursive. If it was recursive this would call it self and you would be in an infinite loop.
When v:searchforward == 1
(search forward) the mappings are equivalent to
noremap <expr> n n
noremap <expr> N N
and when v:searchfoward == 0
(search backwards) the mappings are equivalent to
noremap <expr> n N
noremap <expr> N n
This mapping works in Normal, Visual, and Operator pending modes.
I probably would have written it like this. (Although I'm not sure this is any clearer)
noremap <expr> n (v:searchforward ? 'n' : 'N')
noremap <expr> N (v:searchforward ? 'N' : 'n')
That is just the way it is, notwithstanding some debate on the developers' mailing list ...
Here's what you can do about it:
:noremap n /<CR>
:noremap N ?<CR>
Relevant mailing list thread with a lot more interesting info: https://groups.google.com/d/msg/vim_dev/8jSoA931P2Y/JklYtxFOiAYJ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With