BUY THIS BOOK
Add to Cart

Print Book $9.95


Add to Cart

Print+PDF $12.93

Add to Cart

PDF $7.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £6.95

What is this?

Looking to Reprint or License this content?


vi Editor Pocket Reference
vi Editor Pocket Reference

By Arnold Robbins
Book Price: $9.95 USD
£6.95 GBP
PDF Price: $7.99

Cover | Table of Contents


Table of Contents

Chapter 1: vi Editor Pocket Reference
This pocket reference is a companion to Learning the vi Editor, by Linda Lamb and Arnold Robbins. It describes the vi command-line options, command mode commands, ex commands and options, regular expressions and the use of the substitute (s) command, and other pertinent information for using vi. Also covered are the additional features in the four vi clones, nvi, elvis, vim, and vile.
The Solaris 2.6 version of vi served as the “reference” version of vi for this pocket reference.
The following font conventions are used in this book:
Courier
Used for command names, options, and everything to be typed literally
Courier Italic
Used for replaceable text within commands
Italic
Used for replaceable text within regular text, program names, filenames, paths, for emphasis, and new terms when first defined
[ … ]
Identifies optional text; the brackets are not typed
CTRL-G
Indicates a keystroke
CommandAction
vi file
Invoke vi on file
vi file1 file2
Invoke vi on files sequentially
view file
Invoke vi on file in read-only mode
vi -R file
Invoke vi on file in read-only mode
vi -r file
Recover file and recent edits after a crash
vi -t tag
Look up tag and start editing at its definition
vi -w n
Set the window size to n; useful over a slow connection
vi + file
Open file at last line
vi +n file
Open file directly at line number n
vi -c command file
Open file, execute command, which is usually a search command or line number (POSIX)
vi +/pattern file
Open file directly at pattern
ex file
Invoke ex on file
ex - file < script
Invoke ex on file, taking commands from script; suppress informative messages and prompts
ex -s file < script
Invoke ex on file, taking commands from script; suppress informative messages and prompts (POSIX)
Most vi commands follow a general pattern:
[command][number]text object
or the equivalent form:
[number][command]text object
CommandMeaning
Character
h, j, k, l
Left, down, up, right (, , , )
Text
w, W, b, B
Forward, backward by word
e, E
End of word
), (
Beginning of next, previous sentence
}, {
Beginning of next, previous paragraph
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
This pocket reference is a companion to Learning the vi Editor, by Linda Lamb and Arnold Robbins. It describes the vi command-line options, command mode commands, ex commands and options, regular expressions and the use of the substitute (s) command, and other pertinent information for using vi. Also covered are the additional features in the four vi clones, nvi, elvis, vim, and vile.
The Solaris 2.6 version of vi served as the “reference” version of vi for this pocket reference.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conventions
The following font conventions are used in this book:
Courier
Used for command names, options, and everything to be typed literally
Courier Italic
Used for replaceable text within commands
Italic
Used for replaceable text within regular text, program names, filenames, paths, for emphasis, and new terms when first defined
[ … ]
Identifies optional text; the brackets are not typed
CTRL-G
Indicates a keystroke
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Command-Line Options
CommandAction
vi file
Invoke vi on file
vi file1 file2
Invoke vi on files sequentially
view file
Invoke vi on file in read-only mode
vi -R file
Invoke vi on file in read-only mode
vi -r file
Recover file and recent edits after a crash
vi -t tag
Look up tag and start editing at its definition
vi -w n
Set the window size to n; useful over a slow connection
vi + file
Open file at last line
vi +n file
Open file directly at line number n
vi -c command file
Open file, execute command, which is usually a search command or line number (POSIX)
vi +/pattern file
Open file directly at pattern
ex file
Invoke ex on file
ex - file < script
Invoke ex on file, taking commands from script; suppress informative messages and prompts
ex -s file < script
Invoke ex on file, taking commands from script; suppress informative messages and prompts (POSIX)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
vi Commands
Most vi commands follow a general pattern:
[command][number]text object
or the equivalent form:
[number][command]text object
CommandMeaning
Character
h, j, k, l
Left, down, up, right (, , , )
Text
w, W, b, B
Forward, backward by word
e, E
End of word
), (
Beginning of next, previous sentence
}, {
Beginning of next, previous paragraph
]], [[
Beginning of next, previous section
Lines
RETURN
First nonblank character of next line
0, $
First, last position of current line
^
First nonblank character of current line
+, -
First nonblank character of next, previous line
n|
Column n of current line
H
Top line of screen
M
Middle line of screen
L
Last line of screen
nH
n (number) of lines after top line
nL
n (number) of lines before last line
Scrolling
CTRL-F, CTRL-B
Scroll forward, backward one screen
CTRL-D, CTRL-U
Scroll down, up one-half screen
CTRL-E, CTRL-Y
Show one more line at bottom, top of window
z RETURN
Reposition line with cursor: to top of screen
z.
Reposition line with cursor: to middle of screen
z
Reposition line with cursor: to bottom of screen
CTRL-L
Redraw screen (without scrolling)
Searches
/pattern
Search forward for pattern
?pattern
Search backward for pattern
n, N
Repeat last search in same, opposite direction
/, ?
Repeat previous search forward, backward
fx
Search forward for character x in current line
Fx
Search backward for character x in current line
tx
Search forward to character before x in current line
Tx
Search backward to character after x in current line
;
Repeat previous current-line search
,
Repeat previous current-line search in opposite direction
Line number
CTRL-G
Display current line number
nG
Move to line number n
G
Move to last line in file
:n
Move to line n in file
Marking position
mx
Mark current position as x
x
Move cursor to mark x
‘‘
Return to previous mark or context
x
Move to beginning of line containing mark x
Return to beginning of line containing previous mark
CommandAction
Insert
i, a
Insert text before, after cursor
I, A
Insert text before beginning, after end of line
o, O
Open new line for text below, above cursor
Change
r
Replace character
cw
Change word
cc
Change current line
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Input Mode Shortcuts
:ab abbr phrase
Define abbr as an abbreviation for phrase.
:unab abbr
Remove definition of abbr.
Be careful with abbreviation texts that either end with the abbreviation name or contain the abbreviation name in the middle.
:map x sequence
Define character(s) x as a sequence of editing commands.
:unmap x
Disable the sequence defined for x.
:map
List the characters that are currently mapped.
:map! x sequence
Define character(s) x as a sequence of editing commands or text that will be recognized in input mode.
:unmap! x
Disable the sequence defined for the input mode map x.
:map!
List the characters that are currently mapped for interpretation in insert mode.
For both command and input mode maps, the map name x can take several forms:
One character
When you type the character, vi executes the associated sequence of commands.
Multiple characters
All the characters must be typed within one second. The value of notimeout changes the behavior.
#n
Function key notation: a # followed by a digit n represents the sequence of characters sent by the terminal’s function key number n.
To enter characters such as Escape (^[) or carriage return (^M), first type a CTRL-V (^V).
Named buffers provide yet another way to create “macros”—complex command sequences you can repeat with a few keystrokes. Here's how it's done:
  1. Type a vi command sequence or an ex command preceded by a colon; return to command mode.
  2. Delete the text into a named buffer.
  3. Execute the buffer with the @ command followed by the buffer letter.
The ex command :@buf-name works similarly.
Some versions treat * identically to @ when used from the ex command line. In addition, if the buffer character supplied after the @ or * commands is *, the command is taken from the default (unnamed) buffer.
You enable automatic indentation with the command:
:set autoindent
Four special input sequences affect automatic indentation:
^T
Add one level of indentation; typed in insert mode
^D
Remove one level of indentation; typed in insert mode
^ ^D
Shift the cursor back to the beginning of the line, but only for the current line
0 ^D
Shift the cursor back to the beginning of the line and reset the current auto-indent level to zero
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Substitution and Regular Expressions
The general form of the substitute command is:
:[addr1[,addr2]]s/old/new/[flags]
Omitting the search pattern (:s//replacement/) uses the last search or substitution regular expression.
An empty replacement part (:s/pattern//) “replaces” the matched text with nothing, effectively deleting it from the line.

Section 1.4.1.1: Substitution flags

Flag
Meaning
c
Confirm each substitution
g
Change all occurrences of old to new on each line (globally)
p
Print the line after the change is made
It's often useful to combine the substitute command with the ex global command, :g:

:g/Object Oriented/s//Buzzword compliant/g
.
Matches any single character except a newline. Remember that spaces are treated as characters.
*
Matches zero or more (as many as there are) of the single character that immediately precedes it.
The * can follow a metacharacter, such as . or a range in brackets.
^
When used at the start of a regular expression, ^ requires that the following regular expression be found at the beginning of the line. When not at the beginning of a regular expression, ^ stands for itself.
$
When used at the end of a regular expression, $ requires that the preceding regular expression be found at the end of the line. When not at the end of a regular expression, $ stands for itself.
\
Treats the following special character as an ordinary character. (Use \\ to get a literal backslash.)
[ ]
Matches any one of the characters enclosed between the brackets. A range of consecutive characters can be specified by separating the first and last characters in the range with a hyphen.
You can include more than one range inside brackets and specify a mix of ranges and separate characters.
Most metacharacters lose their special meaning inside brackets, so you don’t need to escape them if you want to use them as ordinary characters. Within brackets, the three metacharacters you still need to escape are \ - ]. (The hyphen (-) acquires meaning as a range specifier; to use an actual hyphen, you can also place it as the first character inside the brackets.)
A caret (^) has special meaning only when it's the first character inside the brackets, but in this case, the meaning differs from that of the normal
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
ex Commands
:[address]command[options]
Address
Includes
1,$
All lines in the file
x,y
Lines x through y
x;y
Lines x through y, with current line reset to x
0
Top of file
.
Current line
n
Absolute line number n
$
Last line
%
All lines; same as 1,$
x-n
n lines before x
x+n
n lines after x
-[n]
One or n lines previous
+[n]
One or n lines ahead
’x
Line marked with x
’’
Previous mark
/pat/ or ?pat?
Ahead or back to line where pat matches
Symbol
Meaning
!
A variant form of the command
count
Repeat the command count times
file
Filename: % is current file, # is previous file
Full NameCommand
Abbrev
ab [string text]
Append
[address]a[!] text
.
Args
ar
Change
[address] c[!] text
.
Copy
[address] co destination
Delete
[address] d [buffer]
Edit
e [!][+n] [filename]
File
f [filename]
Global
[address]g[!]/pattern/[commands]
Insert
[address]i[!]
text
.
Join
[address]j[!][count]
K (mark)
[address] k char
List
[address] l [count]
Map
map char commands
Mark
[address] ma char
Move
[address] m destination
Next
n[!] [[+command] filelist]
Number
[address] nu [count]
Open
[address] o [/pattern/]
Preserve
pre
Print
[address] p [count] [address] P [count]
Put
[address] pu [char]
Quit
q[!]
Read
[address] r filename
Read
[address] r ! command
Recover
rec [filename]
Rewind
rew[!]
Set
set
set option
set nooption
6set option=value
set option?
Shell
sh
Source
so filename
Substitute
[addr] s [/pat/repl/][opts]
T (to)
[address]t destination
Tag
[address] ta tag
Unabbreviate
una word
Undo
u
Unmap
unm char
V (global exclude)
[address] v/pattern/[commands]
Version
ve
Visual
[address] vi [type] [count]
Visual
vi [+n] [filename]
Write
[address] w[!] [[>>]filename]
Write
[address] w !command
Wq (write + quit)
wq[!]
Xit
x
Yank
[address] y [char] [count]
Z (position line)
[address] z[type] [count]
type can be one of:
+
Place line at the top of the window (default)
-
Place line at bottom of the window
.
Place line in the center of the window
^
Print the previous window
=
Place line in the center of the window and leave the current line at thisline
!
[address] !command
= (line number)
[address] =
<> (shift)
[address] < [count]
[address] > [count]
Address
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Initialization and Recovery
vi performs the following initialization steps:
  1. If the EXINIT environment variable exists, execute the commands it contains. Separate multiple commands by a pipe symbol (|).
  2. If EXINIT doesn't exist, look for the file $HOME/.exrc. If it exists, read and execute it.
  3. If either EXINIT or $HOME/.exrc turns on the exrc option, read and execute the file ./.exrc, if it exists.
  4. Execute search or goto commands given with +/pattern or +n command-line options (POSIX: –c option).
The .exrc files are simple scripts of ex commands; they don't need a leading colon. You can put comments in your scripts by starting a line with a double quote ("). This is recommended.
The commands ex -r or vi -r list any files you can recover. You then use the command:
$ vi -r file
to recover a particular file.
Even without a crash, you can force the system to preserve your buffer by using the command :pre (preserve).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
vi Options
Option
Default
autoindent (ai)
noai
autoprint (ap)
ap
autowrite (aw)
noaw
beautify (bf)
nobf
directory (dir)
/tmp
edcompatible
noedcompatible
errorbells (eb)
errorbells
exrc (ex)
noexrc
hardtabs (ht)
8
ignorecase (ic)
noic
lisp
nolisp
list
nolist
magic
magic
mesg
mesg
novice
nonovice
number (nu)
nonu
open
open
optimize (opt)
noopt
paragraphs (para)
IPLPPPQP LIpplpipbp
prompt
prompt
readonly (ro)
noro
redraw (re)
remap
remap
report
5
scroll
half window
sections (sect)
SHNHH HU
shell (sh)
/bin/sh
shiftwidth (sw)
8
showmatch (sm)
nosm
showmode
noshowmode
slowopen (slow)
tabstop (ts)
8
taglength (tl)
0
tags
tags /usr/lib/tags
tagstack
tagstack
term
(from $TERM)
terse
noterse
timeout (to)
timeout
ttytype
(from $TERM)
warn
warn
window (w)
wrapscan (ws)
ws
wrapmargin (wm)
0
writeany (wa)
nowa
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Enhanced Tags and Tag Stacks
The “Exuberant ctags” program was written by Darren Hiebert (home page: http://home.hiwaay.net/~darren/ctags/). As of this writing, the current version is 2.0.3.
This enhanced tags file format has three tab-separated fields: the tag name (typically an identifier), the source file containing the tag, and where to find the identifier. Extended attributes are placed after a separating ;". Each attribute is separated from the next by a tab character and consists of two colon-separated subfields. The first subfield is a keyword describing the attribute; the second is the actual value.

Section 1.8.1.1: Extended ctags keywords

Keyword
Meaning
kind
The value is a single letter that indicates the lexical type of the tag
file
For static tags, i.e., local to the file
function
For local tags
struct
For fields in a struct
enum
For values in an enum data type
class
For C++ member functions and variables
scope
Intended mostly for C++ class member functions
arity
For functions
If the field doesn't contain a colon, it's assumed to be of type kind.
Within the value part of each attribute, the backslash, tab, carriage return, and newline characters should be encoded as \\, \t, \r, and \n, respectively.

Section 1.8.2.1: Tag commands

Command
Function
ta[g][!] tagstring
Edit the file containing tagstring as defined in the tags file
po[p][!]
Pop the tag stack by one element

Section 1.8.2.2: 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; if tag stacking is enabled, the current location is automatically pushed onto the tag stack
^T
Return to the previous location in the tag stack, i.e., pop off one element

Section 1.8.2.3: 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, tagpath
The value is a list of filenames in which to look for tags; the default value is "tags /usr/lib/tags"
tagstack
When set to true, vi stacks each location on the tag stack
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
nvi—New vi
–c command
Execute command at startup.
–F
Don’t copy the entire file when starting to edit.
–R
Start in read-only mode, setting the readonly option.
–S
Run with the secure option set, disallowing access to external programs.
–s
Enter batch (script) mode. This is only for ex and is intended for running editing scripts. Prompts and nonerror messages are disabled.
Command
Function
bg
Hide the current window
di[splay] b[uffers]
Display all buffers, including named, unnamed, and numeric buffers
di[splay] s[creens]
Display the filenames of all backgrounded windows
Edit filename
Edit filename in a new window
Edit /tmp
Create a new window editing an empty buffer; /tmp is interpreted especially to create a new temporary file
fg filename
Uncover filename into the current window
Fg filename
Uncover filename in a new window; the current window is split
Next
Edit the next file in the argument list in a new window
Previous
Edit the previous file in the argument list in a new window
resize ±nrows
Increase or decrease the size of the current window by nrows rows
Tag tagstring
Edit the file containing tagstring in a new window
The ^W command cycles between windows, top to bottom. The :q and ZZ commands exit the current window.
You may have multiple windows open in the same file. Changes made in one window are reflected in the other.
You use :set extended to enable extended regular expression matching:
|
Indicates alternation. The left and right sides don't need to be single characters.
(…)
Used for grouping, to allow the application of additional regular expression operators.
+
Matches one or more of the preceding regular expressions. This is either a single character or a group of characters enclosed in parentheses.
?
Matches zero or one occurrence of the preceding regular expression.
{…}
Defines an interval expression. Interval expressions describe counted numbers of repetitions. In the following description, n and m represent integer constants:
{n}
Matches exactly n repetitions of the previous regular expression.
{n,}
Matches n or more repetitions of the previous regular expression.
{n,m}
Matches n to m repetitions.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
elvis
–a
Load each file named on the command line to a separate window.
–R
Start editing each file in read-only mode.
–i
Start editing in input mode instead of in command mode.
–s
Set the safer option for the whole session, not just execution of .exrc files. In elvis 2.1, this option is renamed to –S, and (following the POSIX standard) –s provides ex scripting.
–f filename
Use filename for the session file instead of the default name.
–G gui
Use the given interface.
–c command
Execute command at startup (POSIX version of the historic +command syntax).
–V
Output more verbose status information.
–?
Print a summary of the possible options.
Command
Function
sp[lit] [file]
Create a new window; load it with file if supplied; otherwise, the new window shows the current file
new
Create a new empty buffer and then create a new window to show that buffer
sne[w]
sn[ext] [file…]
Create a new window, showing the next file in the argument list
sN[ext]
Create a new window, showing the previous file in the argument list
sre[wind][!]
Create a new window, showing the first file in the argument list; reset the “current” file as the first with respect to the :next command
sl[ast]
Create a new window, showing the last file in the argument list
sta[g][!] tag
Create a new window showing the file where the requested tag is found
sa[ll]
Create a new window for any files named in the argument list that don’t already have a window
wi[ndow] [target]
With no target, list all windows; the possible values for target are described in the following table
close
Close the current window; the buffer that the window was displaying remains intact
wquit
Write the buffer back to the file and close the window; the file is saved whether or not it has been modified
qall
Issue a :q command for each window; buffers without windows are not affected

Section 1.10.2.1: Arguments to the :window command

Argument
Meaning
+
Switch to the next window, like ^W k
++
Switch to the next window, wrapping like ^W ^W
-
Switch to the previous window, like ^W j
--
Switch to the previous window, wrapping
num
Switch to the window whose windowid =num
buffer-name
Switch to the window editing the named buffer
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
vim—vi Improved
–c command
Execute command at startup. (POSIX version of the historic +command)
–R
Start in read-only mode, setting the readonly option.
–s
Enter batch (script) mode. This is only for ex and intended for running editing scripts (POSIX version of the historic “–” argument).
–b
Start in binary mode.
–f
For the GUI version, stay in the foreground.
–g
Start the GUI version of vim, if it has been compiled in.
–o [N]
Open N windows, if given; otherwise open one window per file.
–i viminfo
Read the given viminfo file for initialization, instead of the default viminfo file.
–n
Don't create a swap file: recovery won't be possible.
–q filename
Treat filename as the “quick fix” file.
–u vimrc
Read the given .vimrc file for initialization and skip all other normal initialization steps.
–U gvimrc
Read the given .gvimrc file for GUI initialization and skip all other normal GUI initialization steps.
–Z
Enter restricted mode (same as having a leading r in the name).
Command
Function
[N]sp[lit] [position] [file]
Split the current window in half
[N]new [position] [file]
Create a new window, editing an empty buffer
[N]sv[iew] [position] [file]
Same as :split, but set the readonly option for the buffer
q[uit][!]
Quit the current window (exit if given in the last window)
clo[se][!]
Close the current window; behavior affected by the hidden option
hid[e]
Close the current window, if it's not the last one on the screen
on[ly]
Make this window the only one on the screen
res[ize] [±