Up to now we have reviewed many ways to navigate through a document, from simple cursor movements, to paging, to text objects. Vim also provides the ability to search a buffer for specific text or a pattern for desired text, then quickly navigating through matching text.
Searching forward
The first search operator we will look at it /, which searches the buffer forward from the current cursor location. Starting from the following buffer:
Initiate the search by typing /, followed by the text you want to search for, then finally hit enter to start the search.
Vim found the text, and moved the cursor forward to the start of the first match. Since there are often multiple matches, Vim provides a shortcut command for repeating a search. To repeat the search, hit n.
Repeating the search moves the cursor to the location of the next matching text. The cursor is now at the last match, what happens if we repeat the search once more?
When Vim is not able to find matching text, it "wraps around" to the top of the buffer and continues the search. In this example there are only two matches in the document, so the cursor returns to the first match.
Searching backward
Searching backward uses the ? operator, but otherwise operates the same as searching forward:
The n also works when searching backward, and like most operators this shortcut accepts a count. To move the cursor to the "second next match", precede the operator with a count of 2:
As expected, this moves the cursor to the start of the first match. Now, suppose we moved the cursor too far, and wanted to jump to the second match. Vim has a second shortcut for repeating a search, but in the opposite direction: N.
Search for word under cursor
Vim provides two additional shortcuts, & and #, for searching in the forward and backward directions, respectively. These shortcuts initiate a search and populate the search pattern with the word that is currently under the cursor, so that the search executes by simply hitting <CR>.
Here is a quick summary of the search-related operators:
Command | Action |
---|---|
/{pattern} | search forward for the Nth occurrence of {pattern} |
?{pattern} | search backward for the Nth previous occurrence of {pattern} |
& | repeat last :s |
# | search backward for the Nth occurrence of the ident under the cursor |
n | repeat the latest '/' or '?' N times |
N | repeat the latest '/' or '?' N times in opposite direction |
This section has introduced the basics of searching a buffer with simple patterns. Vim extends the searching function with powerful patterns that can pinpoint specific text, and also supports the ability to search and replace text that has been matched.