Vim Tips Wiki
m (Reverted edits by 83.56.20.141 (talk) to last version by 85.31.194.186)
(34 intermediate revisions by 17 users not shown)
Line 1: Line 1:
__NOTOC__
 
 
{{TipImported
 
{{TipImported
 
|id=1
 
|id=1
 
|previous=
 
|previous=
 
|next=2
 
|next=2
|created=February 24, 2001
+
|created=2001
 
|complexity=basic
 
|complexity=basic
|author=Scott+Yegappan
+
|author=
|version=5.7
+
|version=6.0
 
|rating=5333/1765
 
|rating=5333/1765
|category1=Searching
+
|category1=Getting started
|category2=
+
|category2=Searching
 
}}
 
}}
  +
This tip shows how to search using Vim, including use of <code>*</code> (the ''super star'') to search for the current word. Search options are described, and the [[#See also|see also]] section links to other useful searching tips.
In normal mode, move the cursor to any word. How do you search for the next occurrence of that word?
 
   
  +
==Basic searching==
Press the <tt>*</tt> key to search forwards for the current word, or press <tt>#</tt> to search backwards.
 
  +
In normal mode you can search forwards by pressing <code>/</code> (or <code>&lt;kDivide&gt;</code>) then typing your search pattern. Press Esc to cancel or press Enter to perform the search. Then press <code>n</code> to search forwards for the next occurrence, or <code>N</code> to search backwards. Type <code>ggn</code> to jump to the first match, or <code>GN</code> to jump to the last.
   
  +
Note: <code>ggn</code> skips first match if it is at row 1 column 1. Type <code>Gn</code> to jump to the real first match. For this, <code>'wrapscan'</code> must be on (default).
Using <tt>*</tt> or <tt>#</tt> searches for the exact word at the cursor (searching for ''rain'' would not find ''rainbow'').
 
   
  +
Search backwards by pressing <code>?</code> then typing your search pattern. Pressing <code>n</code> searches in the same direction (backwards), while <code>N</code> searches in the opposite direction (forwards).
Use <tt>g*</tt> or <tt>g#</tt> if you don't want to search for the exact word.
 
   
===Using the mouse===
+
==Searching for the current word==
 
In normal mode, move the cursor to any word. Press <code>*</code> to search forwards for the next occurrence of that word, or press <code>#</code> to search backwards.
With the proper settings, you can search for an exact word using the mouse.
 
   
 
Using <code>*</code> (also &lt;kMultiply&gt;, &lt;S-LeftMouse&gt;) or <code>#</code> (also &lt;S-RightMouse&gt;) searches for the exact word at the cursor (searching for ''rain'' would not find ''rainbow'').
Shift-LeftClick a word to search forwards, or Shift-RightClick to search backwards.
 
  +
 
Use <code>g*</code> or <code>g#</code> if you don't want to search for the exact word.
  +
  +
===Using the mouse===
 
With appropriate settings, you can search for an exact word using the mouse: Shift-LeftClick a word to search forwards, or Shift-RightClick to search backwards.
   
 
This needs a GUI version of Vim (gvim), or a console Vim that accepts a mouse. You may need the following line in your [[vimrc]] to enable mouse searches:
 
This needs a GUI version of Vim (gvim), or a console Vim that accepts a mouse. You may need the following line in your [[vimrc]] to enable mouse searches:
Line 32: Line 37:
 
In gvim, click the Edit menu, then Global Settings, then the "tear off" bar at the top. That will show a floating Global Settings menu with useful ''Toggle Pattern Highlight'' and ''Toggle Ignore-case'' commands.
 
In gvim, click the Edit menu, then Global Settings, then the "tear off" bar at the top. That will show a floating Global Settings menu with useful ''Toggle Pattern Highlight'' and ''Toggle Ignore-case'' commands.
   
===More searching===
+
==More searching==
 
Vim maintains a [[VimTip45|search history]]. Type <code>/</code> or <code>?</code> and use the arrow up/down keys to recall previous search patterns. You can edit a pattern, and press Enter to search for something different.
After searching, press <tt>n</tt> for the next match, or <tt>N</tt> to search in the reverse direction.
 
 
Vim maintains a [[VimTip45|search history]]. Type <tt>/</tt> or <tt>?</tt> and use the arrow up/down keys to recall previous search patterns. You can edit a pattern, and press Enter to search for something different.
 
   
 
Suppose the cursor is on a word, and you want to search for a similar word.
 
Suppose the cursor is on a word, and you want to search for a similar word.
   
Press <tt>/</tt> then <C-r><C-w> to copy the current word to the command line. You can now edit the search pattern and press Enter. Use <C-r><C-w> for a <cword>, or <C-r><C-a> for a <cWORD>.
+
Press <code>/</code> then Ctrl-r then Ctrl-w to copy the current word to the command line. You can now edit the search pattern and press Enter. Use Ctrl-r Ctrl-w for a <cword>, or Ctrl-r Ctrl-a for a <cWORD>.
   
  +
After searching, press Ctrl-o to [[VimTip10|jump back]] to your previous position (then Ctrl-i will jump forwards).
<C-r><C-w> is Control-R then Control-W (hold down <tt>Ctrl</tt> and press <tt>r</tt> then <tt>w</tt>).
 
   
After searching, use <C-o> to jump back to your previous position (then <C-i> will jump forwards).
+
After searching, an empty search pattern will repeat the last search. This works with <code>/</code>, <code>:s</code> and <code>:g</code>.
   
 
So, after searching for a word, use <code>:%s//new/g</code> to change all occurrences to 'new', or <code>:g/</code> to list all lines containing the word. See [[VimTip1501|substitute last search]].
After searching, an empty search pattern will repeat the last search. This works with <tt>/</tt>, <tt>:s</tt> and <tt>:g</tt>.
 
   
 
You can enter a count before a search. For example <code>3/pattern</code> will search for the third occurrence of ''pattern'', and <code>3*</code> will search for the third occurrence of the current word.
So, after searching for a word, use <tt>:%s//new/g</tt> to change all occurrences to 'new', or <tt>:g/</tt> to list all lines containing the word. See [[VimTip1501|Substitute last search]].
 
   
  +
You can highlight all search matches (and quickly turn highlighting off), and you can use a mapping to highlight all occurrences of the current word without moving (see [[VimTip14|highlight matches]]).
You can enter a count before a search. For example <tt>3/pattern</tt> will search for the third occurrence of ''pattern'', and <tt>3*</tt> will search for the third occurrence of the current word.
 
   
  +
A search can include an offset to position the cursor. For example, searching with <code>/green</code> positions the cursor at the beginning of the next "green", while <code>/green/e</code> positions the cursor at the end of the next "green". {{help|search-offset}}
====Highlight matches without moving====
 
It can be useful to highlight the word under the cursor like <tt>*</tt>, but ''without'' jumping to the next match. Then you can see the search highlights on the current screen, without any scrolling. Move to the first (<tt>ggn</tt>), last (<tt>GN</tt>), next (<tt>n</tt>) or previous (<tt>N</tt>) match as usual.
 
   
  +
A search pattern can include characters with codes specified in decimal or hex. For example, searching with <code>/\%d65</code> or with <code>/\%x41</code> both find '<code>A</code>' (character decimal 65 = hex 41), and searching with <code>/\%d8211</code> or with <code>/\%u2013</code> both find '<code>–</code>' (a Unicode en dash). {{help|/\%d}}
The basic command is (type Ctrl-r then Ctrl-w to insert the current word):
 
  +
  +
==Case sensitivity==
  +
By default, searching is case sensitive (searching for "the" will not find "The").
  +
  +
With the following in your vimrc (or entered via a [[VimTip920|toggle mapping]]), searching is not case sensitive:
 
<pre>
 
<pre>
  +
:set ignorecase
:let @/="<C-r><C-w>"<CR>
 
 
</pre>
 
</pre>
   
  +
Now the command <code>/the</code> will find "the" or "The" or "THE" etc. You can use <code>\c</code> to force a pattern to be case insensitive, or <code>\C</code> to force a pattern to be case sensitive. For example, the search <code>/the\c</code> is always case insensitive, and <code>/the\C</code> is always case sensitive, regardless of the <code>'ignorecase'</code> option.
The following map uses F10 to highlight all occurrences of the current word, and F11 to unhighlight (put in your vimrc):
 
  +
<pre>
 
  +
If <code>'ignorecase'</code> is on, you may also want:
nnoremap <F10> :set hls<CR>:exec "let @/='\\<".expand("<cword>")."\\>'"<CR>
 
nnoremap <F11> :nohls<CR>
 
</pre>
 
It is functionally the same as doing <C-r><C-w> manually, but using "<cword>" avoids errors if the cursor is not over anything.
 
Here is another version that uses F10 to toggle search highlighting (F11 is not used).
 
 
<pre>
 
<pre>
  +
:set smartcase
nnoremap <F10> :set invhls<CR>:exec "let @/='\\<".expand("<cword>")."\\>'"<CR>/<BS>
 
 
</pre>
 
</pre>
   
  +
When <code>'ignorecase'</code> and <code>'smartcase'</code> are both on, if a pattern contains an uppercase letter, it is case sensitive, otherwise, it is not. For example, <code>/The</code> would find only "The", while <code>/the</code> would find "the" or "The" etc.
The 'inv' prefix on a boolean setting toggles it. The trailing <tt>/<BS></tt> clears the command line.
 
   
  +
The <code>'smartcase'</code> option only applies to search patterns that you type; it does not apply to <code>*</code> or <code>#</code> or <code>gd</code>. If you press <code>*</code> to search for a word, you can make <code>'smartcase'</code> apply by pressing <code>/</code> then up arrow then Enter (to repeat the search from history).
Position the cursor on an interesting word, then press F10 to highlight all occurrences of that word. Use commands like <tt>n</tt> and <tt>N</tt> to search up and down. When you're done, press F10 again to toggle highlighting off.
 
   
  +
When programming, there is generally no reason to want <code>'smartcase'</code> to apply when you press <code>*</code>. For other situations, use:
Here is how to do the same for visually selected text:
 
 
<pre>
 
<pre>
 
:nnoremap * /\<<C-R>=expand('<cword>')<CR>\><CR>
function! <SID>FidgetWhitespace(pat)
 
  +
:nnoremap # ?\<<C-R>=expand('<cword>')<CR>\><CR>
let pat = substitute(a:pat,'\_s\+$','\\s\\*', '')
 
let pat = substitute(pat, '^\_s\+', '\\s\\*', '')
 
return substitute(pat, '\_s\+', '\\_s\\+','g')
 
endfunction
 
vmap <silent><M-8> :<C-U>let @/="\\V<C-R>=escape(<SID>FidgetWhitespace(escape(@*,'\')),'\"')<CR>"<CR>
 
 
</pre>
 
</pre>
   
  +
With these mappings, if <code>'smartcase'</code> is on and you press <code>*</code> while on the word "The", you will only find "The" (case sensitive), but if you press <code>*</code> while on the word "the", the search will not be case sensitive.
Replace <M-8> with the key of your choice. The function FidgetWhitespace() allows changes in whitespace for potential matches, so using the mapping while "foo bar" is selected will also highlight "foo bar" and "foo
 
bar" (separated by a newline). If you want to keep your visual selection, append 'gv' to that mapping.
 
   
  +
The mapping for <code>*</code> uses <code>/</code> to start a search; the pattern begins with <code>\<</code> and ends with <code>\></code> so only whole words are found; <code><C-R>=</code> inserts the expression register to evaluate <code>expand('<cword>')</code> which inserts the current word (similar to Ctrl-R Ctrl-W but avoiding an error when used on a blank line).
====Show the next match while entering a search====
 
  +
 
==Show the next match while entering a search==
 
To move the cursor to the matched string, while typing the search pattern, set the following option in your [[vimrc]]:
 
To move the cursor to the matched string, while typing the search pattern, set the following option in your [[vimrc]]:
 
<pre>
 
<pre>
Line 93: Line 93:
 
</pre>
 
</pre>
   
Complete the search by pressing Enter, or cancel the search by pressing Escape. When typing the search pattern, press Ctrl-L ({{help|c_CTRL-L}}) to insert the next character from the match or press Ctrl-R Ctrl-W ({{help|c_CTRL-R_CTRL-F}}) to complete the current matching word.
+
Complete the search by pressing Enter, or cancel by pressing Esc. When typing the search pattern, press Ctrl-L ({{help|c_CTRL-L}}) to insert the next character from the match or press Ctrl-R Ctrl-W ({{help|c_CTRL-R_CTRL-F}}) to complete the current matching word.
  +
  +
==Other search options==
  +
By default, the <code>'wrapscan'</code> option is on, which means that when "search next" reaches end of file, it wraps around to the beginning, and when "search previous" reaches the beginning, it wraps around to the end.
  +
  +
These examples show how to set <code>'wrapscan'</code> (abbreviated as <code>'ws'</code>):
 
<pre>
  +
:set nowrapscan " do not wrap around
  +
:set wrapscan " wrap around
  +
:set wrapscan! " toggle wrap around on/off
  +
:set ws! ws? " toggle and show value
 
</pre>
  +
  +
By default, search hits may occur in lines at the top or bottom of the window. The [[Make search results appear in the middle of the screen|<code>'scrolloff'</code> option]] controls whether context lines will be visible above and below the line containing the search hit.
  +
  +
If your text is folded, you probably want folds to automatically open to reveal search hits. To achieve that, the <code>'foldopen'</code> option should include "search" (check by entering :set&nbsp;fdo?). {{help|'foldopen'}} Conversely, this option can be used to [[Search only in unfolded text]].
   
 
==See also==
 
==See also==
  +
;Searching
 
*[[VimTip14|Highlighting search matches]]
 
*[[VimTip14|Highlighting search matches]]
 
*[[VimTip171|Search for visually selected text]]
 
*[[VimTip171|Search for visually selected text]]
  +
*[[VimTip188|Search patterns]] regex tutorial with useful searches
 
*[[VimTip798|Search for current word in new window]]
 
*[[VimTip798|Search for current word in new window]]
 
*[[VimTip528|Make search results appear in the middle of the screen]]
 
*[[VimTip528|Make search results appear in the middle of the screen]]
  +
*[[VimTip31|Search and replace]] using <code>:s</code> to substitute text
*[[VimTip1543|Find in files within Vim]]
 
 
*Browse the [[:Category:Searching|searching category]] for more.
 
*Browse the [[:Category:Searching|searching category]] for more.
  +
  +
;Searching in multiple files:
 
*[[VimTip1543|Find in files within Vim]]
  +
  +
;Finding a file from its name:
  +
*[[VimTip1146|Project browsing using find]]
  +
*[[VimTip1234|Find files in subdirectories]]
   
 
==References==
 
==References==
 
*{{help|*}}
 
*{{help|*}}
*{{help|#}}
 
*{{help|g*}}
 
*{{help|g#}}
 
 
*{{help|tag=%3CS-LeftMouse%3E|label=&#60;S-LeftMouse&#62;}}
 
*{{help|tag=%3CS-LeftMouse%3E|label=&#60;S-LeftMouse&#62;}}
*{{help|tag=%3CS-RightMouse%3E|label=&#60;S-RightMouse&#62;}}
 
 
*{{help|:<cword>|:&lt;cword&gt;}}
 
*{{help|:<cword>|:&lt;cword&gt;}}
 
*{{help|jump-motions}}
 
*{{help|jump-motions}}
*{{help|'iskeyword'}} controls which characters <tt>*</tt> considers make a word
+
*{{help|'iskeyword'}} controls which characters <code>*</code> considers make a word
   
 
==Comments==
 
==Comments==
On UK keyboards, <Shift-3> produces ₤ but works just like <tt>#</tt> for searching backwards.
+
On UK keyboards, <Shift-3> produces ₤ but works just like <code>#</code> for searching backwards.
 
----
 

Revision as of 04:33, 1 January 2019

Tip 1 Printable Monobook Next

created 2001 · complexity basic · version 6.0


This tip shows how to search using Vim, including use of * (the super star) to search for the current word. Search options are described, and the see also section links to other useful searching tips.

Basic searching

In normal mode you can search forwards by pressing / (or <kDivide>) then typing your search pattern. Press Esc to cancel or press Enter to perform the search. Then press n to search forwards for the next occurrence, or N to search backwards. Type ggn to jump to the first match, or GN to jump to the last.

Note: ggn skips first match if it is at row 1 column 1. Type Gn to jump to the real first match. For this, 'wrapscan' must be on (default).

Search backwards by pressing ? then typing your search pattern. Pressing n searches in the same direction (backwards), while N searches in the opposite direction (forwards).

Searching for the current word

In normal mode, move the cursor to any word. Press * to search forwards for the next occurrence of that word, or press # to search backwards.

Using * (also <kMultiply>, <S-LeftMouse>) or # (also <S-RightMouse>) searches for the exact word at the cursor (searching for rain would not find rainbow).

Use g* or g# if you don't want to search for the exact word.

Using the mouse

With appropriate settings, you can search for an exact word using the mouse: Shift-LeftClick a word to search forwards, or Shift-RightClick to search backwards.

This needs a GUI version of Vim (gvim), or a console Vim that accepts a mouse. You may need the following line in your vimrc to enable mouse searches:

:set mousemodel=extend

In gvim, click the Edit menu, then Global Settings, then the "tear off" bar at the top. That will show a floating Global Settings menu with useful Toggle Pattern Highlight and Toggle Ignore-case commands.

More searching

Vim maintains a search history. Type / or ? and use the arrow up/down keys to recall previous search patterns. You can edit a pattern, and press Enter to search for something different.

Suppose the cursor is on a word, and you want to search for a similar word.

Press / then Ctrl-r then Ctrl-w to copy the current word to the command line. You can now edit the search pattern and press Enter. Use Ctrl-r Ctrl-w for a <cword>, or Ctrl-r Ctrl-a for a <cWORD>.

After searching, press Ctrl-o to jump back to your previous position (then Ctrl-i will jump forwards).

After searching, an empty search pattern will repeat the last search. This works with /, :s and :g.

So, after searching for a word, use :%s//new/g to change all occurrences to 'new', or :g/ to list all lines containing the word. See substitute last search.

You can enter a count before a search. For example 3/pattern will search for the third occurrence of pattern, and 3* will search for the third occurrence of the current word.

You can highlight all search matches (and quickly turn highlighting off), and you can use a mapping to highlight all occurrences of the current word without moving (see highlight matches).

A search can include an offset to position the cursor. For example, searching with /green positions the cursor at the beginning of the next "green", while /green/e positions the cursor at the end of the next "green". :help search-offset

A search pattern can include characters with codes specified in decimal or hex. For example, searching with /\%d65 or with /\%x41 both find 'A' (character decimal 65 = hex 41), and searching with /\%d8211 or with /\%u2013 both find '' (a Unicode en dash). :help /\%d

Case sensitivity

By default, searching is case sensitive (searching for "the" will not find "The").

With the following in your vimrc (or entered via a toggle mapping), searching is not case sensitive:

:set ignorecase

Now the command /the will find "the" or "The" or "THE" etc. You can use \c to force a pattern to be case insensitive, or \C to force a pattern to be case sensitive. For example, the search /the\c is always case insensitive, and /the\C is always case sensitive, regardless of the 'ignorecase' option.

If 'ignorecase' is on, you may also want:

:set smartcase

When 'ignorecase' and 'smartcase' are both on, if a pattern contains an uppercase letter, it is case sensitive, otherwise, it is not. For example, /The would find only "The", while /the would find "the" or "The" etc.

The 'smartcase' option only applies to search patterns that you type; it does not apply to * or # or gd. If you press * to search for a word, you can make 'smartcase' apply by pressing / then up arrow then Enter (to repeat the search from history).

When programming, there is generally no reason to want 'smartcase' to apply when you press *. For other situations, use:

:nnoremap * /\<<C-R>=expand('<cword>')<CR>\><CR>
:nnoremap # ?\<<C-R>=expand('<cword>')<CR>\><CR>

With these mappings, if 'smartcase' is on and you press * while on the word "The", you will only find "The" (case sensitive), but if you press * while on the word "the", the search will not be case sensitive.

The mapping for * uses / to start a search; the pattern begins with \< and ends with \> so only whole words are found; <C-R>= inserts the expression register to evaluate expand('<cword>') which inserts the current word (similar to Ctrl-R Ctrl-W but avoiding an error when used on a blank line).

Show the next match while entering a search

To move the cursor to the matched string, while typing the search pattern, set the following option in your vimrc:

:set incsearch

Complete the search by pressing Enter, or cancel by pressing Esc. When typing the search pattern, press Ctrl-L (:help c_CTRL-L) to insert the next character from the match or press Ctrl-R Ctrl-W (:help c_CTRL-R_CTRL-F) to complete the current matching word.

Other search options

By default, the 'wrapscan' option is on, which means that when "search next" reaches end of file, it wraps around to the beginning, and when "search previous" reaches the beginning, it wraps around to the end.

These examples show how to set 'wrapscan' (abbreviated as 'ws'):

:set nowrapscan        " do not wrap around
:set wrapscan          " wrap around
:set wrapscan!         " toggle wrap around on/off
:set ws! ws?           " toggle and show value

By default, search hits may occur in lines at the top or bottom of the window. The 'scrolloff' option controls whether context lines will be visible above and below the line containing the search hit.

If your text is folded, you probably want folds to automatically open to reveal search hits. To achieve that, the 'foldopen' option should include "search" (check by entering :set fdo?). :help 'foldopen' Conversely, this option can be used to Search only in unfolded text.

See also

Searching
Searching in multiple files
Finding a file from its name

References

Comments

On UK keyboards, <Shift-3> produces ₤ but works just like # for searching backwards.