Uncategorized


Personal coding styles can be a big thing for some people. It can take a while for some people to figure out what styles are their favorite. For instance: I used to code by putting curly braces on their own lines; I have since changed. Unfortunately, I’m constantly coming across my own code (and the code of others) where this coding style is still practiced. For a while I’ve been using a couple of Vim commands to help search and replace for these curly braces quickly and easily. I figured others might be able to use these commands too.

Let’s start with the original code where the curly braces are on their own lines:

if ($this) 
{ 
    dostuff();
} 
else if ($other)
{
    dosomethingelse();
}
else 
{
    dothattoo();
}

Now, we can use one, or a combination of, these commands to reformat the code so the curly braces are not on their own lines. First we have:

%s/)\s*\n\s*{/) {/pg

This command will replace the instances where we have if statements followed by a curly brace on the next line. So, it will turn this:

if ($this) 
{

…into this:

if ($this) {

The next command is:

%s/}\s*\n\s*else\s*\n\s*{/} else {/pg

This will replace the areas where an else statement is in the middle of two curly braces. It will turn this:

}
else 
{

…into this:

} else {

Lastly, we have:

%s/}\s*\n\s*else if (/} else if (/pg

This will help us with the areas where we have else if statements in between two curly braces. It will turn this:

} 
else if ($other)
{

…into this:

} else if ($other) {

So, in the end you get your nicely formatted code:

if ($this) {
    dostuff();
} else if ($other) {
    dosomethingelse();
} else {
    dothattoo();
}

There you go!

If you enjoyed this post, then please consider subscribing to my feed.

  • Patrick

    hmm… sounds like you’re fighting up-hill… try this in normal mode:

    =}

  • I’ve been looking for exactly this. thanks!