Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting search scope for code in Vim

Tags:

vim

vi

How can I limit the search scope in Vim to the function/class/code block that the cursor is currently in, without having to figure out what the line numbers are? Being able to search in the visual selection would also do, as there are methods for selecting the current code block.

(Similar to this question, but more generic)

like image 651
Walter Avatar asked May 27 '10 14:05

Walter


2 Answers

For brevity:

" tldr;
v i { <ESC> /\%Vsearch-term

" Search for search-term within the current code block (defined by curly braces {}).
" Begin in normal mode, then enter the following:

" enter visual mode
v

" look for stuff in-between the current...
i

" curly braces enclosure
{

" (now the enclosure should be highlighted)

" exit visual mode
<ESC>

" search the last visual mode selection for search-term
/\%Vsearch-term

" note: to search within other enclosures, you can substitute curly braces for: 
" - parenthesis, 
" - square brackets, 
" - or other enclosure pair characters
like image 183
bagrounds Avatar answered Nov 07 '22 05:11

bagrounds


I'm going to just copy and paste the entire content of "Searching with / and ?" (within a visual selection) from the Vim Tips Wiki.

In visual mode, / and ? will update the visual selection just like any other cursor-movement command (that is, when in visual mode, searching will extend the selection).

In order to actually search within the visual selection, you will need to use the \%V atom, or use the markers defined by the visual selection with the \%>'< and \%<'> atoms. This is best done by leaving the visual selection with Esc before entering your search. You may want to consider a mapping to automatically leave visual selection and enter the appropriate atoms. For example:

:vnoremap <M-/> <Esc>/\%V

Using this mapping, you can press Alt-/ in order to automatically fill in a "range" for your search just like using an Ex command with :. To use this, move to the first line of interest and press V to start line-wise visual selection. Move down (press j for a line or } for a paragraph, etc). When you have selected the area you want to search, press Alt-/. The visual selection will be removed, and a search command will start. You will see:

/\%V

Add what you want to find, then press Enter. For example, you may enter green and see:

/\%Vgreen

When you press Enter, each occurrence of "green" will be highlighted, but only in the area that you had previously selected.

Here are two further examples that do not use a visual selection. The first command searches only in lines 10 to 20 inclusive. The second searches only between marks a and b.

/\%>9l\%<21lgreen
/\%>'a\%<'bgreen
like image 20
Mark Rushakoff Avatar answered Nov 07 '22 03:11

Mark Rushakoff