15

I have looked at the following question:

How to comment out a block of Python code in Vim

But that does not seem to work for me. How do I comment code easily without resorting to plugins/scripts?

Community
  • 1
  • 1
Samaursa
  • 16,527
  • 21
  • 89
  • 160

4 Answers4

30

Use ctrl-V to do a block selection and then hit I followed by //[ESC].

Alternatively, use shift-V to do a line-based select and then type :s:^://[Enter]. The latter part could easily go into a mapping. eg:

:vmap // :s:^://<CR>

Then you just shift-V, select the range, and type // (or whatever you bind it to).

Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
  • ctrl-v or ctrl-V pastes yanked or deleted text. I am using VIM 7.3. – Samaursa Mar 25 '11 at 20:38
  • @Samaursa Are you talking about insert mode or normal mode? In normal mode ctrl-V enters block select, while in insert mode (and other modes where you enter text, like : and /) it enables "verbatim" for the next keypress. It sounds like you may have some sort mapping that's altering this behavior. Try using `:map`, `:nmap' or `:imap` to see what's going on. – Laurence Gonsalves Mar 25 '11 at 23:14
  • 2
    might be using the mswin.vim script. It maps the ^V and ^C to the windows standard cut and paste. Try ^Q - (See gui_w32.txt - CTRL-V-alternative in the vim help). – PAntoine Mar 29 '11 at 10:06
  • @Laurence: Thanks, that was useful:Use ctrl-V to do a block selection and then hit I followed by //[ESC]. – user2023370 Jul 26 '11 at 11:43
20

You can add this to your .vimrc file

map <C-c> :s/^/\/\//<Enter>

Then when you need to comment a section just select all lines (Shift-V + movement) and then press CtrlC.

To un-comment you can define in a similar way

map <C-u> :s/^\/\///<Enter>

that removes a // at begin of line from the selected range when pressing CtrlU.

6502
  • 112,025
  • 15
  • 165
  • 265
9

You can use the NERD commenter plugin for vim, which has support for a whole bunch of languages (I'm sure C++ is one of them). With this installed, to comment/uncomment any line, use <Leader>ci. To do the same for a block of text, select text by entering the visual mode and use the same command as above.

There are other features in this such as comment n lines by supplying a count before the command, yank before comment with <Leader>cy, comment to end of line with <Leader>c$, and many others, which you can read about in the link. I've found this plugin to be extremely useful and is one of my 'must have' plugins.

abcd
  • 41,765
  • 7
  • 81
  • 98
  • I'm completely in love with "sexy" comments. Although it's a bit annoying for my coworkers when they want to undo them ... =) – Jim Mitchener Mar 25 '11 at 23:11
3

There's always #ifdef CHECK_THIS_LATER ... #endif which has the advantage of not causing problems with nested C-style comments (if you use them) and is easy to find and either uncomment or remove completely later.

Mark B
  • 95,107
  • 10
  • 109
  • 188