Peeter Joot's (OLD) Blog.

Math, physics, perl, and programming obscurity.

search within search in vim

Posted by peeterjoot on September 20, 2011

I was asked how to search within a function for something and report an error if not found (as opposed to continuing past that function for the pattern of interest).

I’d never done this. Something I have done a bazillion times is search and replace within a function. Suppose one has the following:

void foo( int c )
   for ( int i = 0 ; i < c ; i++ )
      bar( i ) ;

Then positioning yourself on the first line of the function, you can do something like:

:,/^}/ s/bar/Blah/

to replace bar’s with Blah’s on all lines in the range (current line), to curly brace anchored on the beginning of the line (although this requires a coding convention where that is done).

How would you search only within the current function? I tried:

:,/^}/ /bar/

but this appears to take me past my current function, to the next /bar/ match that is NOT in the specified range.

I admit this is something that would have been handy a few times. In particular, we’ve got one source file that’s now 45000 lines long. I’ve gotten messed up a few times by searching for something, and ending up in a completely different function.

Here’s what I came up with:

,/^}/ s/bar//c

Use a prompted search and replace using the /c modifier, and ‘q’uit the replace once a match is found. If no match is found in the range, one gets an error.

This seems like a somewhat abusive use of /c, but works. I’d be curious if there are any other ways?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: