Chapter 8. The vi Editor

CONTENTS
  •  The vi Editor
  •  Regular Expression Words-of-Caution
  •  Expressions Are Strings and Wildcards
  •  Modes and Notations
  •  Starting a vi Session
  •  Cursor Control Commands
  •  Adding Text in vi
  •  Deleting Text in vi
  •  Changing Text in vi
  •  Search and Replace in vi
  •  Copying Text in vi
  •  Undo and Repeat in vi
  •  Save Text and Exit vi
  •  Options in vi
  •  Status in vi
  •  Section Positioning and Placing Marks in Text
  •  Joining Lines in vi
  •  Cursor Placement and Adjusting the Screen
  •  Shell Escape Commands
  •  Macros and Abbreviations
  •  Indenting Text
  •  Shell Filters
  •  Pattern Matching
  •  Manual Pages for vi Command Used in Chapter 8

The vi Editor

In this chapter, we'll cover the following topics:

  • Regular expressions

  • vi

graphics/06icon04.gif

Many UNIX users have a Graphical User Interface (GUI) through which they access their UNIX system. The Common Desktop Environment (CDE) is the most commonly used GUI on UNIX systems. It is based on the X Windows System and Motif, which together provide an advanced windowing environment. A chapter in this book is devoted to CDE. Most UNIX GUIs provide a graphical editor. Despite the fact that these graphical editors are a standard part of most GUIs, the visual editor, vi, still remains the most popular UNIX editor. With many fine graphics-based editors as a standard part of most UNIX GUIs and a plethora of editors available as part of personal computer windowing environments, why am I covering vi? The answer is two-fold. First, not everyone using a UNIX system has access to a graphics display and may therefore need to know and use vi. Because vi comes with most UNIX-based systems and is a powerful editor, many new UNIX users end up using and liking it. Second, vi has traditionally been thought of as the UNIX editor. Few UNIX users have not used vi. This fact does not mean that it is everyone's primary editor; however, virtually all UNIX users have had some experience with vi.

graphics/08icon01.gif

Also, a line editor called ed comes with many UNIX systems. It is now seldom used because vi is a screen editor. Also available is an enhanced version of ed called ex. vi is much more widely used than either of the line editors, so I'll cover only vi in this chapter.

I'll cover the basics of using vi in this chapter. You can experiment with what is covered here, and if you really like it, you can investigate some of the more advanced features of vi. A quick reference card summarizing all the vi commands covered in this chapter is included with this book.

Table 8-1 is a list of tables in this chapter that summarize some of the more commonly used vi commands by function:

Table 8-1. Meta-Characters and Programs to Which They Apply

Table Number

vi Function

Expr

Regular Expressions

Introduction

Modes and Notations in vi

1

Starting a vi Session

2

Cursor Control Commands in vi

3

AddingTextinvi

4

Deleting Text in vi

5

Changing Text in vi

6

Search and Replace in vi

7

Copying in vi

8

Undoinvi

9

Saving Text and Exiting vi

10

Options in vi

11

Status in vi

12

Positioning and Marking in vi

13

Joining Lines in vi

14

Cursor Placement and Adjusting Screen in vi

15

Shell Escape Commands in vi

16

Macros and Abbreviations in vi

17

Indenting Text in vi

18

Shell Filters in vi

19

Pattern Matching in vi

Regular Expression Words-of-Caution

Regular expressions describe patterns for which you are searching. The regular expression usually defines the pattern for which you are searching using wildcards. Since a regular expression defines a pattern you are searching for, the terms "regular expression" and "pattern matching" are often used interchangably.

Let's get down to a couple of words-of-caution immediately:

  • Regular expressions are different from file-matching patterns used by the shell. Regular expressions are used by both the shell and many programs, including those covered in this chapter. The file matching done by the shell and programs such as find are different from the regular expressions covered in this chapter.

  • Use single quotes around regular expressions. The meta-characters used in this chapter must be quoted in order to be passed to the shell as an argument. You will, therefore, see most regular expressions in this chapter quoted.

Expressions Are Strings and Wildcards

graphics/05icon13.gif

graphics/06icon04.gif

graphics/06icon01.gif

graphics/06icon02.gif

When using the programs in this book, such as grep and vi, you provide a regular expression that the program evaluates. The command will search for the pattern you supply. The pattern could be as simple as a string or it could include wildcards. The wildcards used by many programs are called meta-characters.

Table 8-2 shows a list of meta-characters and the program(s) to which they apply. Only the programs covered in this book (awk, grep, sed, and vi) are shown in Table 8-2. These meta-characters may be used with other programs, such as ed and egrep, as well, which are not covered in the book. Table 8-2 describes the meta-characters and their use.

Table 8-2. Meta-Characters and Programs to Which They Apply

Meta Character

awk

grep

sed

vi

Use

.

Yes

Yes

Yes

Yes

Match any single character.

*

Yes

Yes

Yes

Yes

Match any number of the single character that precedes *.

[...]

Yes

Yes

Yes

Yes

Match any one of the characters in the set [...]

$

Yes

Yes

Yes

Yes

Matches the end of the line.

^

Yes

Yes

Yes

Yes

Matches the beginning of the line.

\

Yes

Yes

Yes

Yes

Escape the special character that follows \.

\{n,m\}

Yes

Yes

No

No

Match a range of occurrences of a single character between n and m.

+

Yes

No

No

No

Match one or more occurrences of the preceding regular expression.

?

Yes

No

No

No

Match zero or one occurrence of the preceding regular expression.

|

Yes

No

No

No

The preceding or following regular expression can be matched.

()

Yes

No

No

No

Groups regular expressions in a typical parenthesis fashion.

\{ \}

No

No

No

Yes

Match a word's beginning or end.

You may want to refer to this table when regular expressions are used for one of the commands in the table.

Modes and Notations

graphics/06icon04.gif

We're first going to cover some of the fundamentals of the operation of vi called modes, and then go over some of the notations used in the tables in this chapter.

A feature of vi that often confuses new users is that it has modes. When you are in command mode, everything you type is interpreted as a command. In command mode, you can specify such actions as the location to which you want the cursor to move. When you are in input mode, everything you type is information to be added to the file. Command mode is the default when you start vi. You can move into command mode from input mode atany time by pressing the escape key. You move into insert mode from command mode by typing one of the input mode commands covered shortly.

vi commands don't really have a standard form. For this reason, I cover common notations. Table 8-3 summarizes modes and commands in vi:

Table 8-3. Modes and Notations in vi

Mode or Notation

Description

Command Mode

You are issuing commands such as moving the cursor or deleting text, rather than inserting or changing text when in command mode. You can switch to insert mode by issuing an insert mode command such as i for insert or a for add text.

Insert Mode

You are in insert mode when changing or inserting more than one character of text. You canswitch to commandmodeby pressing the escape key.

: (colon commands)

Commands that start with a: are completed by pressing the return key.

control (^) commands

When a command uses the control (^) key, you pressand hold down thecontrol key and then press the next key that is part of the command. For instance, ^g means press and hold control and then g to get the status on the file you are editing.

file for the name of a file

Many commands require you to specify the name of a file. For instance, in the command vi file, you would substitute the name of the file you wish to edit for file.

char for the name of a character

Many commands require you to specify a single character. For instance, in the command fchar, you would substitute the character you wish to search for in place of char.

cursor_command for a cursor movement command

Many commands require you to specify a cursor command to execute. For instance, in the command dcursor_ command, you would substitute for cursor_command the commandyou wish to execute.

string for a character string

Many commands require you to specify a character string. For instance, in the command /string, you would substitute for string the character string for which you wish to search.

Starting a vi Session

graphics/06icon04.gif

Let's jump right in and edit a file. For most of the examples in this chapter, I perform various vi commands and capture the results in an X Window. The best way to learn any topic is by example. I not only provide many examples, but I also capture each example in an X Window so that you can see the results of each command. From the command line, we type vi and the name of the file we wish to edit, in this case, wisdom:

graphics/06icon04.gif

$ vi wisdom 

We are then editing the file wisdom as shown in Figure 8-1. wisdom contains a passage from Tao Te Ching or "Book of the Way." We use this file throughout this chapter.

Figure 8-1. Editing the File wisdom

graphics/08fig01.gif

The bottom line in Figure 8-1 is the message line in vi. After invoking vi, the message line indicates the name of the file, the number of lines, and the number of characters in the file. Different messages appear on the message line, depending on the command you issue, as we see in upcoming examples. If a tilde appears on any lines in the file, as it does in the two lines above the message line in wisdom, it means that not enough lines exist to fill up the screen. The cursor is the dark box that appears at line 1 in Figure 8-1.

We can specify several file names, and after saving the first file we move on to the second file by entering:n, and continue going through the list of files in this way. Or we can specify a file and position the cursor on the last line in the file. The default is for the cursor to appear over the first character in the file, as shown in Figure 8-1.

Table 8-4 shows some of the ways we can start a vi session:

Table 8-4. Starting a vi Session

Command

Description

vi file

Edit file.

vi -r file

Edit last saved version of file after a crash.

vi -R file

Edit file in read-only mode.

vi + n file

Edit file and place cursor at line n.

vi + file

Edit file and place cursor on last line.

vi file1 file2 file3 ...

Edit file1 through file3, and after saving changes in file1, you can move to file2 by entering:n.

vi +/ string file

Edit file and place cursor at the beginning of the line containing string.

Figure 8-2 shows editing wisdom and placing the cursor at line 5 with the command vi +5 wisdom:

Figure 8-2. Editing the File wisdom and Placing Cursor at Line 5 with vi +5 wisdom

graphics/08fig02.gif

graphics/06icon04.gif

Figure 8-3 shows editing wisdom and placing the cursor at the last line of the file with the command vi + wisdom.

Figure 8-3. Editing the File wisdom and Placing Cursor at Last Line with vi + wisdom

graphics/08fig03.gif

graphics/06icon04.gif

Figure 8-4 shows editing wisdom and placing the cursor at the line containing task with vi +/task wisdom.

Figure 8-4. Editing the File wisdom and Placing Cursor at Line Containing task with vi +/task wisdom

graphics/08fig04.gif

Cursor Control Commands

graphics/06icon04.gif

A key skill to develop in vi is getting the cursor to the desired position. You do this in command mode. You have a variety of ways to move the cursor around the screen. Table 8-5 summarizes some of the more commonly used cursor movements:

Table 8-5. Cursor Control Commands in vi

Command

Cursor Movement

h or ^h

Move left one character.

j or ^j or ^n

Move down one line.

k or ^p

Move up one line.

l or space

Move right one character.

G

Go to the last line of the file.

nG

Go to line number n.

G$

Go to the last character in the file.

1G

Go to the first line in the file.

w

Go to the beginning of the next word.

W

Go to the beginning of next word, ignore punctuation.

b

Go to the beginning of the previous word.

B

Go to the start of previous word, ignore punctuation.

L

Go to the last line of the screen.

M

Go to the middle line of the screen.

H

Go to the first line of the screen.

e

Move to the end of the next word.

E

Move to the end of the next word, ignore punctuation.

(

Go to the beginning of the sentence.

)

Go to the end of the sentence.

{

Go to the beginning of the paragraph.

}

Go to the beginning of the next paragraph.

0 or

Go to the first column in the current line.

n

Go to column n in the current line.

^ (caret)

Go to the first non-blank character in the current line.

$

Go to the last character in the current line.

+

or return Go to the first character in the next line.

-

Go to the first non-blank character in the previous line.

graphics/06icon04.gif

I know that the fact that you have to remember these commands in order to get the cursor to the desired position may seem a little strange at first, but this is the way vi works. Let's use wisdom to show how some of these cursor movements work. Figures 8-5 and 8-6 show some cursor movements. Like all of the upcoming figures, Figures 8-5 and 8-6 show wisdom before a command is entered on the left and the result after the command is entered on the right. The command issued appears in the middle. Some of the commands in upcoming figures use the enter and escape keys.

Figure 8-5. Examples of Cursor Movement in vi (h, j, k, and l)

graphics/08fig05.gif

Figure 8-6. Examples of Cursor Movement in vi (G, w, b, and e)

graphics/08fig06.gif

Adding Text in vi

Now that we know how to move around the cursor, let's do something with it. You need to first learn about cursor movement, because the commands for adding text take place relative to the position of the cursor. Table 8-6 summarizes some commands for adding text:

Table 8-6. Adding Text In vi

Command

Insertion Action

a

Append new text after the cursor.

A

Append new text after the end of the current line.

i

Insert new text before the cursor.

I

Insert new text before the beginning of the current line.

o

Open a line below the current line and insert.

O

Opena line abovethe current line and insert.

:r file

Read file and insert after the current line.

:nr file

Read file and insert after line n.

escape

Get back to command mode.

^v char

Ignore special meaning of char when inserting. This is for inserting special characters.

Let's now look at some examples of adding text into wisdom in Figure 8-7:

Figure 8-7. Examples of Adding Text in vi

graphics/08fig07.gif

Deleting Text in vi

We also need to learn about cursor movement before learning how to delete text, because the commands for deleting text take place relative to the position of the cursor. Table 8-7 summarizes some commands for deleting text:

Table 8-7. Deleting Text in vi

Command

Deletion Action

x

Delete the character at the cursor. You can also put a number in front of x to specify the number of characters to delete.

nx

Delete n characters beginning with the current.

X

Delete the previous character. You can also put a number in front of X to specify the number of previous characters to delete.

nX

Delete previous n characters.

dw

Delete to the beginning of the next word.

ndw

Delete the next n words beginning with the current.

dG

Delete lines to the end of the file.

dd

Delete the entire line.

ndd

Delete n lines beginning with the current.

db

Delete the previous word.

ndb

Delete the previous n words beginning with the current.

:n,md

Deletes lines n through m.

D or d$

Delete from the cursor to the end of the line.

dcursor_command

Delete text to the cursor_command. dG would delete from the current line to the end of the file.

^h or backspace

While inserting, delete the previous character.

^w

While inserting, delete the previous word.

Let's now look at some examples of deleting text from wisdom in Figures 8-8 and 8-9:

Figure 8-8. Examples of Deleting Text in vi (x, X, dw, and dG)

graphics/08fig08.gif

Figure 8-9. Examples of Deleting Text in vi (dd and db)

graphics/08fig09.gif

Changing Text in vi

graphics/06icon04.gif

Okay, you've added text and deleted text, and now you want to change text. vi isn't so bad so far, is it? Table 8-8 summarizes some commands for changing text:

Table 8-8. Changing Text In vi

Command (Preceding these commands with a number repeats the commands any number of times.)

Replacement Action

rchar

Replace the current character with char.

Rtext escape

Replace the current characters with text until escape is entered.

stext escape

Substitute text for the current character.

S or cctext escape

Substitute text for the entire line.

cwtext escape

Change the current word to text.

Ctext escape

Change the rest of the current line to text.

cG escape

Change to the end of the file.

ccursor_cmd text escape

Change to text from the current position to cursor_cmd.

Let's now look at some examples of replacing text from wisdom in Figures 8-10 and 8-11:

Figure 8-10. Examples of Changing Text in vi (r, R, cw, and cG)

graphics/08fig10.gif

Figure 8-11. Example of Changing Text in vi with cc

graphics/08fig11.gif

Search and Replace in vi

graphics/06icon04.gif

You have a lot of search and replace functionality in vi. Table 8-9 summarizes some of the more common search-and-replace functionality in vi:

Table 8-9. Search And Replace in vi

Command

Search and Replace Action

/text

Search for text going forward into the file.

?text

Search for text going backward into the file.

n

Repeat the search in the same direction as the original search.

N

Repeat the search in the opposite direction as the original search.

ftext

Search for text going forward in the current line.

Ftext

Search for text going backward in the current line.

ttext

Search for text going forward in the current line and stop at the character before text.

Ttext

Search for text going backward in the current line to character after text.

:set ic

Ignore case when searching.

:set noic

Make searching case-sensitive.

:s/oldtext/newtext/

Substitute newtext for oldtext.

:m,ns/oldtext/newtext/

Substitute newtext for oldtext in lines m through n.

&

Repeat the last:s command.

:g/text1/s/text2/text3

Find line containing text1, replace text2 with text3.

:g/text/command

Run command on all lines that contain text.

:v/text/command

Run command on all lines that do not contain text.

Let's now look at some examples of searching and replacing text in wisdom in Figure 8-12:

Figure 8-12. Examples of Search and Replace in vi gb

graphics/08fig12.gif

You can perform advanced searches with:g and:v. You can find and display all the lines in a file containing while with the following command:

:g/while/p 

The /p in this command line is the print command used with the ex editor. You can find all the lines in the file that contain while and delete those lines with the following command:

:g/while/d 

You can also specify the specific line numbers for which you want the search to take place. The following command finds all the lines between 10 and 20 that contain while and prints the line number on which they appear:

:10,20g/while/nu 

:g runs a command on the lines that contain the text for which we are searching, and:v runs a command on the lines that do not contain the specified text. The following three commands act on the lines that do not contain while, in the same way that the previous three act on the lines that do contain while:

:v/while/p  :v/while/d  :10,20v/while/nu 

The first command prints lines that do not contain while. The second command deletes the lines on which while does not appear. The third command prints the line number between 10 and 20 on which while does not appear.

Copying Text in vi

graphics/06icon04.gif

You can copy text in vi. Some commands for copying are shown in Table 8-10:

Table 8-10. Copying In vi

Command

Copy Action

yy

Yank the current line.

nyy

Yank n lines.

p (lowercase)

Put the yanked text after the cursor.

p (uppercase)

Put the yanked text before the cursor.

"(a-z)nyy

Copy n lines into the buffer named in parentheses. Omit n for the current line.

"(a-z)ndd

Delete n lines into the buffer named in parentheses. Omit n for the current line.

"(a-z)p

Put lines named in the buffer in parentheses after current line.

"(a-z)P

Put lines named in the buffer in parentheses before the current line.

Let's now look at some examples of copying text in wisdom in Figure 8-13:

Figure 8-13. Copying in vi

graphics/08fig13.gif

Undo and Repeat in vi

graphics/06icon04.gif

You can easily undo and repeat changes in vi with the commands shown in Table 8-11:

Table 8-11. Unso In vi

Command

Undo Action

u

Undo the last change.

U

Undo all changes to the current line.

. (period)

Repeat the last change.

, (comma)

Repeat, in reverse direction, last f, F, t, or T search command.

; (semi-colon)

Repeat last f, F, t, or T search command.

"np

Retrieve the last nth delete (a limited number of deletes are in the buffer, usually nine).

n

Repeat last / or ? search command.

N

Repeat, in reverse direction, last / or ? search command.

Save Text and Exit vi

graphics/06icon04.gif

You have a number of different ways to save files and exit vi, some of which are summarized in Table 8-12:

Table 8-12. Saving Text and Exiting vi

Command

Save and/or Quit Action

:w

Save the file but don't exit vi.

:w file

Save changes in file but don't quit vi.

:wq or ZZ or:x

Save the file and quit vi.

:q!

Quit vi without saving the file.

:e!

Re-edit the file, discarding changes since the last write.

Options in vi

graphics/06icon04.gif

There are many options you can set and unset in vi. To set an option, you type:set option. To unset an option, you type:set nooption. Table 8-13 summarizes some of the more commonly used options:

Table 8-13. Options In vi

Option

Action

:set all

Print all options.

:set nooption

Turn off option.

:set nu

Prefix lines with line number.

:set showmode

Show whether input or replace mode.

:set noic

Ignore case when searching.

:set list

Show tabs (^l) and end of line ($).

:set ts=8

Set tab stops for text input.

:set window=n

Set number of lines in a text window to n.

Let's now prefix lines with line numbers and show input or replace mode in Figure 8-14:

Figure 8-14. Options in vi

graphics/08fig14.gif

graphics/06icon04.gif

Many additional options are available beyond those in Table 8-13. The following is a list of options produced on a UNIX system from the:set all command. You should issue this command when in vi to see the options available to you:

:set all  noautoindent  autoprint  noautowrite  nobeautify  directory=/var/tmp  nodoubleescape  noedcompatible  noerrorbells  noexrc  flash  hardtabs=8  noignorecase  keyboardedit  nokeyboardedit!  nolisp  nolist  magic  mesg  nomodelines  nonumber  nonovice  nooptimize  paragraphs=IPLPPPQPP LIpplpipnpbp  prompt  noreadonly  redraw  remap  report=5  scroll=11  sections=NHSHH HUuhsh+c  shell=/sbin/sh  shiftwidth=8  noshowmatch  noshowmode  noslowopen  tabstop=8  taglength=0  tags=tags /usr/lib/tags  tagstack  term=hp  noterse  timeout  timeoutlen=500  ttytype=hp  warn  window=23  wrapscan  wrapmargin=0  nowriteany  noshowmatch  noshowmode 

Many of the options are preceded by a "no," indicating that the option is not set. You may want to list your options with:set all and then experiment with the options of interest to you to see the effect they will have on your vi session.

graphics/06icon04.gif

Status in vi

You can obtain a lot of useful status information with some simple commands in vi. You can display the current line number, number of lines in the file, file name, and other status information with the commands shown in Table 8-14:

Table 8-14. Status in vi

Option

Action

:.=

Print the current line number.

:=

Print the number of lines in the file.

^g

Show the file name, current line number, total lines in the file, and percent of file location.

:l

Use the letter "l" to display various special characters such as tab and newline.

Section Positioning and Placing Marks in Text

graphics/06icon04.gif

You can define sections of text to which you can move as well as mark text with characters and move to those marks. Table 8-15 summarizes positioning and marking in vi:

Table 8-15. Positioning and Marking in vi

Option

Action

{

Insert { in first column to define section.

[[

Go back to beginning of section.

]]

Forward to beginning of next section.

m(a-z)

Mark current position with a letter such as mz for mark z.

'(a-z)

Move cursor to specified mark such as'z for move to z.

Joining Lines in vi

graphics/06icon04.gif

You can join one or more lines in vi using the commands shown in Table 8-16:

Table 8-16. Joining Lines In vi

Option

Action

J

Join the next line to the end of the current line.

nJ

Join the next n lines.

Cursor Placement and Adjusting the Screen

You can place the cursor anywhere in your file and adjust the screen in a variety of ways using the commands shown in Table 8-17:

Table 8-17. Cursor Placement and Adjusting the Screen In vi

Option

Action

H

Move cursor to top line of the screen.

nH

Move cursor to n line from the top of the screen.

M

Move cursor to the middle of the screen.

L

Move cursor to the bottom line of the screen.

nL

Move cursor to line n from the bottom of the screen.

^e (control-e)

Move screen up one line.

^y

Move screen down one line.

^u

Move screen up one-half page.

^d

Move screen down one-half page.

^b

Move screen up one page.

^f

Move screen down one page.

^l (letter l)

Redraw screen.

z - return

Make current line the top of screen.

nz - return

Make n line the top of screen.

z.

Make current line the middle line.

nz.

Make line n the middle line on screen.

z-

Make current line the bottom line.

nz-

Make line n the bottom line on screen.

Shell Escape Commands

You can run a UNIX command without exiting vi by using shell escape commands. You could do something as simple as start a subshell with the:sh command. You could also run a command outside the file you are editing without exiting vi. Table 8-18 describes shell escape commands:

Table 8-18. Shell Escape Commands in vi

Option

Action

:! command

Execute shell command command such as:! ls.

:!!

Execute last shell command.

:r! command

Read and insert output from command, such as:r! ls to run ls and read contents.

:w !command

Send currently edited file to command as standard input and execute command, such as:w ! grep all.

:cd directory

Change the current working directory to directory.

:sh

Start a sub-shell and use ^d (control-d) to return to vi.

:so file

Read and execute commands in the shell program file.

graphics/05icon13.gif

An example of using:w would be to send the file wisdom as standard input to grep, looking for all lines that contain all, asinthe following example:

:w ! grep all  Think of the small as  by a series of small acts. 

You can issue the:so command to read and execute the commands in a file. Issuing the following command when in vi would run the commands in the file file_with_commands:

:so file_with_commands 

This file contains the following two commands:

:set nu  :g/all/p 

When we issue the earlier:so command, line numbers are shown with the:set nu command and the following lines containing all are printed:

Think of the small as  by a series of small acts. 

Macros and Abbreviations

graphics/06icon04.gif

You are not limited to issuing individual vi commands. You can define strings of vi commands and define a key corresponding to this string that you can recall. When defining the keys for your macros, you can't use the following: K V g q v *= and function keys. There are also control keys you can't use, so stay away from control keys in general. Table 8-19 shows macros and abbreviations.

Table 8-19. Macros and Abbreviations in vi

Option

Action

:map key command_seq

Define key to run command_seq, such as:map e ea to append text whenever you use e to move to the end of a word.

:map

Display all defined macros on the status line.

:umap key

Remove the macro for key.

:ab string1 string2

Define an abbreviation such that when string1 is inserted, replace it with string2. When inserting text type string1, press escape key and string2 will be inserted.

:ab

Display all abbreviations.

:cd directory

Change the current working directory to directory.

:una string

Unabbreviate string.

 

Avoid control keys, symbols, and don't use characters: K V g q v *= and function keys.

An example of using the map command would be to automatically add text when you move to the end, as shown with the following map command:

:map e ea 

This command maps e to ea. When you go to the end of the next word with e, you are also placed in insert mode with a so that you can append new text immediately after the end of the word.

You can also abbreviate long sequences with ab. For instance, you could abbreviate system administration with sa with the following command:

:ab sa system administration 

Now, whenever you insert text, type sa and then presstheescape key to complete the insert; the string system administration appears. sa is an abbreviation for system administration.

Indenting Text

You can indent text in a variety of different ways. Table 8-20 shows some of the more commonly used indenting commands:

Table 8-20. Indenting Text in vi

Option

Action

^i (control i) or tab

While inserting text, insert on shift width. Shift width can be defined.

:set ai

Turn on auto-indentation.

:set sw=n

Set shift width to n characters.

n<<

Shift n lines left by one shift width.

n>>

Shift n lines right by one shift width. For example, 3>> shifts the next three lines right by oneshift width.

Before you adjust the shift width, you may want to issue:set all in order to see the current number of characters to which the shift width is set. It is usually eight characters by default. To set shift width to 16 characters, issue the following command:

:set sw=16 

You can then shift over the next three lines to the right by 16 characters each, with the following command:

3>> 

The next three lines are then shifted right by 16 characters.

Shell Filters

You can send information from the file you are editing to a command and then replace the original text with the output of the command. Table 8-21 shows a shell filter:

Table 8-21. Shell Filters in vi

Option

Action

!cursor_command command

Send text from the current position to that described by cursor_command to the shell command. For example, use !} grep admin to take text from the current position to the end of the paragraph, run this text through grep looking for the word admin, and replace existing text with the output of grep.

Pattern Matching

Pattern matching allows you to find patterns within the file you are editing. You can then perform functions such as changing what you have found in some way. Table 8-22 shows some of the most common pattern-matching commands:

Table 8-22. Pattern Matching in vi

Option

Action

^ (caret)

Match the beginning of the line. To search for Think at only the beginning of the line, you would use:

/^Think

You can use this in combination with $, which matches to the end of the line, to delete all blank lines with:

:g/^$/d.

$

Match end of line.

To match last. only when it is followed by a newline character, you would use:

/last.$

.

Match any single character.

\<

Match beginning of word.

\>

Match end of word.

[string]

Match any single character in string. To find mp, mP, Mp, or MP, use: /[mM][pP]

Change all occurrences of input or Input to INPUT with:

:%s/[Ii]nput/INPUT/g

[^string]

Match any character not in string.

[a-p]

Match any character between a and p.

*

Match zero or more occurrences of previous character in expression.

\

Escape meaning of next character. To search for [, use the following: /\[

\\

Escape the \ character.

You may find pattern matching a little confusing when you first start to use it, so I'll go through several simple examples to get you started. Keep in mind that many of the pattern-matching techniques described here also work outside vi in your shell.

graphics/06icon04.gif

Matching a Set

We'll begin with the square bracket operator. To match any of the single characters m, f, or p, you would use the following:

/[mfp] 

A common pattern to match would be a word with the first letter in the word, either uppercase or lowercase. To match input or Input, you would use the following:

/[Ii]nput 

After you match either Input or input, you could then change it to INPUT with the following command:

:%s/[Ii]nput/INPUT/g 

You can use sequences of expressions to search for more than one character, as shown in the following example:

/[mM][pP] 

This sequence will match mp, mP, Mp, or MP. You are, in effect, searching for any of the four two-character strings.

Matching a Range

You can also use the square bracket operator to match single characters within a range. To find an occurrence of any digit in a file, you could use either of the two following square bracket searches:

/[0123456789] 

or

/[0-9] 

The hyphen denotes a range within the square bracket. To find any character, either uppercase or lowercase, you could use the following:

/[a-zA-Z] 

To search for characters that normally have a special meaning, such as [, you can ignore, or escape, the special meaning by preceding the special character with a \ (backslash). To search for [in vi, for instance, you would use the following sequence:

/\[

This search finds the first occurrence of [.

Beginning and End of Line Search

You can specify that you wish your pattern match to take place at only the beginning or end of a line. To specify a beginning of the line pattern match, use the ^ (caret) preceding your desired pattern, as shown in the following example:

/^Think 

This matches Think only when it appears at the beginning of a line.

To specify an end-of-the-line pattern match, use a $ (dollar sign) following your desired pattern, as shown in the following example:

/last.$ 

This matches last. only when it is followed by a newline.

Manual Pages for vi Command Used in Chapter 8

The following section contains copies of the manual pages for vi.

vi

graphics/06icon04.gif

vi - Run visual editor.

vi(1)                                                                 vi(1)  NAME       vi, view, vedit - screen-oriented (visual) text editor  SYNOPSIS       vi [-] [-l] [-r] [-R] [-t tag] [-v] [-V] [-wsize] [-x] [+command] [file       ...]     XPG4 Synopsis       vi [-rR] [-c command] [-t tag] [-w size] [file ...]     Obsolescent Options       vi [-rR] [+command] [-t tag] [-w size] [file ...]       view [-] [-l] [-r] [-R] [-t tag] [-v] [-V] [-wsize] [-x] [+command]       [file ...]       vedit [-] [-r] [-R] [-l] [-t tag] [-v] [-V] [-wsize] [-x] [+command]       [file ...]     Remarks       The program names ex, edit, vi, view, and vedit are separate       personalities of the same program. This manual entry describes the       behavior of the vi/view/vedit personality.  DESCRIPTION       The vi (visual) program is a display-oriented text editor that is       based on the underlying ex line editor (see ex(1)). It is possible to       switch back and forth between the two and to execute ex commands from       within vi. The line-editor commands and the editor options are       described in ex(1). Only the visual mode commands are described here.       The view program is identical to vi except that the readonly editor       option is set (see ex(1)).       The vedit program is somewhat friendlier for beginners and casual       users. The report editor option is set to 1, and the nomagic, novice,       and showmode editor options are set.       In vi, the terminal screen acts as a window into a memory copy of the       file being edited. Changes made to the file copy are reflected in the       screen display. The position of the cursor on the screen indicates       the position within the file copy.       The environment variable TERM must specify a terminal type that is       defined in the terminfo database (see terminfo(4)). Otherwise, a       message is displayed and the line-editor is invoked.       As with ex, editor initialization scripts can be placed in the       environment variable EXINIT, or in the file .exrc in the current or       home directory.     Options and Arguments       vi recognizes the following command-line options and arguments:            -         Suppress all interactive-user feedback. This is useful                      when editor commands are taken from scripts.            -l        Set the lisp editor option (see ex(1)). Provides                      indents appropriate for lisp code. The (, ), {, }, [[,                      and ]] commands in vi are modified to function with                      lisp source code.            -r        Recover the specified files after an editor or system                      crash. If no file is specified, a list of all saved                      files is printed. You must be the owner of the saved                      file in order to recover it (superuser cannot recover                      files owned by other users).            -R        Set the readonly editor option to prevent overwriting a                      file inadvertently (see ex(1)).            -t tag    Execute the tag tag command to load and position a                      predefined file. See the tag command and the tags                      editor option in ex(1).            -v        Invoke visual mode (vi). Useful with ex, it has no                      effect on vi.            -V        Set verbose mode. Editor commands are displayed as                      they are executed when input from a .exrc file or a                      source file (see the source command in ex(1)).            -wsize    Set the value of the window editor option to size. If                      size is omitted, it defaults to 3.            -x        Set encryption mode. You are prompted for a key to                      allow for the creation or editing of an encrypted file                      (see the crypt command in ex(1)).            -c command  (XPG4 only.)            +command  (Obsolescent) Begin editing by executing the specified                      ex command-mode commands. As with the normal ex                      command-line entries, the command option-argument can                      consist of multiple ex commands separated by vertical-                     line commands (|). The use of commands that enter input                      mode in this manner produces undefined results.            file      Specify the file or files to be edited. If more than                      one file is specified, they are processed in the order                      given. If the -r option is also specified, the files                      are read from the recovery area.       (XPG4 only.) If both the -t tag and -c command (or the obsolescent       +command) options are given, the -t tag will be processed first, that       is, the file containing the tag is selected by -t and then the command       is executed.       When invoked, vi is in command mode. input mode is initiated by       several commands used to insert or change text.       In input mode, ESC (escape) is used to leave input mode; however, two       consecutive ESC characters are required to leave input mode if the       doubleescape editor option is set (see ex(1)).       In command mode, ESC is used to cancel a partial command; the terminal       bell sounds if the editor is not in input mode and there is no       partially entered command.       WARNING: ESC completes a "bottom line" command (see below).       The last (bottom) line of the screen is used to echo the input for       search commands (/ and ?), ex commands (:), and system commands (!).       It is also used to report errors or print other messages.       The receipt of SIGINT during text input or during the input of a       command on the bottom line terminates the input (or cancels the       command) and returns the editor to command mode. During command mode,       SIGINT causes the bell to be sounded. In general the bell indicates       an error (such as an unrecognized key).       Lines displayed on the screen containing only a Zindicatethatthe       last li~e above them is the last line of the file (the Z lines are       past the end o~ the file). Terminals with limited local intelligence       might display lines on the screen marked with an @. These indicate       space on the screen not corresponding to lines in the file. (These       lines can be removed by entering a ^R, forcing the editor to retype       the screen without these holes.)       If the system crashes or vi aborts due to an internal error or       unexpected signal, vi attempts to preserve the buffer if any unwritten       changes were made. Use the -r command line option to retrieve the       saved changes.       The vi text editor supports the SIGWINCH signal, and redraws the       screen in response to window-size changes.     Command Summary       Most commands accept a preceding number as an argument, either to give       a size or position (for display or movement commands), or as a repeat       count (for commands that change text). For simplicity, this optional       argument is referred to as count when its effect is described.       The following operators can be followed by a movement command to       specify an extent of text to be affected: c, d, y, <, >, !, and =.       The region specified begins at the current cursor position and ends       just prior to the cursor position indicated by the move. If the       command operates on lines only, all the lines that fall partly or       wholly within this region are affected. Otherwise the exact marked       region is affected.       In the following description, control characters are indicated in the       form ^X, which represents Ctrl-X. Whitespace is defined to be the       characters space, tab, and alternative space. Alternative space is       the first character of the ALT_PUNCT item described in langinfo(5) for       the language specified by the LANG environment variable (see       environ(5)).       Unless otherwise specified, the commands are interpreted in command       mode and have no special effect in input mode.            ^B          Scroll backward to display the previous window of                        text. A preceding count specifies the number of                        windows to go back. Two lines of overlap are kept if                        possible.            ^D          Scroll forward a half-window of text. A preceding                        count gives the number of (logical) lines to scroll,                        and is remembered for future ^D and ^U commands.            ^D          (input mode) Backs up over the indentation provided                        by autoindent or ^T to the next multiple of                        shiftwidth spaces. Whitespace inserted by ^T at                        other than the beginning of a line cannot be backed                        over using ^D. A preceding ^ removes all indentation                        for the current and subsequent input lines of the                        current input mode until new indentation is                        established by inserting leading whitespace, either                        by direct input or by using ^T.            ^E          Scroll forward one line, leaving the cursor where it                        is if possible.            ^F          Scroll forward to display the window of text                        following the current one. A preceding count                        specifies the number of windows to advance. Two                        lines of overlap are kept if possible.                        (XPG4 only.) The current line is displayed and the                        cursor is moved to the first nonblank character of                        the current line or the first character if the line                        is a blank line.            ^G          Print the current file name and other information,                        including the number of lines and the current                        position (equivalent to the ex command f).            ^H          Move one space to the left (stops at the left                        margin). A preceding count specifies the number of                        spaces to back up. (Same as h).            ^H          (input mode) Move the cursor left to the previous                        input character without erasing it from the screen.                        The character is deleted from the saved text.            ^J          Move the cursor down one line in the same column, if                        possible. A preceding count specifies the number of                        lines to move down. (Same as ^N and j).            ^L          Clear and redraw the screen. Use when the screen is                        scrambled for any reason.            ^M          Move to the first nonwhitespace character in the next                        line. A preceding count specifies the number of                        lines to advance.            ^N          Same as ^J and j.            ^P          Move the cursor up one line in the same column. A                        preceding count specifies the number of lines to move                        up (same as k).            ^R          Redraw the current screen, eliminating the false                        lines marked with @ (which do not correspond to                        actual lines in the file).            ^T          Pop the tag stack. See the pop command in ex(1).            ^T          (input mode) Insert shiftwidth whitespace. If at the                        beginning of the line, this inserted space can only                        be backed over using ^D.            ^U          Scroll up a half-window of text. A preceding count                        gives the number of (logical) lines to scroll, and is                        remembered for future ^D and ^U commands.            ^V          In input mode, ^V quotes the next character to permit                        the insertion of special characters (including ESC)                        into the file.            ^W          In input mode, ^W backs up one word; the deleted                        characters remain on the display.            ^Y          Scroll backward one line, leaving the cursor where it                        is, if possible.            ^[          Cancel a partially formed command; ^[ sounds the bell                        if there is no partially formed command.                        In input mode, ^[ terminates input mode. However,                        two consecutive ESC characters are required to                        terminate input mode if the doubleescape editor                        option is set (see ex(1)).                        When entering a command on the bottom line of the                        screen (ex command line or search pattern with \ or                        ?), terminate input and execute command.                        On many terminals, ^[ can be entered by pressing the                        ESC or ESCAPE key.            ^\          Exit vi and enter ex command mode. If in input mode,                        terminate the input first.            ^]          Take the word at or after the cursor as a tag and                        execute the tagMbobC editor command (see ex(1)).            ^^          Return to the previous file (equivalent to :ex #).            space       Move one space to the right (stops at the end of the                        line). A preceding count specifies the number of                        spaces to go forward (same as l).            erase       Erase, where erase is the user-designated erase                        character (see stty(1)). Same as ^H.            kill        Kill, where kill is the user-designated kill                        character (see stty(1)). In input mode, kill backs                        up to the beginning of the current input line without                        erasing the line from the screen display.            susp        Suspend the editor session and return to the calling                        shell, where susp is the user-designated process-                       control suspend character (see stty(1)). See ex(1)                        for more information on the suspend editor command.            !           An operator that passes specified lines from the                        buffer as standard input to the specified system                        command, and replaces those lines with the standard                        output from the command. The ! is followed by a                        movement command specifying the lines to be passed                        (lines from the current position to the end of the                        movement) and then the command (terminated as usual                        by a return). A preceding count is passed on to the                        movement command after !.                        Doubling ! and preceding it by count causes that                        many lines, starting with the current line, to be                        passed.            "           Use to precede a named buffer specification. There                        are named buffers 1 through 9 in which the editor                        places deleted text. The named buffers a through z                        are available to the user for saving deleted or                        yanked text; see also y, below.            $           Move to the end of the current line. A preceding                        count specifies the number of lines to advance (for                        example, 2$ causes the cursor to advance to the end                        of the next line).            %           Move to the parenthesis or brace that matches the                        parenthesis or brace at the current cursor position.            &           Same as the ex command & (that is, & repeats the                        previous substitute command).            '           When followed by a ', vi returns to the previous                        context, placing the cursor at the beginning of the                        line. (The previous context is set whenever a                        nonrelative move is made.) When followed by a letter                        a-z, returns to the line marked with that letter (see                        the m command), at the first nonwhitespace character                        in the line.                        When used with an operator such as d to specify an                        extent of text, the operation takes place over                        complete lines (see also `).            `           When followed by a `, vi returns to the previous                        context, placing the cursor at the character position                        marked (the previous context is set whenever a                        nonrelative move is made). When followed by a letter                        a z, returns to the line marked with that letter (see                        the m command), at the character position marked.                        When used with an operator such as d to specify an                        extent of text, the operation takes place from the                        exact marked place to the current position within the                        line (see also ').            [[          Back up to the previous section boundary. A section                        is defined by the value of the sections option.                        Lines that start with a form feed (^L) or { also stop                        [[.                        If the option lisp is set, the cursor stops at each (                       at the beginning of a line.            ]]          Move forward to a section boundary (see [[).            ^           Move to the first nonwhitespace position on the                        current line.            (           Move backward to the beginning of a sentence. A                        sentence ends at a ., !, or ? followed by either the                        end of a line or by two spaces. Any number of                        closing ), ], ", and ' characters can appear between                        the ., !, or ? and the spaces or end of line. If a                        count is specified, the cursor moves back the                        specified number of sentences.                        If the lisp option is set, the cursor moves to the                        beginning of a lisp s-expression. Sentences also                        begin at paragraph and section boundaries (see { and                        [[).            )           Move forward to the beginning of a sentence. If a                        count is specified, the cursor advances the specified                        number of sentences (see ().            {           Move back to the beginning of the preceding                        paragraph. A paragraph is defined by the value of                        the paragraphs option. A completely empty line and a                        section boundary (see [[ above) are also interpreted                        as the beginning of a paragraph. If a count is                        specified, the cursor moves backward the specified                        number of paragraphs.            }           Move forward to the beginning of the next paragraph.                        If a count is specified, the cursor advances the                        specified number of paragraphs (see {).            |           Requires a preceding count; the cursor moves to the                        specified column of the current line (if possible).            +           Move to the first nonwhitespace character in the next                        line. If a count is specified, the cursor advances                        the specified number of lines (same as ^M).            ,           The comma (,) performs the reverse action of the last                        f, F, t, or T command issued, by searching in the                        opposite direction on the current line. If a count                        is specified, the cursor repeats the search the                        specified number of times.            -           The hyphen character (-) moves the cursor to the                        first nonwhitespace character in the previous line.                        If a count is specified, the cursor moves back the                        specified number of times.            _           The underscore character (_) moves the cursor to the                        first nonwhitespace character in the current line.                        If a count is specified, the cursor advances the                        specified number of lines, with the current line                        being counted as the first line; no count or a count                        of 1 specifies the current line.            .           Repeat the last command that changed the buffer. If                        a count is specified, the command is repeated the                        specified number of times.            /           Read a string from the last line on the screen,                        interpret it as a regular expression, and scan                        forward for the next occurrence of a matching string.                        The search begins when the user types a carriage                        return to terminate the pattern; the search can be                        terminated by sending SIGINT (or the user-designated                        interrupt character).                        When used with an operator to specify an extent of                        text, the defined region begins with the current                        cursor position and ends at the beginning of the                        matched string. Entire lines can be specified by                        giving an offset from the matched line (by using a                        closing / followed by a +n or -n).            0           Move to the first character on the current line (the                        0 is not interpreted as a command when preceded by a                        nonzero digit).            :           The colon character (:) begins an ex command. The :                        and the entered command are echoed on the bottom                        line; the ex command is executed when the user types                        a carriage return.            ;           Repeat the last single character find using f, F, t,                        or T. If a count is specified, the search is                        repeated the specified number of times.            <           An operator that shifts lines to the left by one                        shiftwidth. The < can be followed by a move to                        specify lines. A preceding count is passed through                        to the move command.                        When repeated (<<), shifts the current line (or count                        lines starting at the current one).            >           An operator that shifts lines right one shiftwidth                        (see <).            =           If the lisp option is set, = reindents the specified                        lines, as if they were typed in with lisp and                        autoindent set. = can be preceded by a count to                        indicate how many lines to process, or followed by a                        move command for the same purpose.            ?           Scan backwards, the reverse of / (see /).            @buffer     Execute the commands stored in the named buffer. Be                        careful not to include a <return> character at the                        end of the buffer contents unless the <return> is                        part of the command stream. Commands to be executed                        in ex mode should be preceded by a colon (:).            ~           The tilde (~) switches the case of the character                        under the cursor (if it is a letter), then moves one                        character to the right, stopping at the end of the                        line). A preceding count specifies how many                        characters in the current line are switched.            A           Append at the end of line (same as $a).            B           Back up one word, where a word is any nonblank                        sequence, placing the cursor at the beginning of the                        word. If a count is specified, the cursor moves back                        the specified number of words.            C           Change the rest of the text on the current line (same                        as c$).            D           Delete the rest of the text on the current line (same                        as d$).            E           Move forward to the end of a word, where a word is                        any nonblank sequence. If a count is specified, the                        cursor advances the specified number of words.            F           Must be followed by a single character; scans                        backwards in the current line, searching for that                        character and moving the cursor to it, if found. If                        a count is specified, the search is repeated the                        specified number of times.            G           Go to the line number given as preceding argument, or                        the end of the file if no preceding count is given.            H           Move the cursor to the top line on the screen. If a                        count is given, the cursor moves to count number of                        lines from the top of the screen. The cursor is                        placed on the first nonwhitespace character on the                        line. If used as the target of an operator, entire                        lines are affected.            I           Insert at the beginning of a line (same as ^ followed                        by i).            J           Join the current line with the next one, supplying                        appropriate whitespace: one space between words, two                        spaces after a period, and no spaces at all if the                        first character of the next line is a closing                        parenthesis ()). A preceding count causes the                        specified number of lines to be joined, instead of                        just two.            L           Move the cursor to the first nonwhitespace character                        of the last line on the screen. If a count is given,                        the cursor moves to count number of lines from the                        bottom of the screen. When used with an operator,                        entire lines are affected.            M           Move the cursor to the middle line on the screen, at                        the first nonwhitespace position on the line.            N           Scan for the next match of the last pattern given to                        / or ?, but in the opposite direction; this is the                        reverse of n.            O           Open a new line above the current line and enter                        input mode.            P           Put back (replace) the last deleted or yanked text                        before/above the cursor. Entire lines of text are                        returned above the cursor if entire lines were                        deleted or yanked. Otherwise, the text is inserted                        just before the cursor.                        (XPG4 only.) In this case, the cursor is moved to                        last column position of the inserted characters.                        If P is preceded by a named buffer specification (x),                        the contents of that buffer are retrieved instead.            Q           Exit vi and enter ex command mode.            R           Replace characters on the screen with characters                        entered, until the input is terminated with ESC.            S           Change entire lines (same as cc). A preceding count                        changes the specified number of lines.            T           Must be followed by a single character; scan                        backwards in the current line for that character,                        and, if found, place the cursor just after that                        character. A count is equivalent to repeating the                        search the specified number of times.            U           Restore the current line to its state before the                        cursor was last moved to it.                        (XPG4 only.) The cursor position is set to the column                        position 1 or to the position indicated by the                        previous line if the autoindent is set.            W           Move forward to the beginning of a word in the                        current line, where a word is a sequence of nonblank                        characters. If the current position is at the                        beginning of a word, the current position is within a                        bigword or the character at that position cannot be a                        part of a bigword, the current position shall move to                        the first character of the next bigword. If no                        subsequent bigword exists on the current line, the                        current position shall move to the first character of                        the first bigword on the first following line that                        contains the bigword. For this command, an empty or                        blank line is considered to contain exactly one                        bigword. The current line is set to the line                        containing the bigword selected and the current                        position is set to the first character of the bigword                        selected. A preceding count specifies the number of                        words to advance.            X           Delete the character before the cursor. A preceding                        count repeats the effect, but only characters on the                        current line are deleted.            Y           Place (yank) a copy of the current line into the                        unnamed buffer (same as yy). If a count is                        specified, count lines are copied to the buffer. If                        the Y is preceded by a buffer name, the lines are                        copied to the named buffer.            ZZ          Exit the editor, writing out the buffer if it was                        changed since the last write (same as the ex command                        x). Note that if the last write was to a different                        file and no changes have occurred since, the editor                        exits without writing out the buffer.            a           Enter input mode, appending the entered text after                        the current cursor position. A preceding count                        causes the inserted text to be replicated the                        specified number of times, but only if the inserted                        text is all on one line.            b           Back up to the previous beginning of a word in the                        current line. A word is a sequence of alphanumerics                        or a sequence of special characters. A preceding                        count repeats the effect.            c           Must be followed by a movement command. Delete the                        specified region of text, and enter input mode to                        replace deleted text with new text. If more than                        part of a single line is affected, the deleted text                        is saved in the numeric buffers. If only part of the                        current line is affected, the last character deleted                        is marked with a $. A preceding count passes that                        value through to the move command. If the command is                        cc, the entire current line is changed.            d           Must be followed by a movement command. Delete the                        specified region of text. If more than part of a                        line is affected, the text is saved in the numeric                        buffers. A preceding count passes that value through                        to the move command. If the command is dd, the                        entire current line is deleted.            e           Move forward to the end of the next word, defined as                        for b. A preceding count repeats the effect.            f           Must be followed by a single character; scan the rest                        of the current line for that character, and moves the                        cursor to it if found. A preceding count repeats the                        action that many times.            h           Move the cursor one character to the left (same as                        ^H). A preceding count repeats the effect.            i           Enter input mode, inserting the entered text before                        the cursor (see a).            j           Move the cursor one line down in the same column                        (same as ^J and ^N).            k           Move the cursor one line up (same as ^P).            l           Move the cursor one character to the right (same as                        <space>).            mx          Mark the current position of the cursor. x is a                        lowercase letter, a-z, that is used with the ` and '                        commands to refer to the marked line or line                        position.            n           Repeat the last / or ? scanning commands.            o           Open a line below the current line and enter input                        mode; otherwise like O.            p           Put text after/below the cursor; otherwise like P.            r           Must be followed by a single character; the character                        under the cursor is replaced by the specified one.                        (The new character can be a new-line.) If r is                        preceded by a count, count characters are replaced by                        the specified character.            s           Delete the single character under the cursor and                        enter input mode; the entered text replaces the                        deleted character. A preceding count specifies how                        many characters on the current line are changed. The                        last character being changed is marked with a $, as                        for c.            t           Must be followed by a single character; scan the                        remainder of the line for that character. The cursor                        moves to the column prior to the character if the                        character is found. A preceding count is equivalent                        to repeating the search count times.            u           Reverse the last change made to the current buffer.                        If repeated, u alternates between these two states;                        thus is its own inverse. When used after an                        insertion of text on more than one line, the lines                        are saved in the numerically named buffers.            w           Move forward to the beginning of the next word (where                        word is defined as in b). A preceding count                        specifies how many words the cursor advances.            x           Delete the single character under the cursor. When x                        is preceded by a count, x deletes the specified                        number of characters forward from the cursor                        position, but only on the current line.            y           Must be followed by a movement command; the specified                        text is copied (yanked) into the unnamed temporary                        buffer. If preceded by a named buffer specification,                        "x, the text is placed in that buffer also. If the                        command is yy, the entire current line is yanked.            z           Redraw the screen with the current line placed as                        specified by the following options: z<return>                        specifies the top of the screen, z. the center of                        the screen, and z- the bottom of the screen. The                        commands z^ and z+ are similar to ^B and ^F,                        respectively. However, z^ and z+ do not attempt to                        maintain two lines of overlap. A count after the z                        and before the following character to specifies the                        number of lines displayed in the redrawn screen. A                        count before the z gives the number of the line to                        use as the reference line instead of the default                        current line.     Keyboard Editing Keys       At initialization, the editor automatically maps some terminal       keyboard editing keys to equivalent visual mode commands. These       mappings are only established for keys that are listed in the       following table and defined in the terminfo(4) database as valid for       the current terminal (as specified by the TERM environment variable).       Both command and input mode mappings are created (see the map command       in ex(1)). With the exception of the insertchar keys, which simply       toggle input mode on and off, the input mode mappings exit input mode,       perform the same action as the command mode mapping, and then reenter       input mode.       On certain terminals, the character sequence sent by a keyboard       editing key, which is then mapped to a visual mode command, can be the       same character sequence a user might enter to perform another command       or set of commands. This is most likely to happen with the input mode       mappings; therefore, on these terminals, the input mode mappings are       disabled by default. Users can override the disabling and enabling of       both the command and input mode keyboard editing key mappings by       setting the keyboardedit and keyboardedit! editor options as       appropriate (see ex(1)). The timeout, timeoutlen, and doubleescape       editor options are alternative methods of addressing this problem.         terminfo    command    input      map         entry       mode map   mode map   name      description         __________________________________________________________________         key_ic      i          ^[         inschar   insert char         key_eic     i          ^[         inschar   end insert char         key_up      k          ^[ka       up        arrow up         key_down    j          ^[ja       down      arrow down         key_left    h          ^[ha       left      arrow left         key_right   l          ^[la       right     arrow right         key_home    H          ^[Ha       home      arrow home         key_il      o^[        ^[o^[a     insline   insert line         key_dl      dd         ^[dda      delline   delete line         key_clear   ^L         ^[^La      clear     clear screen         key_eol     d$         ^[d$a      clreol    clear line         key_sf      ^E         ^[^Ea      scrollf   scroll down         key_dc      x          ^[xa       delchar   delete char         key_npage   ^F         ^[^Fa      npage     next page         key_ppage   ^B         ^[^Ba      ppage     previous page         key_sr      ^Y         ^[^Ya      sr        scroll up         key_eos     dG         ^[dGa      clreos    clear to end of screen         __________________________________________________________________  EXTERNAL INFLUENCES       Support for international codes and environment variables are as       follows:     Environment Variables       UNIX95 specifies using the XPG4 behaviour for this command.       COLUMNS overrides the system-selected horizontal screen size.       LINES overrides the system-selected vertical screen size, used as the       number of lines in a screenful and the vertical screen size in visual       mode.       SHELL is a variable that shall be interpreted as the preferred       command-line interpreter for use in !, shell, read, and other commands       with an operand of the form !string. For the shell command the       program shall be invoked with the two arguments -c and string. If       this variable is null or not set, the sh utility shall be used.       TERM is a variable that shall be interpreted as the name of the       terminal type. If this variable is unset or null, an unspecified       default terminal type shall be used.       PATH determines the search path for the shell command specified in the       editor commands, shell, read, and write. EXINIT determines a list of       ex commands that will be executed on editor startup, before reading       the first file. The list can contain multiple commands by separating       them using a vertical line (|) character.       HOME determines a pathname of a directory that will be searched for an       editor startup file named .exrc.       LC_ALL This variable shall determine the locale to be used to override       any values for locale categories specified by the setting of LANG or       any environment variables beginning with LC_.       LC_MESSAGES determines the locale that should be used to affect the       format and contents of diagnostic messages written to standard error       and informative messages written to standard output.       LC_COLLATE determines the collating sequence used in evaluating       regular expressions and in processing the tags file. LC_CTYPE       determines the interpretation of text as single and/or multi-byte       characters, the classification of characters as uppercase or lowercase       letters, the shifting of letters between uppercase and lowercase, and       the characters matched by character class expressions in regular       expressions.       LANG determines the language in which messages are displayed.       LANGOPTS specifies options determining how text for right-to-left       languages is stored in input and output files. See environ(5).       If LC_COLLATE or LC_CTYPE is not specified in the environment or is       set to the empty string, the value of LANG is used as a default for       each unspecified or empty variable. If LANG is not specified or is       set to the empty string, a default of "C" (see lang(5)) is used       instead of LANG. If any internationalization variable contains an       invalid setting, the editor behaves as if all internationalization       variables are set to "C". See environ(5).     International Code Set Support       Single- and multi-byte character code sets are supported.  WARNINGS       See also the WARNINGS section in ex(1).     Program Limits       vi places the following limits on files being edited:       Maximum Line Length            LINE_MAX characters (defined in <limits.h>), including 2-3 bytes            for overhead. Thus, if the value specified for LINE_MAX is 2048,            a line length up to 2044 characters should cause no problem.            If you load a file that contain lines longer than the specified            limit, the lines are truncated to the stated maximum length.            Saving the file will write the truncated version over the            original file, thus overwriting the original lines completely.            Attempting to create lines longer than the allowable maximum for            the editor produces a line too long error message.       Maximum File Size            The maximum file length of 234,239 lines is silently enforced.       Other limits:            -  256 characters per global command list.            -  128 characters in a file name in vi or ex open mode. On               short-file-name HP-UX systems, the maximum file name length is               14 characters.            -  128 characters in a previous insert/delete buffer.            -  100 characters in a shell-escape command.            -  63 characters in a string-valued option (:set command).            -  30 characters in a program tag name.            -  32 or fewer macros defined by map command.            -  512 or fewer characters total in combined map macros.  AUTHOR       vi was developed by the University of California, Berkeley. The 16-      bit extensions to vi are based in part on software of the Toshiba       Corporation.  SEE ALSO       ctags(1), ed(1), ex(1), stty(1), write(1), terminfo(4), environ(5),       lang(5), regexp(5).       The Ultimate Guide to the vi and ex Text Editors,            Benjamin/Cummings Publishing Company, Inc., ISBN 0-8053-4460-8,            HP part number 97005-90015.  STANDARDS CONFORMANCE       vi: SVID2, SVID3, XPG2, XPG3, XPG4 
CONTENTS


UNIX User's Handbook
UNIX Users Handbook (2nd Edition)
ISBN: 0130654191
EAN: 2147483647
Year: 2001
Pages: 34

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net