OpenWindows Advanced User's Guide

6.5.6 Copying and Moving Text -- Yank, Delete, and Put

Many word-processors allow you to "copy and paste" and "cut and paste" lines of text. The vi editor also includes these features. The vi command-mode equivalent of "copy and paste" is yank and put; the equivalent of "cut and paste" is delete and put.

The methods for copying or moving small blocks of text in vi involves using a combination of the yank, delete, and put commands. Copying Lines

To copy a line requires two commands: yy or Y ("yank") and either p ("put below") or P ("put above"). Note that Y does the same thing as yy.

To yank one line, position the cursor anywhere on the line and type yy. Now move the cursor to the line above where you want the yanked line to be put (copied), and type p. A copy of the yanked line will appear in a new line below the cursor.

To place the yanked line in a new line above the cursor, type P.

The yy command works well with a count: to yank 11 lines, for example, just type 11yy. Eleven lines, counting down from the cursor, will be yanked, and vi indicates this with a message at the bottom of the screen: 11 lines yanked.

You can also use the P or p commands immediately after any of the deletion commands discussed earlier. This puts the text you deleted above or below the cursor, respectively.

Caution - Caution -

Use only cursor-moving commands between yanking or deleting and putting. If you delete or yank any other text before putting the new text in place, the lines you yanked or deleted will be lost. Moving Lines

Moving lines also requires two commands: dd ("delete") and either p or P.

To move one line, position the cursor anywhere on the line and type dd. For example, to delete 5 lines, type 5dd.

Next, move the cursor to the line above where you want the deleted line reinserted and type p. This inserts the text on a new line below the cursor.

Alternatively, you can put the deleted line above the cursor by typing P. Using Named Buffers

To repeatedly insert a group of lines in various places within a document, you can yank (or delete) the lines into a named buffer. You specify named buffers by preceding a command with double quotes (") and a name for the buffer. For example, to yank four lines into the named buffer a, type "a4yy". You can use several different buffers. For example, you might also delete text from one location and add it to several others. To delete 12 lines into the named buffer b, type "b12dd".

To insert the text, precede the p or P command with n, where n is the named buffer. For example, to insert the lines saved in buffer b, type "bP".

You can overwrite named buffers with new lines. The buffers are saved until you exit vi.

When you use named buffers, you can safely delete and yank other text without affecting the lines you have already saved in the named buffers -- unless, of course, you purposely overwrite the named buffer.