32

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

How can I do this in Vim?

Tom
  • 15,798
  • 4
  • 37
  • 48
Chalist
  • 3,160
  • 5
  • 39
  • 68
  • 1
    Related to https://unix.stackexchange.com/questions/247329/vim-how-to-replace-one-new-line-n-with-two-ns – jdhao Mar 28 '19 at 11:35

3 Answers3

49

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?
Tom
  • 15,798
  • 4
  • 37
  • 48
  • 4
    For such a beginner question, an explanation would surely help: `\0` (shorter would be `&`) re-inserts the match, `\r` is the escape sequence for a newline (in a replacement, usually it's `\n`). – Ingo Karkat Feb 21 '13 at 11:24
8
:%s/pre/cur\r/g

%: operate on the entire buffer.

pre(previous pattern): which pattern will be to changed.

cur(current pattern): by which the previous pattern will be changed.

\r: new line.

g: repeat for every match on a line (default is to just replace the first).

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
alhelal
  • 916
  • 11
  • 27
7

The answer is :%s/}/}\r/ I guess.

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79