Thursday, February 17, 2011

Vim Usage: batch comment out in program code

When doing programming, commenting out some code for debugging is needed in many cases. In fact, most IDE like my favourite java IDE, Eclipse, they include this function already. You can select the lines you need to comment out/undo comment by using their fancy edit tab. In vim, how can you do that?

There are so many solutions in vim.

Method 1: 
If you are using your own vim and you need to do commenting out code very often, I suggest you to use vim plugin - comments. The web site includes the installation guide and how to use it. You can check it.

Method 2:
You can use block selection mode in vim. To enter block selection mode, press "Ctrl - v". Then, use arrow keys or "h j k l" to move the cursor and select the lines you need to comment out. Then, press "I" which mean insertion at the beginning of line. Depending on your programming language, you can input "//" for C, C++ or java, etc, or "#" for shell script, python, etc. Finally, press "Esc" to escape the insert mode. See...Vim will automatically insert the comment symbol for the lines you selected.

To uncomment out the lines, use "Ctrl - v" again to enter block selection mode. Highlight all comment symbol, then press "d". All the characters you selected will be deleted. Cool!

Method 3: 
Last time you talked about mastering replacing function in Vim. You can use this to comment lines also. (Want to have more detail, please refer to my post)
To comment lines, ":[startline], [endline]s/^/[comment symbols]/g"
This means replace "^" with comment symbols from startline to endline globally. What "^" means is the beginning of line. This is the same meaning in Regex (Regex is very useful in vim, and in *nix system).
To uncomment lines,  ":[startline], [endline]s/^[comment symbols]//g"
This means replace comment symbols which are located at the beginning of line to empty. In order words, to delete all comment symbols which are located at the beginning of line.
Example (remember to use appropriate seperator):
  • add // within line 10 and line 20: ":10,20s#^#//#g"
  • uncomment within line 10 and line 20: ":10,20s#^//##g"
  • add # within line 10 and line 20: ":10,20s/^/#/g"
  • uncomment within line 10 and line 20: ":10,20s/^#//g"
In fact, the best way is to use "+" as separator as there is no programming language use "+" as separator in my knowledge.
  • add // within line 10 and line 20: ":10,20s+^+//+g"
  • uncomment within line 10 and line 20: ":10,20s+^//++g"
  • add # within line 10 and line 20: ":10,20s+^+#+g"
  • uncomment within line 10 and line 20: ":10,20s+^#++g"

No comments:

Post a Comment