Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

comments

css

vim

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

border: 1px solid black;

I want to comment this line like this:

/*border: 1px solid black;*/

Is there a shortcut to do this comment for all 5 occurrence?

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

I don't want to search and replace this only line, i want to set a key so that when i hover a line and press that key, that line will be commented or selecting a line or selecting a block of line, if i press that key, that line or block of line will be commented.

like image 517
shibly Avatar asked Dec 06 '11 07:12

shibly


3 Answers

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

To record a macro type: q<letter><commands>q. Where <letter> is any letter from a-z and indicates the register in which the macro will be saved. After that you simply type the commands you wish to be recorded and finally press q again to stop recording.

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

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

like image 64
telenachos Avatar answered Oct 03 '22 23:10

telenachos


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

like image 43
Alexander Stavonin Avatar answered Oct 03 '22 21:10

Alexander Stavonin


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 have to escape characters like * or /.

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

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

you now can visually mark a line and press ctrl+r which gives you the right regular expression. You're now asked line by line if you want to comment it and can do this by pressing y.

like image 39
frosch03 Avatar answered Oct 03 '22 22:10

frosch03