vimtricks.wiki Concise Vim tricks, one at a time.

How do I collapse each paragraph of text into a single long line, removing the hard line breaks within it?

Answer

:g/./,/^$/join

Explanation

Hard-wrapped text (where each sentence is on its own line) is common in commit messages, email threads, and older documentation. :g/./,/^$/join collapses every paragraph into a single long line while preserving the blank lines between paragraphs. It's the inverse of gq — instead of wrapping text to fit a width, it unwraps it completely.

How it works

This command chains three powerful Ex features:

  • :g/./ — the :global command matches every non-empty line (. matches any character)
  • ,/^$/ — extends the range from the matched line to the next blank line
  • join — joins all lines in that range into one, separated by spaces

Because :global processes each paragraph's first line, then collapses it into one, subsequent lines of the same paragraph become no-ops for later passes.

Example

Before:

This is the first
sentence of a paragraph
that is hard-wrapped.

This is a second
paragraph with
three lines.

After :g/./,/^$/join:

This is the first sentence of a paragraph that is hard-wrapped.

This is a second paragraph with three lines.

Tips

  • Apply to a range to limit scope: :'<,'>g/./,/^$/join on a visual selection
  • Use gqip or gqap to do the reverse — re-wrap a paragraph to fit textwidth
  • To also strip leading/trailing whitespace after joining: :%s/^\s\+// followed by :%s/\s\+$//
  • The j flag variant :g/./,/^$/j! joins without adding extra spaces (useful for CJK text or prose where no space separator is wanted)

Next

How do I prepend a value to the front of a comma-separated Vim option like path or runtimepath?