Peeter Joot's (OLD) Blog.

Math, physics, perl, and programming obscurity.

vim: filtering a function body through a script

Posted by peeterjoot on March 9, 2010

While working in a coworker’s cubicle today, I casually ran the following from my vim command prompt

:,/^}/!pdcode -i 1 -s 1

I got a “whoa, what the hell was that” in response, since it was apparently not obvious. There’s really three parts to this. The first is a range expression. In vim (or vi) one can run a command on some set of lines. For example, to delete lines 4 to 8 one would do:

:4,8 d

or to delete 4 lines starting from the current position you could do (without knowing your line number)

:,+4 d

The comma by itself essentially means the current line number, so this is a starting line number of the current spot continuing for 4 additional lines down.

Now, part of the power of the line selection is the fact that one can use search expressions instead of numbers. So, I can run something like:

:,/^}/ d

and this will delete all the lines until the first line that starts with a ending curly brace. The ^ (carat) symbol is a special regular expression indicating the begining of the line, so /^}/ would not match a line that happened to have a brace somewhere else as in the following example.

if ( blah ) { }

Next ingredient is the ! (exclaimation). This says to take the selected lines and pipe them through a filter (something that takes stdin and produces modified stdout, such as grep). In my case, the script was ‘pdcode -i 1 -s 1’. This happens to be a little script I wrote, and it takes all lines like

pdTraceCodePath( 10 ) ;

in a function and renumbers them using the desired step and increment size. For reference this pdTraceCodePath is an internal db2 trace macro that we have that just adds a bit in a 64-bit word, so that later if we want a tracer of the codepath taken (all the branches) we can just dump out this single bitmask and know what the program flow was.


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: