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

How do I collapse multiple consecutive blank lines into a single blank line throughout a file?

Answer

:g/^$/,/./-j

Explanation

The command :g/^$/,/./-j reduces every run of consecutive blank lines to a single blank line, preserving paragraph structure while removing excessive whitespace. This is useful after pasting code or pulling in content from editors that insert extra blank lines.

How it works

This is a :global command with a clever range trick:

  • :g/^$/ — match each blank line
  • ,/./ — extend the range forward from that blank line to the next non-blank line
  • - — back off by one line (so we don't include the first non-blank line)
  • j — join the selected range of blank lines into one

Effectively, for each blank line found, the range ^$ to /./-1 selects that blank line plus all following blank lines, then j joins them all into a single blank line.

Example

Before:

first paragraph



second paragraph


third paragraph

After running :g/^$/,/./-j:

first paragraph

second paragraph

third paragraph

Tips

  • To delete all blank lines instead: :g/^$/d
  • To delete trailing whitespace on blank lines too (lines with only spaces): :g/^\s*$/,/\S/-j
  • This is safe to run on code files — it only compresses blank line runs, never touches non-blank content

Next

How do I run a normal mode command from the ex command line without triggering my custom key mappings?