Chapter 4. Beyond the Basics

You have already been introduced to the basic editing commands, i, a, c, d, and y. This chapter expands on what you already know about editing. It covers:

  • Descriptions of additional editing facilities, with a review of the general command form

  • vi and Vim command-line options, including different ways to open a file for editing

  • Making use of registers that store yanks and deletions

  • Marking your place in a file

  • Other advanced edits

More Command Combinations

In Chapter 2, “Simple Editing”, you learned the edit commands c, d, and y, as well as how to combine them with movements and numbers (such as 2cw or 4dd). In Chapter 3, “Moving Around in a Hurry”, you added many more movement commands to your repertoire. Although the fact that you can combine edit commands with movement is not a new concept to you, Table 4-1 presents several additional editing options you have not seen before.

Table 4-1. More editing commands
Change Delete Copy From cursor to…

cH

dH

yH

Top of screen

cL

dL

yL

Bottom of screen

c+

d+

y+

Next line

c5|

d5|

y5|

Column 5 of current line

2c)

2d)

2y)

Second sentence following

c{

d{

y{

Previous paragraph

c/pattern

d/pattern

y/pattern

Pattern

cn

dn

yn

Next pattern

cG

dG

yG

End of file

c13G

d13G

y13G

Line number 13

Notice how all of the sequences in Table 4-1 follow one of two general patterns:

(command)(number)(text object)

or:

(number)(command)(text object)

number is the optional numeric argument. command in this case is one of c, d, or y. text object is a movement command.

The general form of a vi command is discussed in Chapter 2. You may wish to review Tables 2-2 and 2-3 as well.

Options When Starting vi and Vim

So far, you have invoked the editor from the shell with the command:

$ vi file

or with

$ vim file

There are other options to the vim command that can be helpful. You can open a file directly to a specific line number or pattern. You can also open a file in read-only mode. Another option recovers all changes to a file that you were editing when the system crashed.

The options described in the following section apply both to vi and to Vim.

Advancing to a Specific Place

When you begin editing an existing file, you can call the file in and, then move to the first occurrence of a pattern or to a specific line number. You can also specify your first movement by search or by line number right on the command line. You do this using -c command; for backward compatibility with earlier versions of vi, you may also use +command:

$ vim -c n file

Open file at line number n.

$ vim -c /pattern file

Open file at the first occurrence of pattern.

$ vim + file

Open file at the last line.

In the file practice, to open the file and advance directly to the line containing the word Screen, enter the following:

Keystrokes Results

$ vim -c /Screen practice

With a screen editor you can scroll
the page, move the cursor, delete
lines, and insert characters, while
seeing the results of your edits as
you make them. Screen editors are
very popular, since they allow you
to make changes as you read

Give the vim command with the option -c /pattern to go directly to the line containing Screen.

As you see in this example, your search pattern is not necessarily positioned at the top of the screen. Interestingly, the cursor is placed on the first character of the line and not on the first character of the matching text! If you include spaces in the pattern, you must enclose the whole pattern within single or double quotes:1

-c /"you make"

or escape the space with a backslash:

-c /you\ make

In addition, if you want to use the general pattern-matching syntax described in Chapter 6, “Global Replacement”, you may need to protect one or more special characters from interpretation by the shell with either single quotes or backslashes.

Using -c /pattern is helpful if you have to leave an editing session before you’re finished. You can mark your place by inserting a pattern such as ZZZ or HERE. Then, when you return to the file, all you have to remember is /ZZZ or /HERE.

After the editor opens your file and does a pattern search for the pattern you gave it with -c, you can continue to the next occurrence of that pattern simply by using n.

Note

Normally, when you’re editing in vi and Vim, the wrapscan option is enabled. If you’ve customized your environment so that wrapscan is always disabled (see the section “Repeating Searches”), you might not be able to use -c /pattern. If you try to open a file this way, the editor opens the file at the last line and displays the message, “Address search hit BOTTOM without matching pattern.” The message will likely vary among different versions of vi and Vim.

Read-Only Mode

There will be times when you want to look at a file but want to protect that file from inadvertent keystrokes and changes. (You might want to call in a lengthy file to practice vi movements, or you might want to scroll through a command file or program.) You can enter a file in read-only mode and use all the regular movement commands, but you won’t be able to change the file.

To look at a file in read-only mode, enter either:

$ vim -R file

or:

$ view file

(The view command, like Vim, can use any of the command-line options for advancing to a specific place in the file.2) If you do decide to make some edits to the file, you can override read-only mode by adding an exclamation point to the write command:

:w!

or:

:wq!

Note that if you edit a file for which you do not have write permission, you will also be in read-only mode. In that case, if you own the file, a :w! or :wq! will still work; vi temporarily changes the permissions of the file to allow you to write it. Otherwise, saving the file will fail.

If you have a problem writing out the file, see the problem checklist in the section “Problems Saving Files”.

Recovering a Buffer

Occasionally a system failure may happen while you are editing a file. Ordinarily, any edits made after your last write (save) are lost. However, there is an option, -r, which lets you recover the edited buffer as it was at the time of a system crash.

Recovery in vi

On a traditional Unix system with the original vi, when you first log on after the system is running again, you will receive a mail message stating that your buffer has been saved. In addition, if you type the command:

$ ex -r

or:

$ vi -r

you will get a list of any files that the system has saved.

Use the -r option with a filename to recover the edited buffer. For example, to recover the edited buffer of the file practice after a system crash, enter:

$ vi -r practice

It is wise to recover the file immediately, lest you inadvertently make edits to the file and then have to resolve a version skew between the preserved buffer and the newly edited file.

You can force the system to preserve your buffer even when there is not a crash by using the command :pre (short for :preserve). You may find it useful if you have made edits to a file and then discover that you can’t save your edits because you don’t have write permission. (You could also just write out a copy of the file under another name or into a directory where you do have write permission. See the section “Problems Saving Files”.)

Recovery in Vim

Recovery in Vim works somewhat differently. Vim usually keeps its working file (called a swap file) in the same directory as the file being edited. For practice, Vim’s working file would be named .practice.swp.

If that file exists when you next go to edit practice, Vim asks you if you want to recover. You should do so, and write the file back out. You should then quit immediately and manually remove .practice.swp; Vim does not do that for you. After doing so, you may go back into Vim and continue editing your file normally.

The directory option to the :set command lets you control where Vim places the swap file. For more information, see the entry for directory in Table B-2 in the section “Vim 8.2 Options”.

Making Use of Registers

You have seen that while you are editing, your last deletion (d or x) or yank (y) is saved in the unnamed register. You can access the contents of that register and put the saved text back in your file with the put command (p or P).

The last nine deletions are stored in numbered registers. You can access any of these numbered registers to restore any (or all) of the last nine deletions. (Small deletions, of only parts of lines, are not saved in numbered registers, however. These deletions can be recovered only by using the p or P command immediately after you’ve made the deletion.)

You may also place yanks (copied text) into registers identified by letters. You can fill up to 26 registers (named a–z) with yanked text and restore that text with a put command at any time in your editing session.

Recovering Deletions

Being able to delete large blocks of text in a single bound is all very well and good, but what if you mistakenly delete 53 lines that you need? You can recover any of your past nine deletions, for they are saved in numbered registers. The last delete is saved in register 1, the second-to-last in register 2, and so on.

To recover a deletion, type " (double quote), identify the deleted text by number, and then give the put command. To recover your second-to-last deletion (from register 2), type:

"2p

The deletion in register 2 is placed after the cursor.

If you’re not sure which register contains the deletion you want to restore, you don’t have to keep typing "np over and over again. You can use "1p to place the first delete text; if that’s not right, use u to undo it. You can then use the repeat command (.) to place the next one, u to undo it, and so on. When you do this, the editor automatically increments the register number. As a result, you can search through the numbered registers using:

"1pu.u.u                etc.

to put the contents of each succeeding register in the file one after the other. Each time you type u, the restored text is removed; when you type a dot (.), the contents of the next register are restored to your file. Keep typing u and . until you’ve recovered the text you’re looking for.

Yanking to Named Registers

You have seen that you must put (p or P) the contents of the unnamed register before you make any other edit, or else the register is overwritten. You can also use y and d with a set of 26 named registers (a–z) that are specifically available for copying and moving text. If you name a register to store the yanked text, you can retrieve the contents of the named register at any time during your editing session.

To yank into a named register, precede the yank command with a double quote (") and the character for the name of the register you want to load. For example:

"dyy            Yank the current line into register d
"a7yy           Yank the next seven lines into register a

After loading the named registers and moving to the new position, use p or P to put the text back:

"dP             Put the contents of register d before the cursor
"ap             Put the contents of register a after the cursor

There is no way to put part of a register into the text—it is all or nothing.

In the next chapter, you’ll learn how to edit multiple files. Once you know how to travel between files without leaving the editor, you can use named registers to selectively transfer text between files. When using Vim’s multiple-window feature, you can also use the unnamed deletion register to transfer data between files.

Note

The unnamed and named deletion registers are shared within the same Vim session, so you can easily copy/paste text between files being edited in multiple windows in one Vim session. But these buffers are not shared between multiple Vim sessions! (You might have gvim open on several files at once, for example.) However, gvim can access the system clipboard just like any other graphical application. So you can use GUI-level copy and paste to move text between files with no problems.

You can also delete text into named registers using much the same procedure:

"a5dd           Delete five lines into register a

If you specify a register name with a capital letter, your yanked or deleted text is appended to the current contents of the corresponding lowercase register. This allows you to be selective in what you move or copy. For example:

"zd)

Delete from the cursor to the end of the current sentence and save the text in register z.

2)

Move two sentences further on.

"Zy)

Add the next sentence to register z. You can continue adding more text to a named register for as long as you like, but be warned: if you forget once, and you yank or delete to the register without specifying its name in capitalized form, you’ll overwrite the register, losing whatever you had accumulated in it.

Marking Your Place

During an editing session, you can mark your place in the file with an invisible “bookmark,” perform edits elsewhere, and then return to your marked place. Why would you need to do this? Will Gallego explains:

One of my favorite uses of marking is deleting/yanking/modifying a large chunk of text. For example, say I want to delete a large number of lines. I might not want to count all those lines and then do numdd, but instead jump to the bottom, mark it with something like ma (mark, then a to use register a as the location), then jump to where I want to start deleting and hit d`a to delete the current line and all lines up to and including where a is. yy and other related commands may be used in a similar fashion.

Here’s how you mark locations in command mode:

m x

Mark the current position with x (x can be any letter). (The original vi allows only lowercase letters. Vim distinguishes between uppercase and lowercase letters.)

' x (apostrophe)

Move the cursor to the first character of the line marked by x.

` x (backquote)

Move the cursor to the character marked by x.

`` (backquotes)

Return to the exact position of the previous mark or context after a move.

'' (apostrophes)

Return to the beginning of the line of the previous mark or context.

Note

Place markers are set only during the current session; they are not stored in the file.

Other Advanced Edits

There are other advanced edits that you can execute with vi and Vim, but to use them you must first learn a bit more about the ex editor by reading the next chapter.

Review of Register and Marking Commands

Table 4-2 summarizes the command-line options common to all versions of vi. Tables 4-3 and 4-4 summarize the register and marking commands.

Table 4-2. Command-line options
Option Meaning

-c n file

Open file at line number n (POSIX standard version).

+n file

Open file at line number n (traditional vi version).

+ file

Open file at last line.

-c /pattern file

Open file at first occurrence of pattern (POSIX standard version)

+/pattern file

Open file at first occurrence of pattern (traditional vi version).

-c command file

Run command after opening file; usually a line number or search.

-r

Recover files after a crash.

-R

Operate in read-only mode (same as using view).

Table 4-3. Register names
Register names Register use

1–9

The last nine deletions, from most to least recent.

a–z

Named registers for you to use as needed. Uppercase letters append to the register.

Table 4-4. Register and marking commands
Command Meaning

"bcommand

Do command with register b.

mx

Mark current position with x.

'x

Move cursor to the first character of the line marked by x.

`x

Move cursor to the character marked by x.

``

Return to the exact position of the previous mark or context.

''

Return to the beginning of the line of the previous mark or context.

1 It is the shell that imposes the quoting requirement, not the editor.

2 Typically view is just a link to vi. Some systems arrange things such that view executes vim -R.

Get Learning the vi and Vim Editors, 8th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.