Join lines inside paragraphs in vim

carriage returnnewlinesvim

Suppose you've typed a long document in vim with automatic line breaking on, so all the lines have been broken at, say, 79 characters. You may have even applied formatting to the whole document to break all the lines at that length.

Paragraphs are demarcated in your document by blank lines.

Now you decide you don't want line breaks within paragraphs at all.

How can you remove all the line breaks within paragraphs without eliminating the paragraph boundaries altogether?

I have made this quick and idiotic hack, but am looking for the proper way.

:%s/^\s*$/@@@@@ - replace blank lines with @@@@@
ggVGgJ           - join all lines in the file
:%s/@@@@@/\r\r/g   - replace @@@@@ with line breaks

Best Answer

I think this does what you want: make sure there is an empty line at the end of the file, then join every paragraph (terminated by an empty line).

G:a

.
:g/^./ .,/^$/-1 join

Explanation: first go to the end of the file and append an extra empty line with :a (maybe there's a more elegant way to do that; interactively, you can replace the first three lines with o<ESC>). Then, for every non-blank line that hasn't been considered yet (:g/^./), apply the join command to the range starting at the selected line (.) and ending one line before the next empty line (/^$/-1).

Optionally, :g/^$/d if you don't want any blank line to remain (then you can take off the -1).

Related Question