Adding Line Break After pattern in VIM

Chalist picture Chalist · Feb 21, 2013 · Viewed 15.9k times · Source

I have a css file and I want to add an empty line after every }.

How can I do this in Vim?

Answer

Tom Cammann picture Tom Cammann · Feb 21, 2013

A substitution would work nicely.

:%s/}/\0\r/g

Replace } with the whole match \0 and a new line character \r.
or

:%s/}/&\r/g

Where & also is an alternative for the whole match, looks a bit funny though in my opinion. Vim golfers like it because it saves them a keystroke :)

\0 or & in the replacement part of the substitution acts as a special character. During the substitution the whole string that was matched replaces the \0 or the & character in the substitution.

We can demonstrate this with a more complex search and replace -

Which witch is which?

Apply a substitution -

:s/[wW][ih][ti]ch/The \0/g

Gives -

The Which The witch is The which?