## 11.8. Improved Editing Facilities

This section describes the features of vim that make simple text editing easier and more powerful.

### 11.8.1. Command-Line History and Completion

vim keeps a history of your ex commands, search strings, and expressions in its extended command language. These are three separate histories. The size of each is controlled by the `history` option; the default is 20. You may wish to increase it in your .vimrc file, although vim does take steps to maintain only unique commands.

To access the history, use the cursor key on the colon command line. This will move backwards through the saved commands (most recent first). The key will move forwards. You can move around on the command line using the and keys. By default, text that you type is inserted into the command line. You can use the INS (Insert) key on your keyboard to toggle this mode, in which case what you type will replace what's on the command line. The BACKSPACE key will erase characters.

You can use the SHIFT or CTRL key in combination with the and keys to move the cursor left or right one word at time. This may or may not work on all keyboards, though. You can use `^B` or HOME to move the cursor to the beginning of the command line, and `^E` or END to move to the end of the command line. The control key versions should always work.

The behavior of the ESC character can vary. If vim is in vi compatibility mode, ESC acts likes RETURN and executes the command. When vi-compatibility is turned off, ESC will exit the command line without executing anything.

vim also provides completion facilities on the ex command line. The `wildchar` option contains the character that you type when you want vim to do a completion. The default value is the tab character. You can use completion for all of the following:

Command names
  Available at the start of the command line.
Tag values
  After you've typed `:tag`.
Filenames
  When typing a command that takes a filename argument. When multiple files match a pattern during filename completion, the value of the `suffixes` option sets a priority among them, in order to pick the one vim will actually use. (See `:help suffixes` for the details.)
Option values
  When entering a `:set` command. This has two features: when typing the name of the option itself, hitting TAB will complete the option name. You can then type the `=` sign and hit TAB again, and vim will fill in the current value of the variable.

Besides just the TAB key to do an expansion, a number of other control keys provide additional functionality. Table 11.3 describes the commands and what they do.

#### Table 11.3. vim Command-Line Completion Commands

Command | Function
--- | ---
`^D` | Lists the names that match the pattern. For filenames, directories will be highlighted.
Value of `wildchar` | (Default: tab) Performs a match, inserting the generated text. For multiple matches, the first match is inserted. Hitting TAB successively cycles among all the matches.
`^N` | Go to next of multiple `wildchar` matches, if any; otherwise, recall more recent history line.
`^P` | Go to previous of multiple `wildchar` matches, if any; otherwise, recall older history line.
`^A` | Insert all names that match the pattern.
`^L` | If there is exactly one match, insert it; otherwise, expand to the longest common prefix of the multiple matches.

The completion facilities are extensive; see `:help cmdline` for the full details. Besides command-line completion, vim also provides insert mode completion.

When typing text, especially in programs, the same words appear quite often. vim has commands that search backwards or forwards for a match with a half-finished word. For example, if you were typing this text and had entered ex, giving the `^P` command would have completed it to example. This is a nice way to reduce the number of typed characters and to avoid spelling mistakes.

Completion works not only with words in the text where you are typing, you can also fetch words from much further away. Table 11.4 shows an overview of the relevant commands.

#### Table 11.4. vim Insert Mode Completion Commands

Command | Function
--- | ---
`^N` | Complete a word from the current buffer, searching forward (mnemonic: next).
`^P` | Complete a word from the current buffer, searching backward (mnemonic: previous).
`^X ^K` | Complete words from a dictionary.
`^X ^I` | Complete words from included files.
`^X ^D` | Complete a macro (defined word) from included files.
`^X ^]` | Complete words from a tags file.
`^X ^F` | Complete a filename.
`^X ^L` | Complete a whole line from the current buffer.

See `:help ins-completion` for more details.

### 11.8.2. Tag Stacks

Tag stacking is described in Section 8.5.3. vim provides the richest set of facilities for working with tags. Besides just the ability to stack tags, if there are multiple matching tags, you can choose among them. You can also do a tag selection and window splitting operation in one command. See Table 11.5 for a list of vim tag commands.

#### Table 11.5. vim Tag Commands

Command | Function
--- | ---
`ta`[`g`][`!`] [`tagstring`] | Edit the file containing tagstring as defined in the tags file. The `!` forces vim to switch to the new file if the current buffer has been modified but not saved. The file may or may not be written out depending upon the setting of the `autowrite` option.
[`count`]`ta`[`g`][`!`] | Jump to the countth newer entry in the tag stack.
[`count`]`po`[`p`][`!`] | Pops a cursor position off the stack, restoring the cursor to its previous position. If supplied, go to the countth older entry.
`tags` | Display the contents of the tag stack.
`ts`[`elect`][`!`] [`tagstring`] | List the tags that match tagstring, using the information in the tags file(s). If no tagstring is given, the last tag name from the tag stack is used.
`sts`[`elect`][`!`] [`tagstring`] | Like `:tselect`, but splits the window for the selected tag.
[`count`]`tn`[`ext`][`!`] | Jump to the countth next matching tag (default 1).
[`count`]`tp`[`revious`][`!`] | Jump to the countth previous matching tag (default 1).
[`count`]`tN`[`ext`][`!`]
[`count`]`tr`[`ewind`][`!`] | Jump to the first matching tag. With count, jump to the countth matching tag.
`tl`[`ast`][`!`] | Jump to the last matching tag.

Normally, vim shows you which matching tag, out of how many, has been jumped to:

>     tag 1 of >3

It uses a greater-than sign (`>`) to indicate that it has not yet tried all the matches. You can use `:tnext` or `:tlast` to try more matches. If this message is not displayed because of some other message, use `:0tn` to see it.

The output of the `:tags` command is shown below. The current location is marked with a greater than sign (`>`):

>     # TO tag      FROM line in file
>        1  1 main	         1  harddisk2:text/vim/test
>      > 2  2 FuncA	        58  -current-
>        3  1 FuncC	       357  harddisk2:text/vim/src/amiga.c

The `:tselect` command lets you pick from more than one matching tag. The "priority" (`pri` field) indicates the quality of the match (global versus static, exact case versus case-independent, etc.); this is described more fully in the vim documentation.

>     nr pri kind tag	        file ~
>        1 F   f    mch_delay          os_amiga.c
>     		mch_delay(msec, ignoreinput)
>      > 2 F   f    mch_delay          os_msdos.c
>     		mch_delay(msec, ignoreinput)
>        3 F   f    mch_delay          os_unix.c
>     		mch_delay(msec, ignoreinput)
>     Enter nr of choice (<CR> to abort):

The `:tag` and `:tselect` commands can be given an argument that starts with `/`. In that case, this argument is treated as a regular expression. vim will find all the tags that match the given regular expression.[57] For example, `:tag /normal` will find the macro `NORMAL`, the function `normal_cmd`, and so on. Use `:tselect /normal` and enter the number of the tag you want.

> [57]Prior to Version 5.1, vim keyed its treatment of the `:tag` or `:tselect` argument as a regular expression based on the presence or absence of special characters. The use of `/` disambiguates the process.

The vi command mode commands are described in Table 11.6. Besides using the keyboard, as in the other editors, you can also use the mouse, if mouse support is enabled in your version of vim.

#### Table 11.6. vim Command Mode Tag Commands

Command | Function
--- | ---
`^]` | Look up the location of the identifier under the cursor in the tags file, and move to that location. The current location is automatically pushed onto the tag stack.
`g <LeftMouse>`
`CTRL-<LeftMouse>`
`^T` | Return to the previous location in the tag stack, i.e., pop off one element. A preceding count specifies how many elements to pop off the stack.

The vim options that affect tag searching are described in Table 11.7.

#### Table 11.7. vim Options for Tag Management

Option | Function
--- | ---
`taglength`, `tl` | Controls the number of significant characters in a tag that is to be looked up. The default value of zero indicates that all characters are significant.
`tags` | The value is a list of filenames in which to look for tags. As a special case, if a filename starts with `./`, the dot is replaced with the directory part of the current file's pathname, making it possible to use tags files in a different directory. The default value is `"./tags,tags"`.
`tagrelative` | When set to true (the default), and using a tags file in another directory, filenames in that tags file are considered to be relative to the directory where the tags file is.

The vim 5.1 distribution comes with Version 2.0.3 of the Exuberant ctags program. As of this writing, this is the current version of Exuberant ctags.

vim can use emacs style etags files, but this is only for backwards compatibility; the format is not documented in the vim documentation, nor is the use of etags files encouraged.

Finally, like elvis, vim also looks up the entire word containing the cursor, not just the part of the word from the cursor location forward.

### 11.8.3. Infinite Undo

In vim, being able to undo and redo multiple levels of changes is controlled by the `undolevels` option. This option is a number indicating how many levels of "undo" that vim should allow. A negative value disallows any undoing (which is not terribly useful).

When `undolevels` is set to a non-zero value, you enter text as normal. Then each successive `u` command undoes one change. To redo (undo the undo), you use the (rather mnemonic) CTRL-R command.

vim is different from elvis; it starts out with a default value for `undolevels` of 1,000, which should be close enough to infinite for any given editing session. Also, the option is global, and not per buffer.

Once `undolevels` has been set, a count to either the `u` or `^R` commands undoes or redoes the given number of changes.

vim actually implements undoing and redoing in two different ways. When the `cpoptions` (compatibility options) option contains the letter `u`, the `u` command works like in vi, and `^R` repeats the previous action (like `.` in nvi). When `u` is absent from `cpoptions`, `u` undoes one step and `^R` redoes one step. This is easier to use, but not vi-compatible.

### 11.8.4. Arbitrary Length Lines and Binary Data

vim does not have a limit on the number or lengths of lines. When editing a binary file, you should either use the `-b` command-line option or `:set binary`. These set several other vim options that make it easier to edit binary files. To enter 8-bit text, use `^V` followed by three decimal digits.

### 11.8.5. Incremental Searching

As mentioned in Section 8.6.4, you enable incremental searching in vim using `:set incsearch`.

The cursor moves through the file as you type. vim highlights the text that matches what you've typed so far.

You may wish to use this with the `hlsearch` option, which highlights all matches of the most recent search pattern. This option is particularly useful when looking for all uses of a particular variable or function in program source code.

### 11.8.6. Left-Right Scrolling

As mentioned in Section 8.6.5, you enable left-right scrolling in vim using `:set nowrap`. The value of `sidescroll` controls the number of characters by which vim shifts the screen when scrolling left to right. With `sidescroll` set to zero, each scroll puts the cursor in the middle of the screen. Otherwise, the screen scrolls by the desired number of characters.

vim also has several commands that scroll the window sideways, shown in Table 11.8.

#### Table 11.8. vim Sideways Scrolling Commands

Command | Function
--- | ---
`zl` | Scroll the window left.
`zh` | Scroll the window right.
`zs` | Scroll the window to put the cursor at the left (start) of the screen.
`ze` | Scroll the window to put the cursor at the right (end) of the screen.

### 11.8.7. Visual Mode

vim allows you to select regions one character at a time, one line at a time, or rectangularly, using the commands shown in Table 11.9.

#### Table 11.9. vim Block Mode Command Characters

Command | Function
--- | ---
`v` | Start region selection, character at a time mode.
`V` | Start region selection, line at a time mode.
`^V` | Start region selection, rectangular mode.

vim highlights (using reverse video) the text as you are selecting. To make your selection, simply use the normal motion keys. If `showmode` is set, vim will indicate the mode as one of visual, visual line, or visual block. If vim is running inside an xterm, you can also use the mouse to select text (see `:help mouse-using` for the details). This also works in the GUI versions. The screen below shows a rectangular region:

>     The 6th edition of <citetitle>Learning the vi Editor</citetitle>
>     brings the book into the late 1990&rsquo;s.
>     In particular, besides the &ldquo;original&rdquo; version of
>     <command>vi</command> that comes as a standard part of every UNIX
>     system, there are now a number of freely available &ldquo;clones&rdquo;
>     or work-alike editors.

After applying the `~` operator, the screen looks like this:

>     The 6th edition of <citetitle>Learning the vi Editor</citetitle>
>     brings the BOOK INTO THE LATE 1990&rsquo;s.
>     In particulAR, BESIDES THE &LDQUo;original&rdquo; version of
>     <command>vi</COMMAND> THAT COMES as a standard part of every UNIX system,
>     there are nOW A NUMBER OF FREELY available &ldquo;clones&rdquo;
>     or work-alike editors.

vim permits many operations on the selected text. Some operations work only on whole lines, even if you've selected a region that does not contain whole lines.

vim has special commands for increasing the "swept out" area, and it allows you to apply almost any vi mode command to the highlighted text, as well as some commands that are unique to visual mode.

When defining the area to be operated on, a number of commands make it easy to treat words, sentences, or blocks of C/C++ code as single objects. These are described in Table 11.10. These commands can be used by themselves to extend the region, or they can be used in conjunction with an operator. For example, `daB` deletes a brace-enclosed block of text, including the braces.

#### Table 11.10. vim Block Mode Object Selectors

Command | Selects
--- | ---
`aw` | A word (with whitespace)
`iw` | An inner word (without whitespace)
`aW` | A WORD (with whitespace)
`iW` | An inner WORD (without whitespace)
`as` | A sentence (with whitespace)
`is` | An inner sentence (without whitespace)
`ap` | A paragraph (with whitespace)
`ip` | An inner paragraph (without whitespace)
`ab` | A `(...)` block (includes parentheses)
`ib` | An inner `(...)` block (not including the parentheses)
`aB` | A `{...}` block (includes braces)
`iB` | An inner `{...}` block (not including the braces)

The terms "word" and "WORD" have the same meaning as for the `w` and `W` motion commands.

vim allows you to use many operators on highlighted text. The available operators are summarized in Table 11.11.

#### Table 11.11. vim Block Mode Operations

Command | Operation
--- | ---
`~` | Flip the case of the selected text.
`o`, `O` | Move to the other end of the highlighted text. `o` moves from the start of the highlighted area to end, and vice versa. `O` in block mode moves to the other end of the text on the current line. You can continue sweeping out the area from the new position.
`<`, `>`, `!` | Shift text left or right, filter text. These operate on the whole lines containing the marked region. In the future, for a block, only the block will be shifted.
`=` | Filters text through the program named by the `equalprg` option. (Typically a simple text formatter such as fmt.) This operates on the whole lines containing the marked region.
`gq` | Formats the lines containing the marked region to be no longer that what's set in `textwidth`. This operates on the whole lines containing the marked region.
`:` | Start an ex command for the highlighted lines. This operates on the whole lines containing the marked region.
`c`, `d`, `y` | Change, delete, or yank text. These work even on rectangular text, although the `c` command only enters text on the first line in the block.
`c`, `r`, `s` | Change the highlighted text.
`C`, `S`, `R` | If using CTRL-V, the rectangle is deleted and insert mode is entered in the first line. Otherwise, whole lines are replaced.
`x` | Delete the highlighted text.
`X`, `Y` | Delete or yank the whole lines containing the highlighted area.
`D` | Delete to the end of the line. When using CTRL-V, the highlighted block and the rest of the text to end of each line is deleted. If not using CTRL-V, the whole line is deleted.
`J` | Join the highlighted lines. This operates on the whole lines containing the marked region.
`U` | Make uppercase. This command is unique to visual mode.
`u` | Make lowercase. This command is unique to visual mode.
`^]` | Use the highlighted text as the tag to find in a tag search.

Copyright © 2003 O'Reilly & Associates. All rights reserved.