Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i insert a blank line before every comment (eg "#") in VIM?

Tags:

vim

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
like image 490
excray Avatar asked Apr 20 '10 07:04

excray


2 Answers

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.
like image 84
Jacek Konieczny Avatar answered Oct 01 '22 10:10

Jacek Konieczny


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

like image 25
kdo Avatar answered Oct 01 '22 10:10

kdo