Vim Tips Wiki
Register
Advertisement
Tip 194 Printable Monobook Previous Next

created 2002 · complexity basic · author Gergely Kontra · version 6.0


In visual block mode, you can press I to insert text at the same position in multiple lines, and you can press A to append text to each line in a block. As well as inserting or appending text that you type, you can insert or append text from registers, for example, the clipboard. The substitute command can also be used to insert or append text.

In Vim, check that you have the blockwise-operators feature (I, A, and more) by entering the :version command. The output should include +visualextra. :help +visualextra

Append

In a visual block, you can insert text in each line before the selection with I, and you can append text in each line after the selection with A. If you use $ to convert the visual selection to select to the end of line, then A will append text to the end of each line in the visual block.

For example, suppose the clipboard contains "Hello world." and you have three lines:

First.
This is the second line.
The third.

To insert " Hello world." (space + clipboard) at the end of each of these lines:

  • On a character in the first line, press Ctrl-V (or Ctrl-Q if Ctrl-V is paste).
  • Press jj to extend the visual block over three lines.
  • Press $ to extend the visual block to the end of each line.
  • Press A then space then Ctrl-R then + then Esc.

The result is:

First. Hello world.
This is the second line. Hello world.
The third. Hello world.

Search and replace

The substitute command can be used to insert (or replace) text. Some examples:

:s/^/new text / Insert "new text " at the beginning of the line.
:s/$/ new text/ Append " new text" to the end of the line.
:s/green/bright &/g Replace each "green" with "bright green" in the line.

By default, each command operates on the current line. If you visually select some text before entering the command, it will operate on each line in the visual selection. See Search and replace for details.
Or you can insert a range immediately after the colon, for instance :.-5,$s/ etc. to substitute from 5 lines above the cursor to the end of the file.

See also

References

Comments

Advertisement