Wikia

Vim Tips Wiki

Inserting text in multiple lines

Talk0
1,612pages on
this wiki
Revision as of 21:20, December 19, 2012 by 17.84.25.233 (Talk)

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

Insert

For example, suppose you have some Vim script:

let a = 2
let b = 3
let c = 4

You may want to make these variables script-wise (by inserting "s:" before each variable name, so "a" becomes "s:a" etc). To do this, move to the a in the first line, then press Ctrl-V (or Ctrl-Q if you use Ctrl-V for paste), then jj to select a visual block over three lines.

Now type I to start a special form of insert mode, then type the wanted text (s:). When you press Esc to exit from insert mode, the text will be inserted in the same position on each of the lines affected by the visual block selection.

Instead of inserting text that you type, you may want to insert the contents of a register. To do this, select the visual block and press I as before. Now press Ctrl-R then the character identifying the register. For example, press Ctrl-R then " to insert the unnamed register (the last yanked or deleted text), or press Ctrl-R then + to insert the clipboard.

While in insert mode, typing Ctrl-R then " inserts the unnamed register as if you had typed the characters. For example, if one of the characters is Ctrl-H (the code for Backspace), the character will delete the preceding character. If you want to actually insert all characters, including special codes such as Ctrl-H, you need to press Ctrl-R twice (Ctrl-R Ctrl-R ").

DLXJV019FDD3 DLXJV012FDD3 DLXJT014FDHY DLXJT00HFDHY DLXJT01WFDHY DLXJT01VFDHY

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

Around Wikia's network

Random Wiki