Text search direction in Vim

10

1

After I search for "foo" by doing "?foo", I can search forward by "n" or backward by "N", however sometimes the n/N directions are flipped in the middle of search. If I restart Vim, it's OK again. What key sequence may I have pressed to cause this? How to revert back to normal mode?

I don't recall that I ever ran into this in old Vi.

EDIT: it's not the Caps Lock key. Thanks for the suggestion though.

grokus

Posted 2010-08-09T15:38:52.180

Reputation: 235

I guess it's not just the wrapping around at the end/beginning of the file? Or maybe you typed * or something that reverses the search? I know I unintentionally do it a lot of time. – Dave Vogt – 2010-08-09T16:07:20.097

@Dave Vogt, it's not just end/beginning of the file. I just tested "", you are right, if I press "" I can change/correct the search direction. If you put in an answer, I will vote it up and accept it. Thanks. – grokus – 2010-08-09T16:15:21.343

Answers

11

This can happen if you started out searching backwards with ?foobar, and you pressed / in the middle. Now you're searching forward, so n and N are switched relative to what you used to have. The same thing will happen if you started with / and pressed ? in the middle.

Nathan Fellman

Posted 2010-08-09T15:38:52.180

Reputation: 8 152

Sir you are right. I just tested what you said. Could you tell me what role "*" is playing in this midst? – grokus – 2010-08-09T17:47:59.383

1@grokus: * means to search forward for whatever word is under the cursor. – Daenyth – 2010-08-09T18:05:53.893

@Daenyth, thanks. I always thought that I wasn't too bad at Vim. (I could get things done) Today I'm reconsidering my position. – grokus – 2010-08-09T18:36:49.887

and to follow up @Daenyth, you can search backward for whatever word is under the cursor using #. These will match only on the full word. To search for the word under the cursor, including inside other words, use g* – Nathan Fellman – 2010-08-09T19:06:49.473

3

It sounds stupid but did you checked Caps-Lock?

Chen Levy

Posted 2010-08-09T15:38:52.180

Reputation: 1 495

yes I did. It was on "off" position. I have seen this behavior so many times so I was finally fed up and decided to get to the bottom of this. – grokus – 2010-08-09T16:03:39.723

0

Nathan has already answered why this happens, but if you use both directions regularly and want n to always look ahead and N to always look back, no matter which way you searched, you can put this in your .vimrc:

nmap n /<CR>
nmap N ?<CR>

/ and ? without parameters perform the last search, in their respective (absolute) directions.

Fund Monica's Lawsuit

Posted 2010-08-09T15:38:52.180

Reputation: 214