tags:

views:

132

answers:

5

Hi In Gvim I need to insert a blank line or two before every comment in the file.

Eg

#comment 1
#comment 2
statement 1
statement 2
#comment 3

After running the comamnd it should be

#comment 1

#comment 2
statement 1
statement 2  

#comment 3

How do i do this?

Thanks

Update: Thanks for the answers

But if the comments are continuous, i do not want newline to be added in between them. Is there a way to do this?

eg

#comment 1
#comment 2

I dont to want it to be

#comment 1

#comment 2
A: 

Use this command: :%s/^\ze\s*#/\r/

too much php
+6  A: 

You can also use this command: :g/^#/norm O

Ok, here is an explanation:

This is a shortcut of :global/^#/normal O which means:

  • for each line starting with '#' (:global/^#/)
  • do 'O' command in 'normal mode' (normal O) – which means to do what a 'O' key does in the 'normal' (not insert and not :command) VIM mode. And 'O' inserts a new line.
Jacek Konieczny
I think this is the best answer so far since it's the most intuitive, but maybe you should explain how and why it works.
matias
explanation added
Jacek Konieczny
`:g[lobal]` trumps `:s[ubstitute]` +1 for you sir
jeffjose
+1  A: 

Not affecting the first line

The example output looks like there should be no newline before the first line in the file. You can add a lookbehind check to achieve that.

:%s/^\n\@<=\ze\s*#/\r/

\n\@<= Matches only if there's a newline before the current position, so the first line won't match. For more information see :h \@<=

That can also be done with a line check. The following regex matches only those lines that are not the first line.

:%s/^\%>1l\ze\s*#/\r/

\%>1 Matches below line 1. See :h \%>l


Here's something that should work with the updated question, that is, only add a newline before the current line, if there is no comment line before.

:g/^\%^\@<!\(^\s*#.*\n\)\@<!\s*#/norm O

^\%^\@<! Do not match this line if the beginning of the file is before it. :h \%^ and :h \@<!

\(^\s*#.*\n\)\@<! Only match this line if the first non-blank character on the previous line is not #.

This regex will change

#comment 1
#comment 2
statement 1
statement 2
#comment 3

to

#comment 1
#comment 2
statement 1
statement 2

#comment 3
Heikki Naski
+2  A: 

there's a solution, which works in the "unimproved vi" as well:

:2,$g/^[ TAB]*#/s/^/^M/

where TAB and ^M must be entered as the corresponding control character.

Hope this helps - and my thanks go to Heikki for pointing on the 1st line problem

Klaus-Dieter Ost
A: 

Yet another way (works for 1st line too)

:s/^[ TAB]*#-1s/^/\r/
dimba