CodeCrack
CodeCrack

Reputation: 5363

How to comment several lines out in vim with substitute and replace

Let's say I have bunch of lines

    echo "<br/>";
    echo "<pre>";
    error_log("whatever");
    echo "</pre>";
    echo "<br/>";

and I want to comment them out, I can run this command

s/^/#

but it puts the # sign right in beginning of the line and not in front of first word so it looks like the lines below

#    echo "<br/>";
#    echo "<pre>";
#    error_log("whatever");
#    echo "</pre>";
#    echo "<br/>";

How can I make it look like more like the code below

    #echo "<br/>";
    #echo "<pre>";
    #error_log("whatever");
    #echo "</pre>";
    #echo "<br/>";

What's the proper reg ex for that?

Upvotes: 0

Views: 251

Answers (7)

Ingo Karkat
Ingo Karkat

Reputation: 172550

For commenting in and out, I would rely on a plugin; many are configurable and offer several styles of commenting, for a multitude of programming languages, all with a short mapping. Two popular ones are NERD_Commenter and tComment.

Upvotes: 1

romainl
romainl

Reputation: 196546

Another one:

  1. Start a macro with qx.

  2. Insert an octothorpe right before the first printable character on the line, go back to normal mode and go down one line with I#<Esc>j

  3. Stop recording with q.

  4. Execute the macro x times with 5@x.

Upvotes: 1

romainl
romainl

Reputation: 196546

Another one:

  1. visually select all the lines with V<motion>

  2. use :normal to execute a normal mode command on each line, :'<,'>norm I#.

The range is added automatically so the full sequence would be V4j:norm I#.

Upvotes: 2

romainl
romainl

Reputation: 196546

There are many ways. Here is one:

:'<,'>s/^\s*/\0#

Upvotes: 2

RocketDonkey
RocketDonkey

Reputation: 37259

One thing I do is go to the beginning of the line (^), hit Ctrl+v, then key in the line number followed by gg, then do Shift-I, key in the # and press ESC. I'm sure there is a better way, but it seems to work for me :)

Upvotes: 1

alestanis
alestanis

Reputation: 21863

You could do something like this:

s/^\([\s\t]*\)/\1#/

This takes all space and tabs into variable \1 and restores them before the # sign

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208475

You should be able to use the following:

s/^[ \t]*/&#/

This regex matches any tabs or spaces at the beginning of the line, and then replaces with the entire match (&) followed by a #.

Upvotes: 1

Related Questions