Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: Select rectangular block past end of line

Tags:

vim

How do I select a rectangular block of text which extends beyond the end of the line in Vim?

Suppose that I have

aa
bbb
cc
dddd
ee

I would like to select a rectangular block that extends four characters on all lines. If _ is considered white-space, then I want:

aa__
bbb_
cc__
dddd
ee__

The rectangular visual block, C-v, only extends as far as the end of the last line selected:

rectangular select which extends beyond the end of the line

In Emacs, I can do what I want using C-x <SPC> (rectangle-mark-mode). ;)

like image 544
Lorem Ipsum Avatar asked Dec 20 '18 19:12

Lorem Ipsum


People also ask

How do I select a visual block in vim?

Press v to begin character-based visual selection, or V to select whole lines, or Ctrl-v or Ctrl-q to select a block. Move the cursor to the end of the text to be cut/copied. While selecting text, you can perform searches and other advanced movement. Press d (delete) to cut, or y (yank) to copy.

How do I select vertically in Vim?

Use ctrl+v to select a column of text consisting of the first character of the place you want your new column to go in front of. Use I to go into insert mode, and type one space. Press Esc, and you'll see you have inserted a column of single spaces. Now use ctrl+v again to highlight the column of spaces.

How do I select a region in Vim?

If you want to select the entire line in a file, press V. Now when you press k or j to go up and down, vim will select the entire line above and below your cursor. Finally, you can select text in columns by pressing ctrl+v and moving up or down the block.


1 Answers

blockwise visual mode with ragged border

To extend the blockwise visual selection to the end of all covered lines, you can press $ to switch Vim into a "ragged border" selection mode. This "trick" is mentioned at :help v_b_A:

With a blockwise selection, A{string} will append {string} to the end of block on every line of the block. There is some differing behavior where the block RHS is not straight, due to different line lengths:

  1. Block was created with $ In this case the string is appended to the end of each line.
  2. Block was created with {move-around} In this case the string is appended to the end of the block on each line, and whitespace is inserted to pad to the end-of-block column.

virtual edit

Another way to solve this is via the 'virtualedit' option:

:set virtualedit=all

This makes the space following the end of the line accessible to cursor movements, so you can extend the selection as much as you need. Yanking that text will have whitespace padding inserted to make a rectangular block, so the behavior is different to the above alternative.

like image 93
Ingo Karkat Avatar answered Sep 21 '22 17:09

Ingo Karkat