Neat commenting in Vim

I am a bit of a "neat geek" when it comes to coding. Things should be indented neatly and should have well laid out comments! Why? Well… It's easy to do and in 6 months time when you look at your code you will appreciate it! It will also me even more appreciated by another developer in less than 6 months time ;-)

I recently was looking through some old code and the 1-line comments were in an inconsistent form, for example:

  1. //xxxx
  2. // xxxx
  3. //Xxxx
  4. // Xxx

I personally prefer the 4th coding style (with a space and initial capital), so I started googling around for a solution using Vim and Regular Expressions. I found the following two search/replace phrases worked perfectly:

  • :%s=\/\/\([^ ]\)=// \1=
  • :%s=\/\/ \([a-z]\)=// \u\1=
[adsense:468x60:4496506397]

The first one does a search for anything containing a "slash-slash" followed by a non-space character. The non-space character is grouped so we can reference it in the replace. The replace phrase changes that match to a "slash-slash" followed by a space and finally the character that was matched in the group.

The second is VERY similar to the first, except we search for "slash-slash-space" followed by a group matching a lowercase a to z range. The replacement is "slash-slash-space" followed by the group match converted to upper case (\u is a Vim option for conversion to uppercase).