Make 'n' always search forwards, regardless of whether / or ? was used for searching

前端 未结 2 891
臣服心动
臣服心动 2021-02-09 07:39

I almost always search in Vim with /, and then continue searching forwards with n and backwards with N. Sometimes, however, I use ?<

2条回答
  •  一整个雨季
    2021-02-09 08:10

    This was taken from ZyX's post on the vim mailing list.

    noremap  n 'Nn'[v:searchforward]
    noremap  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  n n
    noremap  N N
    

    and when v:searchfoward == 0 (search backwards) the mappings are equivalent to

    noremap  n N
    noremap  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  n (v:searchforward ? 'n' : 'N')
    noremap  N (v:searchforward ? 'N' : 'n')
    

提交回复
热议问题