vimtricks.wiki Concise Vim tricks, one at a time.

How do I select a rectangular block of text in Vim?

Answer

<C-v>

Explanation

The <C-v> (Ctrl+v) command enters visual block mode, which lets you select a rectangular column of text across multiple lines. This is one of Vim's most powerful features for editing columnar data and making the same change on multiple lines simultaneously.

How it works

  • <C-v> starts visual block mode from the current cursor position
  • Move the cursor with h, j, k, l or other motions to expand the rectangular selection
  • The selection is a true rectangle — it does not follow line lengths
  • Press <Esc> to cancel, or apply an operator to act on the selection

Example

Given the text:

foo: 1
bar: 2
baz: 3

Place the cursor on the f of foo. Press <C-v>, then 2j2l to select the first 3 characters of all 3 lines. Press d to delete the block, resulting in:

: 1
: 2
: 3

Common operations in visual block mode

  • I — insert text at the beginning of every line in the block (type your text, then press <Esc> and it appears on all lines)
  • A — append text at the end of every line in the block
  • c — change (replace) the selected block with new text on every line
  • d or x — delete the block
  • r{char} — replace every character in the block with {char}
  • > or < — indent or unindent the selected lines

Tips

  • Use $ in visual block mode to extend the selection to the end of every line, regardless of line length
  • If <C-v> does not work in your terminal (some terminals intercept it for paste), try remapping or using <C-q> instead
  • Use gv to reselect the last visual selection if you accidentally exit visual block mode
  • Use O or o while in visual block mode to move the cursor to the opposite corner of the selection
  • Combine with g<C-a> to create incrementing number sequences across the selected lines

Next

How do I edit multiple lines at once using multiple cursors in Vim?