Ionică Bizău
Ionică Bizău

Reputation: 113335

Add new lines using vertical select VIM

Suppose we have the following file content opened in VIM:

function a1 {}
function a2 {}
function a3 {}
function a4 {}
function a5 {}
function a6 {}
function a7 {}

I want to expand all functions in this style:

function an {

}

For that, I tried to use a vertical select (using Ctrl + V):

function a1 {█
function a2 {█
function a3 {█
function a4 {█
function a5 {█
function a6 {█
function a7 {█

Then I pressed I. Then Enter (in insert mode):

function a1 {
}
function a2 {}
function a3 {}
function a4 {}
function a5 {}
function a6 {}
function a7 {}

Then I pressed Esc. I expected to expand all blocks. Nothing happened. Why?

I know that a simple replace or a macro would save me. I know that there are alternatives, but I want to know why new line was not added when using vertical select.

Upvotes: 4

Views: 261

Answers (4)

Robert Lujo
Robert Lujo

Reputation: 16361

Like Max said, enter can not be inserted in blockwise-visual vim mode, documentation says:

Visual-block change (v_b_c): All selected text in the block will be replaced by the same text string. When using "c" the selected text is deleted and Insert mode started. You can then enter text (without a line break). When you hit , the same string is inserted in all previously selected lines.

The best workaround I found is:

  • bitwise select column where you want to insert newline, example column 1x3:

    ctrlVjjj

  • insert some mark that is unique in text block manipulated, example use mark "NEWL":

    shiftINEWLesc

  • do line select of the block, example:

    shiftVjjj

  • do replace of the mark just inserted with newline (ctrlventer -> ^M), example:

    :s/NEWL/ctrlventer/g

Upvotes: 1

Ingo Karkat
Ingo Karkat

Reputation: 172520

What I would do is apply a :substitution for the range of lines, e.g. addressing them through visual mode:

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

As Max has already answered, visual block inserting only works as long as you don't disrupt the block's layout by inserting additional lines (or moving around while editing).

Upvotes: 0

Max
Max

Reputation: 22325

Ctrl+V is not "vertical select", it is "blockwise-visual". As it's name implies, it is for selecting a "block" (rectangle) of text.

If you insert a line break inside the selected block, it disrupts everything that comes below it. The result is that there is no longer a meaningful way for Vim to apply changes to the rest of the block since it isn't clear what "the rest" is anymore.

Upvotes: 6

acushner
acushner

Reputation: 9946

try using sed:

:%!sed 's/}/\n\n}/g

read to the bottom of your answer and realized you weren't looking for a workaround... i'm not sure why it doesn't work.

Upvotes: -1

Related Questions