Vim Tips Wiki
(Uploaded by JohnBot from a locally edited file)
m (Undo revision 39039 by 94.71.153.21 (talk))
Tag: sourceedit
(44 intermediate revisions by 15 users not shown)
Line 1: Line 1:
{{Duplicate|5}}
 
{{review}}
 
 
{{TipImported
 
{{TipImported
 
|id=1
 
|id=1
|previous=1504
+
|previous=
 
|next=2
 
|next=2
|created=February 24, 2001
+
|created=2001
 
|complexity=basic
 
|complexity=basic
|author=scott
+
|author=
|version=5.7
+
|version=6.0
 
|rating=5333/1765
 
|rating=5333/1765
  +
|category1=Getting started
 
|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 '''*''' key to search forwards for the current word, or<br>
 
  +
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.
press the '''#''' key to search backwards.
 
   
  +
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).
After searching, press '''n''' (next) to search again, or<br>
 
press '''N''' to search in the reverse direction.
 
   
  +
==Searching for the current word==
Using '''*''' or '''#''' searches for the exact word at the cursor (searching for ''rain'' would not find ''rainbow'').
 
 
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.
   
 
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'').
Use '''g*''' or '''g#''' if you don't want to search for the exact word.
 
   
 
Use <code>g*</code> or <code>g#</code> if you don't want to search for the exact word.
See [[VimTip14|Highlighting]] for information about highlighting search matches.
 
   
  +
===Using the mouse===
==Comments==
 
  +
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.
TODO: merge with [[VimTip5]]
 
   
  +
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:
----
 
  +
<pre>
Another thing worth knowing that is related to this: when entering a search, hit &lt;C-R&gt;&lt;C-W&gt; and the word under the cursor will appear in your search. This is very useful if you want to search for some variation of the word under the cursor.
 
  +
:set mousemodel=extend
  +
</pre>
   
  +
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.
----
 
If you have already searched anything, type '''/''' or '''?''' and use arrow up/down to get the last search patterns/commands.
 
   
  +
==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.
Here's a mapping that lets */# search for the selected text in VISUAL MODE. Put this into your .vimrc file:
 
   
  +
Suppose the cursor is on a word, and you want to search for a similar word.
" Search for selected text in visual mode with */#
 
" effect: overrides unnamed register
 
" Simplest version: vnoremap * y/&lt;C-R&gt;"&lt;CR&gt;
 
" Better one: vnoremap * y/\V&lt;C-R&gt;=escape(@@,"/\\")&lt;CR&gt;&lt;CR&gt;
 
" This is so far the best, allowing all selected characters and multiline selection:
 
   
  +
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>.
" Atom \V sets following pattern to "very nomagic", i.e. only the backslash has special meaning.
 
" As a search pattern we insert an expression (= register) that
 
" calls the 'escape()' function on the unnamed register content '@@',
 
" and escapes the backslash and the character that still has a special
 
" meaning in the search command (/|?, respectively).
 
" This works well even with &lt;Tab&gt; (no need to change ^I into \t),
 
" but not with a linebreak, which must be changed from ^M to \n.
 
" This is done with the substitute() function.
 
vnoremap * y/\V&lt;C-R&gt;=substitute(escape(@@,"/\\"),"\n","\\\\n","ge")&lt;CR&gt;&lt;CR&gt;
 
vnoremap # y?\V&lt;C-R&gt;=substitute(escape(@@,"?\\"),"\n","\\\\n","ge")&lt;CR&gt;&lt;CR&gt;
 
   
  +
After searching, press Ctrl-o to [[VimTip10|jump back]] to your previous position (then Ctrl-i will jump forwards).
----
 
here's a tweak of that which works in --SELECT-- mode:
 
   
  +
After searching, an empty search pattern will repeat the last search. This works with <code>/</code>, <code>:s</code> and <code>:g</code>.
vnoremap &lt;M-/&gt; y/\V&lt;C-R&gt;=substitute(escape(@@,"/\\"),"\n","\\\\n","ge")&lt;CR&gt;&lt;CR&gt;gV
 
vnoremap &lt;M-?&gt; y?\V&lt;C-R&gt;=substitute(escape(@@,"?\\"),"\n","\\\\n","ge")&lt;CR&gt;&lt;CR&gt;gV
 
   
  +
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]].
(note that i map the commands to META-/ and META-? instead of * and # because i want to keep the option of replacing the selection with */#.)
 
   
  +
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.
----
 
&lt;C-R&gt;&lt;C-W&gt; means 'Hold down CTRL, press R, press W, release CTRL'. Or, verbally, Control R, Control W.
 
   
  +
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 also jump backwards after a * by using &lt;C-o&gt; as in control-o. control-i will let you jump forward again. You guessed it, it is a jump stack.
 
   
  +
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}}
also I toggle highlighting when doing a search, and turn it off when I have stopped searching. The next search turns it back on again.
 
   
  +
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}}
from my _vimrc
 
   
  +
==Case sensitivity==
" don't leave highlighting on for ever, but turn back when a new search
 
  +
By default, searching is case sensitive (searching for "the" will not find "The").
" starts or the last one is repeated
 
nnoremap &lt;F7&gt; :se nohls&lt;cr&gt;
 
nnoremap n :set hls&lt;CR&gt;n
 
nnoremap N :set hls&lt;CR&gt;N
 
nnoremap * :set hls&lt;CR&gt;*
 
nnoremap # :set hls&lt;CR&gt;#
 
nnoremap / :set hls&lt;CR&gt;/
 
nnoremap ? :set hls&lt;CR&gt;?
 
   
  +
With the following in your vimrc (or entered via a [[VimTip920|toggle mapping]]), searching is not case sensitive:
----
 
  +
<pre>
Your mapping is not necessary, except F7. Instead of using ":set noh" use
 
  +
:set ignorecase
":noh". Rest is done automaticaly.
 
  +
</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.
----
 
From my .vimrc :
 
" Clears search highlighting by just hitting a return.
 
" The &lt;BS&gt; clears the command line.
 
" (From Zdenek Sekera [zs@sgi.com] on the vim list.)
 
" I added the final &lt;cr&gt; to restore the standard behaviour of
 
" &lt;cr&gt; to go to the next line
 
:nnoremap &lt;CR&gt; :nohlsearch&lt;CR&gt;/&lt;BS&gt;&lt;CR&gt;
 
I like this approach: &lt;CR&gt; is more likely than most other keys, at least when in normal mode, and you don't loose any key with this approach.
 
   
  +
If <code>'ignorecase'</code> is on, you may also want:
----
 
  +
<pre>
How would I use the '*' command to search for an word that has '-' characters within it. I find it only searches for the partial word delimited by '-'
 
  +
:set smartcase
  +
</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.
----
 
set iskeyword to include '-' and the dash will be considered as a part of the word.
 
   
  +
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).
----
 
On UK keyboards, &lt;Shift&gt;-&lt;3&gt; works just like # for searching backwards.
 
That's because &lt;Shift&gt;-&lt;3&gt; gives # on most other countries keyboards,
 
although it gives the pound currency symbol on UK keyboards.
 
Touch typists should appreciate this because it is the left-hand equivalent of
 
how you type * with &lt;Shift&gt;-&lt;8&gt;, whereas the # on UK keyboards is way over
 
next to the return key.
 
   
  +
When programming, there is generally no reason to want <code>'smartcase'</code> to apply when you press <code>*</code>. For other situations, use:
----
 
  +
<pre>
I like to have my searches visible most of the time but in order to clear the searches only when I want to I mapped F3 to clear the search buffer.
 
  +
:nnoremap * /\<<C-R>=expand('<cword>')<CR>\><CR>
  +
:nnoremap # ?\<<C-R>=expand('<cword>')<CR>\><CR>
  +
</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.
:nmap &lt;F3&gt; :let @/=""&lt;CR&gt;
 
   
  +
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).
----
 
My favourite easy-to-remember way of removing search hilight is Alt-/
 
   
  +
==Show the next match while entering a search==
" Alt / removes search highlight
 
  +
To move the cursor to the matched string, while typing the search pattern, set the following option in your [[vimrc]]:
nnoremap &lt;silent&gt; ? :nohlsearch&lt;CR&gt;
 
  +
<pre>
  +
:set incsearch
  +
</pre>
   
  +
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.
----
 
When you have searched for a particular word using *, you would like to replace the * highlighted words, then you can use
 
:%s//new/g
 
/ carries the highlighed buffer.
 
   
  +
==Other search options==
Similarly, with global command, :g/ will give you all the matches of the * searched pattern. For the same reason as, / carries the last highlighed buffer and p[rint] goes by default with :g[lobal] command.
 
  +
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>
Another way to save lot of typos:
 
  +
: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.
Figure out how many times do we type the same word in a file. Here is a way to automate that:
 
Once you have typed a word like "my_big_variable_name_followed_by_suffixes" then
 
when you want to type it again, in insert mode, just type m and then hit 'p', while holding ctrl key.
 
It will show you all the matching word in current file one-by-one that matches the word. Once you have found the word, release the ctrl p.
 
   
  +
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]].
If you have lot of words starting with 'm', you can start with 'my' and so on.
 
   
  +
==See also==
PS: I had posted this tip before but since this turns to the nice thread , thought of dropping here again.
 
  +
;Searching
 
*[[VimTip14|Highlighting search matches]]
  +
*[[VimTip171|Search for visually selected text]]
  +
*[[VimTip188|Search patterns]] regex tutorial with useful searches
  +
*[[VimTip798|Search for current word in new window]]
  +
*[[VimTip528|Make search results appear in the middle of the screen]]
  +
*[[VimTip31|Search and replace]] using <code>:s</code> to substitute text
  +
*Browse the [[:Category:Searching|searching category]] for more.
   
  +
;Searching in multiple files:
----
 
  +
*[[VimTip1543|Find in files within Vim]]
Another tip: the * without n
 
   
  +
;Finding a file from its name:
I find it very useful to highlight the word under the cursor like *, but _without_ jumping directly to the next match.
 
  +
*[[VimTip1146|Project browsing using find]]
This way, you can quickly see the highlights in the current page without scrolling anything, and that's something you might want to do often! Then you can move to the first (ggn), last (GN), next (n) or previous (N) match as usual.
 
  +
*[[VimTip1234|Find files in subdirectories]]
   
  +
==References==
The basic command is:
 
  +
*{{help|*}}
:let @/="&lt;C-r&gt;&lt;C-w&gt;"&lt;CR&gt;
 
  +
*{{help|tag=%3CS-LeftMouse%3E|label=&#60;S-LeftMouse&#62;}}
  +
*{{help|:<cword>|:&lt;cword&gt;}}
  +
*{{help|jump-motions}}
  +
*{{help|'iskeyword'}} controls which characters <code>*</code> considers make a word
   
 
==Comments==
And I have set it as follows in my .vimrc :
 
 
On UK keyboards, <Shift-3> produces ₤ but works just like <code>#</code> for searching backwards.
map &lt;F10&gt; :set hls&lt;CR&gt;:let @/="&lt;C-r&gt;&lt;C-w&gt;"&lt;CR&gt;
 
map &lt;F11&gt; :nohls&lt;CR&gt;
 
 
...this way, &lt;F10&gt; highlights and &lt;F11&gt; unhighlights.
 
 
----
 
I've always found hlsearch distracting, but when francoissteinmetz posted his
 
&lt;F10&gt; and &lt;F11&gt; maps for highlighting the current word, I decided to change it
 
slightly so that F10 toggles the hlsearch setting. This means F11 is not used,
 
which frees it for some other map.
 
 
Here is my toggle version of francoissteinmetz's &lt;F10&gt; map,
 
 
map &lt;F10&gt; :set invhls&lt;CR&gt;:let @/="&lt;C-r&gt;&lt;C-w&gt;"&lt;CR&gt;/&lt;BS&gt;
 
 
The 'inv' prefix on a boolean setting toggles it. The trailing '/&lt;BS&gt;' is
 
from another posting in this tip; it just clears the clutter left in the :
 
command area.
 
 
Just position the cursor to an interesting word, press F10, and all occurences
 
of that word are highlighted. Use commands like n and N to search up and down.
 
When you're done, press F10 again and the highlighting is off.
 
 
It's helpful if you think of F10 as toggling the "Highlight" search mode.
 
 
----
 
[[Category:Searching]]
 

Revision as of 22:15, 17 April 2016

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.

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.