Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim command to comment out a selection of lines?

Tags:

vim

Say I have a bunch of lines:

@Override
public void draw(Graphics g) {
    g.setColor(Color.MAGENTA);
    g.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
    g.setColor(Color.BLACK);
    g.drawRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}

When I want to comment them out with // (i prefer line comments instead of block comments), what I do is:

  • Place the cursor infront of the @ symbol
  • Ctrl-V: Switch to enter block-select mode
  • Select the column down to the } closing parenthesis using multiple hits of j
  • Shift-I: to enter block-insert
  • Type //
  • ESC to excit
  • Enter to finish the command

--> The lines are now commented out.

Is there an easier way where I don't need to do the block-select? I found I can use a substitution like :'<, '>s/^/\/\///g but this has two problems:

  1. Its very clumsy and error prone to type (multiple forward and backward slashes need to be escaped)
  2. It places the comment symbols (//) at the beginning of the line (position 0), not at the position where the first character of that line was (so indentation is lost).

How can I insert // on the selected lines at the position of the first character of each line using Vi?

like image 629
TMOTTM Avatar asked Sep 13 '25 09:09

TMOTTM


2 Answers

You can define a custom mapping or command for your :substitute.

However, there are several commenter plugins that do this very well, and those are generic (and often extensible) so that they work for any filetype:

  • NERD Commenter plugin
  • tComment plugin
  • commentary.vim plugin

I'd highly recommend to use one of those plugins instead of trying to reinvent a poor solution yourself.

like image 190
Ingo Karkat Avatar answered Sep 16 '25 00:09

Ingo Karkat


I use Commentary as in the other answer, but a few thoughts:

  • <C-v>jjjjj could be <C-v>} or <C-v>/}<CR>
  • :substitute doesn’t have to use / as a separator: :'<,'>s-^-//
  • with a visual selection, you can also do :'<,'>normal! I//
like image 20
D. Ben Knoble Avatar answered Sep 15 '25 22:09

D. Ben Knoble