Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

vi - Limiting search scope for code in Vim

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...