Here's how to set keyboard shortcuts to comment/uncomment in Vim. The same shortcut will work for block comments and block uncomments.


Include the following in your vim settings file, which is probably ~/.vimrc on a Linux machine.

map <C-C> :s:^:#<CR>
map <C-T> :s:^#<CR>

Now Ctrl+C maps to comment and Ctrl+T maps to uncomment. And we get this:

Replace # with the comment symbol for your language. In C/C++, comments are done with two forward slashes //, but they need to be escaped in the rc file. That leads to:

map <C-C> :s:^:\/\/<CR>
map <C-T> :s:^\/\/<CR>


The problem with the method above is that the comment symbol is placed at the beginning of the line, which may not be what you want for indented lines. You may want the symbol to be just to the left of the first non-whitespace character, like so:

(If you can't tell the difference, here the # sign is inserted immediately to the left of 'print', at the 5th column. In the simpler version, it was placed before the tab space to the left of 'print', at the 1st column.)

The shortcuts for this behaviour are:

map <C-C> :s:^\(\s*\):\1#<CR>
map <C-T> :s:^\(\s*\)#:\1<CR>

The shortcuts are pretty interesting themselves. Maybe I'll explain them some other time.

Hope this was useful!