7

When I do a /someStringtoFind in vim it immediately jumps to the closest matched string.

Almost always this is what I want it to do. Sometimes though, I want to be able to enter a string to find and not have my cursor move while I am typing the string. Then, after I have finished typing the string, I could hit enter for vim to jump to the string.

How can I do this?

romainl
  • 40,486
  • 5
  • 85
  • 117
red888
  • 193
  • 1
  • 5

2 Answers2

9

Type : before searching: :/someStringtoFind Enter. If the match isn't at the beginning of the line, press n to go to the beginning of the match.

/someStringtoFind/ is an empty ex command with the range of lines /someStringtoFind/ (a 1-line range). The empty ex command means “jump to the end of the range”, so the command jumps to the next line containing a match for someStringtoFind. You can drop the final / if you have nothing to put afterwards.

:/someStringtoFind drops you to the beginning of the target line. The search is stored in the search history, so n brings you to the beginning of the next match, which is on the current line. There's an exception: if the match starts at the beginning of the line, then you're already at the beginning of the match, and n would bring you to the next match. As long as the match doesn't span lines, $N brings you to the beginning of the match reliably, if you don't mind the extra typing (or are writing a macro).

4

You can make use of the fact, that you can set the search register @/ directly, which does not move the cursor. So simply do :let @/='foobar' and the cursor position won't change. If you want to move to the match, you press n as usual.

Christian Brabandt
  • 25,820
  • 1
  • 52
  • 77