Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 766
drug_user841417 Avatar asked Dec 01 '25 09:12

drug_user841417


2 Answers

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
like image 132
pb2q Avatar answered Dec 03 '25 13:12

pb2q


You can use a macro:

qao<esc>jq

then use 3@a to apply the macro 3 times over the last lines.

where:

qa    "Start recording a macro named a
o     "Insert new line under current line
<esc> "Exit insert mode
j     " Move down next line
q     " end macro
like image 31
Rod Avatar answered Dec 03 '25 13:12

Rod