Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Line Break After pattern in VIM

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

How can I do this in Vim?

like image 473
Chalist Avatar asked Feb 21 '13 11:02

Chalist


People also ask

How do I add a line break in Vim?

in my . vimrc for years. Press Enter to insert a blank line below current, Shift + Enter to insert it above.

How do I add a line after a line in Vim?

Starting in normal mode, you can press O to insert a blank line before the current line, or o to insert one after. O and o ("open") also switch to insert mode so you can start typing.

Does Vim automatically add newline?

A sequence of zero or more non- <newline> characters plus a terminating <newline> character. And, therefore, they all need to end with a newline character. That's why Vim always adds a newline by default (because, according to POSIX, it should always be there).

Does Vim add newline at end of file?

Vim doesn't show latest newline in the buffer but actually vim always place EOL at the end of the file when you write it, because it standard for text files in Unix systems. You can find more information about this here. In short you don't have to worry about the absence a new lines at the end of the file in vim.


1 Answers

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? 
like image 55
Tom Cammann Avatar answered Sep 22 '22 02:09

Tom Cammann