Code munging with vim: if modifier to if block

Not infrequently, I discover I want to turn an if modifier into an if block so I can add extra logic when the conditional is true.

# from this
do_something()
  if condition();

# to this
if ( condition() ) {
  do_something();
}

I decided to automate that with a vim macro:

map ,if V:s/\(\s*\)  if \(.*\);/\1if (\2) {/<CR>kVdp>>$a;<CR><BS>}<CR><Esc>kkk^

For it to work, the if modifier has to be on a line of its own (which I usually do for code clarity) and the cursor needs to be on that line when running the macro.

Feel free to copy and adapt to your own needs and preferences.

This entry was posted in perl programming and tagged , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

© 2009-2014 David Golden All Rights Reserved