cola
cola

Reputation: 12466

How can I comment a single line or a block of lines in 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.

Upvotes: 6

Views: 5977

Answers (3)

telenachos
telenachos

Reputation: 896

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.

Upvotes: 11

frosch03
frosch03

Reputation: 729

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.

Upvotes: 3

Alexander Stavonin
Alexander Stavonin

Reputation: 670

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

Upvotes: 3

Related Questions