Code munging with vim: if modifier to if block

Reading time: 1 minute

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.

•      •      •

If you enjoyed this or have feedback, please let me know by or