7

say, I want to search for a particular text withing a function block. The present way, that i am implementing is selecting the block of code from within the function brackets with vi{ and then copying it and pasting it to a new file. After that I am searching for the text within the new file with /<search-text>

I want to know, if there is a short cut to this?

isnvi23h4
  • 1,910
  • 1
  • 27
  • 45
  • In emacs we would use `narrow-to-region` (more specifically, `narrow-to-defun`). I believe vim has a few plugins emulating this behavior with similar names. It more or less automates exactly what you're doing manually right now. – Randy Morris Jun 02 '16 at 13:11

3 Answers3

12
vi{
:'<,'>g/foo/#

The '<,'> range is inserted automatically.

See :help range and :help :g.

romainl
  • 186,200
  • 21
  • 280
  • 313
6

I think this might be what you are looking for:

Limiting search scope for code in Vim

Using /\%Vsearch pattern should get you what you want after you have selected the block of code you wish to search in. You enter visual mode by hitting v and moving the cursor around to highlight the block you are searching in.

AMcCracken
  • 113
  • 1
  • 6
2

The almost exact same question has been asked last week on vi.SE.

While \%V can restrict the search to the current visually selected text (which is the precise answer to your question, but not to your indirectly expressed need), selecting the current function is much more tricky than a simple vi{. A perfect and simple way to select the current function requires scripting. That's where my answer on vi.SE kicks in.

Community
  • 1
  • 1
Luc Hermitte
  • 31,979
  • 7
  • 69
  • 83