Twitter GitHub Facebook Instagram dirv.me

Daniel Irvine on building software

Autoformatting Java code in Vim, one change at a time

18 September 2014

I had a whole bunch of Java files which used Kerninghan & Ritchie style bracketing, which was causing my colleagues to vomit:

int induceVomiting()
{
    ...
}

I wasn’t massively fussed by this, but for their benefit I thought it best for me to sort this out. And so began a wild goose chase. What I was after was opening braces on the same line as the definition before it:

int smile() {
    ...
}

  • I tried astyle and uncrustify for command-line autoformatting. Unfortunately neither is Java 8 compatible and astyle has what I’d consider a serious issue with indenting.
  • I looked into using sed, but that would have involved learning about ‘hold space’ and other concepts--I’m not there quite yet.
  • Finally, I realised I can do it with vanilla Vim.

Vim has a command called argdo which runs another command on every file listed in its argument list. The argument list is, as you might expect, set when you launch Vim on the command line:

$ vim **/*.java

Or if you’ve already loaded Vim, use can use the arga command to add files to the argument list from normal mode:

:arga **/*.java

Armed with this knowledge, all I needed was a substitute command to do the search and replace. Vim’s substitute facility is simpler than sed‘s for multi-line operations like this.

:%s/\n\s*{/ {/g

And then combined with argdo:

:argdo %s/\n\s*{/ {/ge | update

Note the extra e option to the substitute command. This causes Vim to suppress the warning it would otherwise display if no substitutions were found. I’ve also added | update to ensure each file gets saved.

It’s worth noting that I feel the correct solution is to use astyle. But, given I didn’t have the time to submit a patch today, this solution seems adequate.

About the author

Daniel Irvine is a software craftsman at 8th Light, based in London. These days he prefers to code in Clojure and Ruby, despite having been a C++ and C# developer for the majority of his career.

For a longer bio please see danielirvine.com. To contact Daniel, send a tweet to @d_ir or use the comments section below.

Twitter GitHub Facebook Instagram dirv.me