Thursday, February 6, 2014

Quick commenting multiple lines in VIM with a map

A nice, and reasonably easy feature to get a handle on in Vim is key mapping. You can map a key combination to another key combination. In order to comment a line with // at the beginning of the line we would type the following commands in vim:

  0  - move to beginning of the line
  i   - insert mode
  //  - the comment syntax
  <esc> - back to normal mode
  j - move down to the next line

so we can map that series of comands in to an easy to remember key combination like this:

:nmap cc 0i//<esc>j

This works great for one line, but what about where you want to comment out multiple lines you ask? It's a pretty reasonable request!

Well, if we simply right 2cc, the 2 will be appended to the 0, which will be equivalent to typing 20i//j, which is not what we want. Try it!

The solution is to use a concept called register, which will define the command as a block, prevent the appending we say previously. It will look like the following

:nmap cc @='0i//j<C-V><esc>'<C-R>

Note: registers must be followed by a <C-R>, and if you want to put an esc character within the registered command, you must preceed it with a <V-C>.

Note: you could replace 0i with I (capital i)

1 comment:

  1. Fantastic goods from you. I've understand your stuff previous to and you're just too wonderful. I really like what you've acquired here, really like what you're stating and the way in which you say it. You make it enjoyable and you still care for to keep it smart. RTC bus advertising in Vadodara advertisements are predetermined by specialized professionals which gives a sparkler clear view of the advertisement without any wrinkles. They do not negotiation on the effort done and there will be no genuine report. They give details to the client by give billboards of both plus each classified advertisement.