How can I comment on a single line or block of lines in Vim?

In a CSS file, this line contains more than 5 rules.

border: 1px solid black; 

I want to comment this line as follows:

 /*border: 1px solid black;*/ 

Is there a shortcut for this comment for all 5 cases?

Can I assign a key to comment on one line or block of lines?

I don’t want to search and replace this single line, I want to set the key so that when I find the line and press this key, this line will be commented out or will select a line or select a block of a line, if I press this key, this line or block lines will be commented out.

+6
source share
3 answers

I would suggest using a macro for this. Macros are automatically saved by Vim and are available through sessions.

To write the macro type: q<letter><commands>q . Where <letter> is any letter from az and indicates the register in which the macro will be saved. After that, you simply enter the commands you want to record, and finally press q again to stop recording.

In your case, you can do the following. Press q , then press a to select case a , then enter the input mode and enter /* and */ at the beginning and end of the line. Press the q button again to stop recording.

Now just move the cursor to any line and press @a to execute the macro on that line.

+10
source

Why not use a regex for this?

 :1,$s/border: 1px solid black;/\/*border: 1px solid black;\*\// 

1,$s means that your substitution should be done from line 1 to line $ , which is the last line. Keep in mind that you need to avoid characters like * or / .

According to this Stackoverflow question, you can put the following in your .vimrc

 vnoremap <Cr> "hy:%s/\(<Cr>h\)/\/\*\1\*\//gc<left><left><left> 

Now you can visually mark the line and press ctrl + r , which will give you the correct regular expression. Now you will be asked in turn if you want to comment on this, and you can do this by pressing y .

+3
source

You need to try NERD Commenter for VIM. IMHO this plugin is the best for this task.

+2
source

Source: https://habr.com/ru/post/903169/


All Articles