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)

Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Thank you so much for the marvelous post on Times of Transition. Very interesting tips and we can apply in our real life. You are the great author and I appreciate your writing skill. It's in reality a great and helpful piece of info. I am satisfied that you shared this helpful info with us. Please keep us informed like this. Thank you for sharing.
    Best essay writing service

    ReplyDelete

Post a Comment

Popular posts from this blog

AngularJs: User friendly date display with AngularJs and MomentJs

Nerd Tree: A File Explorer with Mac Vim

Getting started with Grails functional tests using Geb + Spock