commenting your source code with combo keys in vim

May 31st, 2007 mysurface Posted in Text Manipulation, vi, vim | Hits: 45976 | 5 Comments »

When I saw my colleague commenting his lines of source code with some special combo key in VC++, I would like to do that in vim too. Vim is great that it is highly flexible to extend features with your own define key combos.

Vim by default bundle with many default key bindings, fortunately you can overlay it with your own action. I find c and cc in normal mode useless for me. Therefore, I use it to performs comment and uncomment action.

What commenting action I needed? Just add a simple // to the front of each line you selected in visual mode. That means when I press select lines of code in visual mode (press v to switch to visual mode from normal mode) and hits some combos, I want all my codes commented.

:s/^/\/\//g

Uncomment action is just the opposite.

:s/^\/\///g

Okay, how the key bindings looks like? Copy those line into your ~/.vimrc


:map cc v:s/^/\/\//g <CR><CR>
:map cx v:s/^\/\///g <CR><CR>
:vmap cc :s/^/\/\//g <CR>
:vmap cx :s/^\/\///g <CR>

I am mapping cc to perform action of v:s/^/\/\//g <CR><CR>, the rest is mapped accordingly. Bare in mind for :vmap makes a constrain to key mapping, that the action will be carry on in visual mode only.

Updates:
After getting the comments and fine tune the regex part, it leads to the better one


:map cc v:s!^!//!g <CR><CR>
:map cx v:s!^\s*//!!g <CR>v=<CR>
:vmap cc :s!^!//!g <CR>
:vmap cx :s!^\s*//!!g <CR>v=

[中文翻译]

[tags]vim tips, vi, programming [/tags]

5 Responses to “commenting your source code with combo keys in vim”

  1. Actually there is some plugins out there doing exactly the same thing, in which what I am using is NERD_commenter.vim. I just assigned F9 to comment a line. If pressing nF9, n lines from the cursor position will be commented.

  2. :map cc v:s!^!//!g <CR><CR>
    :map cx v:s!^//!!g <CR><CR>
    :vmap cc :s!^!//!g <CR>
    :vmap cx :s!^//!!g <CR>

    This is a bit less confusing without the all escaping.

  3. :map cx v:s!^\s*//!!g <CR><CR>
    :vmap cx :s!^\s*//!!g <CR>

    \s* will match the leading white spaces (if any).

  4. Cool!, thanks toydi. This is what i looking for :)
    But after removing comment, the indentation will be running out of shape.
    Let me edit a bit, to make the indent remains nicely.
    :map cx v:s!^\s*//!!g <CR>v=<CR>
    :vmap cx :s!^\s*//!!g <CR>v=

  5. anonymous Says:

    you can also use Ctrl-V to go in visual block. then shift-i and finally type //

    viola…

Leave a Reply