In the buffer
Before:
import os
import sys
def main():
^
After typing :g/^$/,/./-j and pressing Enter:
import os
import sys
def main():
^
The two blank lines after import os and the three after import sys each became a single blank line. The cursor lands on the last blank line that was processed, line 4. Single blank lines are left alone, so paragraph breaks survive.
When you would reach for it
You pasted a block from a web page, a terminal, or a diff, and it arrived with blank lines stacked three and four deep. You want the gaps to stay where they are, because they separate real sections, but you want each gap to be one line tall. :g/^$/d is too blunt: it removes every blank line and glues the sections together. This command keeps the structure and drops only the excess.
Gotchas
- The mental model matters here.
:gvisits each blank line in turn, and the,/./-part builds a range from that line to the end of its run. When the run has been joined, the other blank lines in it no longer exist, so:gskips them. That is why a run of five collapses to one instead of being processed five times. - A run of blank lines at the very end of the file is not touched. There is no non-blank line after it, so
/./wraps around to the top and produces a backwards range. Withwrapscanon, interactive Vim asksBackwards range given, OK to swap (y/n)?; answern. To clear trailing blank lines, pressGthendip, which deletes the whole run. ^$only matches lines that are completely empty. A line holding a stray space or tab counts as text, both for the pattern and for/./. Use:g/^\s*$/,/\S/-jto treat whitespace-only lines as blank. The joined line keeps the whitespace from the first line of the run, so follow up with:%s/\s\+$//if that bothers you.- The whole thing is one undo step. If the result is not what you wanted,
uputs every blank line back.
Variants
import os
import sys
import os
import sys
:g/^$/d: delete every empty line in the file. Useful when you want no gaps at all, not smaller ones.
import os
import sys
import os
import sys
:g/^\s*$/,/\S/-j: the same squeeze, but lines containing only spaces or tabs count as blank. The surviving line keeps the two spaces from the first line of the run.
import os
import sys
import os
import sys
:%s/\n\{3,}/\r\r/: the substitute version. It matches three or more newlines in a row and replaces them with two, which is one blank line. It leaves a trailing run at the end of the file alone too.