Search code examples
vimnewlineshortcutmultiline

Separate lines with blank lines in Vim?


I am dealing with a block of comments like:

//this is comment 1
//this is comment 2
//this is comment 3
//this is comment 4

I would like to make it look like:

//this is comment 1

//this is comment 2

//this is comment 3

//this is comment 4

Is there a Vim shortcut to make this transformation on selected lines while staying in command mode?


Solution

  • You can use the :substitute command. With the cursor anywhere on the first of the lines:

    :,+3s/$/\r
    

    This inserts an additional newline at the end of each line.

    You can also use the :global command. With the cursor anywhere on the first of the lines, run:

    :,+3g//norm o
    

    For each of the next four lines, this executes the o Normal-mode command, adding a new blank line.

    In both of the commands, the ,+3 prefix is a range for the command, see :help range. Briefly, the comma separates the addresses of the starting and ending lines of the range, where the current line is used if we omit the former of the two addresses. The +3 address refers to the line that is three lines below from the current line.

    Rather than specifying a range, e.g., ,+3, for either of these commands, you can use the V Normal-mode command to make a Visual block across all the lines that you want. Then typing : to begin the command will auto-fill the range specifying the visual block, and you can then enter either of the two commands starting with s or g:

    :'<,'>s/$/\r