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).

Comment Icon

2 Comments

The most recent comment was on Wed, 14th Jan 2009 - 08:49

That is a very thorough script! Thanks for the resource :)

Add new comment

Filtered HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd> <img> <p>
  • You can use BBCode tags in the text. URLs will automatically be converted to links.
  • You can enable syntax highlighting of source code with the following tags: <code>, <pre>, <bash>, <css>, <html>, <js>, <jquery>, <mysql>, <php>. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.