vi Command Help Guide

Commands on left (with any corresponding SPF-Edit equivalents), VI commands on right.
VIM-specific commands noted as (VIM: ); NVI-specific commands noted as (NVI: ); ELVIS-specific commands noted as (ELVIS: ).

|| denotes equivalent commands.

For SPF commands, equivalent TSO Edit keystroke commands noted in upper case by [keyname], TSO Edit command line options noted by (=>commandname), TSO Edit line commands noted by (commandname).

© Copyright 1993-2012 Jeff W. You can do whatever you want with this file, just don't claim authorship, don't charge money for it, and don't include emacs commands into it :-)

Note: This file is also available as a plain-text table here

INDEX



Operation

vi/ex Command

Notes

FILE COMMANDS
edit file vi file
edit file at
specific line number
vi + file Begin file edit at last line.
vi +n file Begin file edit at line n .
edit file after
running a command
vi +/pattern file Edit file at first "pattern" occurrence.
vi +":!grep -n pattern %" file Edit file after displaying all occurrences of "pattern" with line numbers.
vi +":g/pattern/p" does the same, but does not list line numbers.
vi +":g/pattern/d" file Edit file after deleting all lines with "pattern" .
edit another file :e file2 || :edit file2
:e +/pattern file2 Edit second file at first line of "pattern" .
split screen
[F2 SPLIT]
:E [files...] NVI
:sp [files...] || :split [files...] VIM
NVI/VIM: Split current window into two equal-sized screens; if "files" are specified, the new screen begins editing these; without file arguments, the current file is edited by both screens. Use Ctrl-W to switch between screens.
swap file edits
[F9 SWAP]
:e# || Ctrl-^ Toggle between two files; # is symbol for the alternate file; % is symbol for current file; when editing more than one file, all currently saved options, maps, buffers, search patterns, and last edit command ( . or Ctrl-@ ) are retained.
edit multiple files vi file1 file2 file3 ... Use :n to go to next file in list or use ':e file' to go directly to named file; for ':e file' , the ':args' still reflects the previous file edited; to return to previous file, use :e# .
vi prog* Edit all filenames beginning with "prog" .
vi `find . -type f -print` Edit all files in current directory and in all subdirectories.
vi `find . -name *.c -print` Edit all files in current directory and in all subdirectories with filename that ends in ".c" .
vi `grep -l "pattern" *` Edit all files in current directory with "pattern" in its contents.
vi `egrep -l "pattern1|pattern2|pattern3" *` Edit all files in current directory with either "pattern1" , "pattern2" , or "pattern3" in contents.
:n || :next Move to next file. If autowrite is set, each file is saved before moving to next file; if autowrite not set, you need to :w first, or use :n! to move to next file without saving changes to current file.
:n file4 file5 Edit new set of files; current file(s) is flushed from edit buffer.
:rew || :rewind Rewind pointer to first file in list. Use :rew! to not save edits made to current file.
:ar || :args Display current set of files being edited.
edit file after
system crash
[=>RECOVER ON]
vi -r List edit files the system saved during crash.
vi -r file Edit buffer file recovered from edit abort.
browse file view file || vi -R file Read-only mode; all vi commands and edits work, but you cannot save any modifications upon exiting, unless you unless you save file with :w! to override the read-only protection.
save file
(=>SAVE)
:w || :write
save and exit
[F3 END]
ZZ || :x || :wq
save part of the file :130,$w file2 Save line 130 to end of file as "file2" .
:'a,'bw file2 Save from line marked label `a' to line marked `b' as "file2" .
:/pattern1/,/pattern2/w! file2 Save from line with "pattern1" to line with "pattern2" to "file2" ; w! overwrites "file2" if it it previously existed.
append current file
to another file
:w >> file2 Append buffer contents to "file2" .
save current file
under different filename
:w file2 Save current file buffer as "file2" ; current file is not saved until you :w it.
:w %.new Save current file as "original_name.new" .
:w new_%.ver3 Save current file as "new_original_name.ver3" .
rename filename without
modifying original file
:f newfilename || :file newfilename Upon exiting, "newfilename" is saved; no change is made to the original file prior to entering :f if you have not saved it yet.
use vi to rename, link,
or delete files
mvi *.dat Edit the names of all files ending in ".dat" ; upon exit from /tmp file created, filenames which were changed are renamed, filenames preceded with "L " are linked, and filenames preceded with "D " are deleted.
[=>CANCEL] edit session;
do not save changes
:q!
undo any changes
made since last save
:e!
CURSOR MOVEMENT
CURSOR MOVEMENT :: MOVE BY CHARACTER
left h || [LeftArrow] || Ctrl-H
right l || [RightArrow] || [space bar]
up k || [UpArrow] || Ctrl-P
down j || [DownArrow] || Ctrl-J || Ctrl-N
input mode [BackSpace] [BackSpace] || Ctrl-H
CURSOR MOVEMENT :: MOVE BY TEXT OBJECT
move to new line [Return] || j || [DownArrow] || Ctrl-M
move forward one word
[Alt][RightArrow]
w || W Move to start of next word.
e || E Move to end of next word.
move backward one word
[Alt][LeftArrow]
b || B Move to start of previous word.
move backward one word
during input mode
Ctrl-W Move backward over newly entered text on current line to type over the words.
move backward to
start of newly entered text
in input mode
Ctrl-U Move backward to start of newly entered text on current line to type over it; if you press [Escape] after this, all new text is deleted.
move to beginning of
next/previous sentence
) Move to start of next sentence. Sentence is delimited by empty line or .?! followed by at least 2 spaces.
( Move to start of previous sentence.
move to beginning of
next/previous paragraph.
} Move to start of next paragraph. Paragraph is delimited by empty line or nroff/troff paragraph macro.
{ Move to start of previous paragraph.
move to beginning of
next/previous section.
]] Move to start of next section. Section is delimited by nroff and troff section macros or each "{" character in a C program.
[[ Move to start of previous section.
CURSOR MOVEMENT :: MOVE BY LINE
move to start of line 0
move to end of line $
move to first
character of line
^ Move to first character on line.
+ Move to first character of next line.
- Move to first character of previous line.
n_ Move to first character (n-1) lines lower.
[Tab] during text input [Tab] Tabs default to 8 spaces; ':set tabstop=n' to set tabs "n" spaces.
Ctrl-I Like [Tab] key during text input mode.
Ctrl-T Like [Tab] when input at start of line.
back up a shiftwidth
of tabs in input mode
Ctrl-D Useful if shiftwidth is set to tabstop ; works only if autoindent is turned on.
disable autoindent
in text input mode
^ Ctrl-D Start edit on column 1 in input mode, resume autoindent on next line.
0 Ctrl-D Start edit on column 1 in input mode, do not resume autoindent until a line is manually indented again.
go to a specific line G || :$ Go to last line.
1G Go to first line.
nG || :n Go to line "n" .
nj || n[DownArrow] Go down "n" lines.
nk || n[UpArrow] Go up "n" lines.
move to top
of current screen
[F12 CURSOR]
H
nH Move cursor to "n" lines below top line.
move to middle line
of current screen
M
move to last line
of current screen
L
nL Move cursor to "n" lines above bottom line.
mark cursor position with
mark to use as line
address for ex commands
(can use to quickly move around)
mx Mark cursor position with label, where `x' is alphabetic character a-z.
`x Move cursor to the character marked by `x' .
'x Move cursor to start of line marked `x' .
`` Return cursor to previous mark or context.
'' Return cursor to start of line of previous mark or context.
CURSOR MOVEMENT :: MOVE BY COLUMN
go to column "n" n| Move to column "n" of current line.
move "n" spaces to right nl || n[RightArrow] || n[space bar]
move "n" spaces to left nh || n[LeftArrow]
CURSOR MOVEMENT :: MOVE BY SCREEN
scroll up one full screen
[F7 UP]
Ctrl-B
nCtrl-B Scroll backward "n" full screenfuls.
scroll up half-screen
[F7 UP] HALF
Ctrl-U
nCtrl-U Set scroll length to "n" lines and scroll up; other Ctrl-U's will also scroll "n" lines.
scroll down one full screen
[F8 DOWN]
Ctrl-F
nCtrl-F Scroll forward "n" full screenfuls.
scroll down half-screen
[F8 DOWN] HALF
Ctrl-D
nCtrl-D Set scroll length to "n" lines and scroll down; other Ctrl-D's will also scroll "n" lines.
scroll 1 line Ctrl-Y Scroll up, retaining the cursor position.
Ctrl-E Scroll down, retaining the cursor position.
scroll screen
[F7 F8] CSR
z [Return] Scroll current line to top of screen.
z. Scroll current line to center of screen.
z- Scroll current line to bottom of screen.
z+ Scroll line to top of next page.
z^ Scroll line to bottom of previous page.
/pattern/z || /pattern/z. || /pattern/z- Search forward for "pattern" and place the next occurrence of "pattern" on the top, center, or bottom of screen.
CURSOR MOVEMENT :: MOVE BY FINDING TEXT
find a pattern
(=>FIND)
/pattern Search forward for "pattern" .
?pattern Search backward for "pattern" .
find a word /\<word\> Search forward for "word" , omitting any string that is an embedded pattern of another word.
?\<[Kk][^ ]*[aeiouAEIOU]\> Search backward for any word that begins with "K" or "k" and ends in a vowel.
repeat find
(rFIND [F5])
n Repeat find in same direction.
N Repeat find in opposite direction.
find pattern only if it occurs after another pattern /pattern1/;/pattern2/;/pattern3/ Find "pattern3" only if it occurs after "pattern1" and "pattern2" ; search fails if either "pattern2" occurs before "pattern1" or "pattern3" is before "pattern1" or "pattern2" .
find nth occurrence
of pattern
I[Esc]ni/pattern[Ctrl-V][Return][Esc]l"xd0@x "n" is number of occurrences to search forward; the key sequence outputs a stream of multiple "/pattern^M" ( ^M is carriage return) that is deleted to buffer "x" and executed by entering @x from wherever the cursor is.
A.[Esc]na?pattern[Ctrl-V][Return][Esc]F.x"xd$@x Same as above command except it searches for nth occurrence backwards.
find character on
current line
fc Search forward for character "c".
nfc Search forward for nth occurrence of "c" .
Fc Search backward for character "c" .
nFc Search backard for "n"th occurrence of "c" .
tc Search forward for the character before "c" .
Tc Search backward for the character after "c" .
repeat character find ; Repeat find in same direction as last find.
, Repeat find in the opposite direction.
find matching bracket
in program code
% If cursor is placed on open bracket (, [, {, press % to move cursor to matching closing bracket of ), ], } ; the reverse also works.
display lines
having pattern
:g/pattern/p Display all lines having "pattern" .
:g!/pattern/nu || :v/pattern/nu Display all lines not having "pattern" along with their line numbers.
:v/^[A-Za-z0-9]/p Display all lines not starting with alphanumerics.
LINE COMMANDS
LINE COMMANDS :: EDIT MODIFIERS
repeat last edit/insert command
[RETRIEVE]
. Repeat last modification command issued; command may be o/O, d, c, i, a, etc...
4. Repeat last modification command 4 times>
Ctrl-@ In input mode, repeat the text that was last inserted if input as the first character of the new insertion; returns to command mode. Only 128 characters are saved from previous insert; will not work if >128 characters were last input.
undo previous change
(=>UNDO)
u Undo last change made.
U Undo all changes made to a line; cursor must not have moved off of that line.
:e! Undo all changes to file since last save.
[reset] [Escape] key In input mode, return from input mode to command mode. In command mode, cancel a partially formed command, such as "z", "c", or "d" , when no followup character has been given.
screen refresh
[Dup PA1]
Ctrl-L || Ctrl-R Refresh the screen; useful if mail message changes screen during edit session.
LINE COMMANDS :: INSERT TEXT
insert text
[Insert]
i Insert text before cursor.
ni Duplicate "n" copies of what is inserted.
a Append text after cursor.
na Duplicate "n" copies of what is appended.
insert at start of line I Insert text at beginning of line.
insert at end of line A Append text at ending of line.
insert new line
(I)
o Open a new line below the current line.
O Open a new line above the current line.
text split
(TS)
i [Return] [Escape]
insert non-printing control characters Ctrl-V Quote the next non-printing character. Quoting a newline [Return] prints out ^M , [Escape] prints ^[ . To quote Ctrl-V itself, press Ctrl-V twice for ^V .
return to command mode Esc [F11] || Ctrl-[
LINE COMMANDS :: CHANGE TEXT
replace text
[overlay]
R Type over existing text starting at cursor.
nR Insert "n" copies of text that is input.
replace a character r Replace the character the cursor is on; this command leaves you in command mode.
nr Overlay "n" copies of replacement character.
change a word cw Change a word starting at cursor.
ncw Change "n" words starting at cursor.
change to end of line C Change text from cursor to end of line.
change to start of line c0 Change text from cursor to start of line.
change to sentence end c) c( changes to start of sentence.
change range of columns cn| Change from cursor to column "n" .
change to character cf? Change from cursor to next "?" on line.
change to text pattern c/pattern Change text from cursor to next occurrence of "pattern" .
c?pattern Change text from cursor to previous occurrence of "pattern" .
change a line cc Blank out current line and go into input mode.
S Same as cc , but does not blank out current line.
ncc Change "n" consecutive lines.
change to end of file cG Change from current line to end of file.
change to start of file c1G Change from current line to first line.
substitute a character s Replace a character with new text.
ns Replace "n" characters with new text.
change txt1 txt2
(=>CHANGE txt1 txt2)
:s/txt1/txt2/ Change first "txt1" on line to "txt2" .
:s/txt1/txt2/g Change all "txt1" on line to "txt2" .
:6,15s/txt1/txt2/ Change first "txt1" to "txt2" on lines 6 to 15.
:%s/pattern1.*pattern2/txt/g Change pattern of text that begins with "pattern1" and ends with "pattern2" to "txt" .
repeat change
(rCHANGE [F6])
n & n moves cursor to next occurrence of text; & changes next occurrence of text.
:&g Repeat last ex substitution command on current line.
:%&g Repeat last ex substitution command for all lines in file.
change all txt1 txt2
(=>CHANGE ALL)
:%s/txt1/txt2/g Change all "txt1" in file to "txt2" .
:%s/txt1/txt2/gc Confirm each change by entering "y" at ^^^ prompt; enter "n" or just press [Return] to negate; Ctrl-C cancels further changes.
:g/pattern/s/old/new/g Globally change all "old" to "new" only on lines where "pattern" occurs.
:g!/pattern/s/old/new/g || :v/pattern/s/old/new/g Globally change all "old" to "new" only on lines where "pattern" does not occur.
regular expressions
for search patterns
(wildcard characters)
. Match any single character except newline.
* Match zero or more of preceding character.
.* Match any number of any characters.
^txt Match "txt" only at start of line.
txt$ Match "txt" only at end of line.
\ Escape the meaning of the special command character that follows, such as . * ^ $ / \ ~ .
[ ] Match any character enclosed in the brackets; e.g., [A9] matches A or 9, [A-Z] matches A to Z, [;:0-9&] matches ; : & and numbers 0-9, ^[aeiou] matches any lowercase vowel at start of line, [^aeiou] matches any character that is not a vowel; to match \ - or ] within brackets, escape their meaning by specifying \\ \- or \]
\( \) Save pattern inside \( \) in 1 of 9 buffers;
recall buffer in replacement text using \n
:%s/\([0-9.]*\) *\([0-9.]*\)/\2 \1/ transposes two fields in a numeric file having only numbers and decimals.
\< Match characters at start of word; e.g., \<un matches words starting with "un".
\> Match characters at end of word; e.g., \>es matches words ending with "es".
~ Match whatever was last used as search pattern. If last search was on "XGrabKey", /~board will will search for "XGrabKeyboard"; does not work as a pattern in substitute command, may not work on some vi's.
regular expressions
for replacement patterns (wildcard characters)
\ Escape the meaning of the special command character that follows such as . or *.
\n where "n" is 0 to 9, replace \n with corresponding \( \) delimited search pattern; see \( \) above.
& Replace & with whatever was used as search pattern;
e.g., :%s/In/& fact/g will replace all "In" with "In fact".
\u \U \u changes next character in replacement to be uppercase; \U changes all characters after it in replacement string to uppercase unless separated by \e or \E .
\l \L \l changes next character in replacement to be lowercase; \L changes all characters after it in replacement string to lowercase unless separated by \e or \E .
~ Replace search pattern with whatever was last used as replacement pattern. If :s/He is/He was/ was substituted on a line, the next substitution command of :s/She saw/~/ changes "She saw" also to "She was".
change case of letter ~ Toggles between upper and lower case.
invert case of word ywmno[Esc]P:s/[^ ]/\~/g[Return]0"nDdd`n@n ywmno yanks word, marking it as `n' ;
P:s/[^ ]/\~/g puts word on next line and converts to lowercase;
0"nDdd deletes tilde'd characters to buffer "n" ;
`n@n moves back to original word and executes buffer "n" .
This command changes "AbC" to "aBc". To include punctuation, use yWmno so "Ab.C" changes to "aB.c".
invert case of line !!tr '[a-z][A-Z]' '[A-Z][a-z]'
:s/\([a-z]*\)\([A-Z]*\)/\U\1\L\2/g
change to uppercase
(=>UPCASE ALL)
:%s/.*/\U&/ Change entire file to uppercase.
:/do:/,/end:go/s/.*/\U&/ Change all text between first occurrence of line having "do:" to next line having pattern "end:go" to uppercase.
:?^$?,'bs/other/\u&/g Change all occurrences of "other" from previous empty line to line marked `b' to "Other".
change to lowercase
(=>LOWCASE ALL)
:%s/.*/\L&/ Change entire file to lowercase.
:3,8s/IN EXAMPLE/\L&\e NUMBER/g Change all "IN EXAMPLE" patterns in lines 3 to 8 to "in example NUMBER"
:,'bs/Ex/\l&/g Change all occurrences of "Ex" from current line to line marked `b' to "ex".
LINE COMMANDS :: DELETE/MOVE TEXT
delete a character
[delete]
x Delete character at cursor.
X Delete character before cursor.
nx Delete "n" characters after cursor.
nX Delete "n" characters before cursor.
delete word
[Alt][delete]
dw Delete a word starting at cursor.
ndw Delete "n" words starting at cursor.
delete to end of line D Delete from cursor to end of line.
delete to start of line d0 Delete from cursor to start of line.
delete to end of sentence d) d( deletes to start of sentence.
delete range of columns dn| Delete from cursor to column "n" .
delete line
(D)
dd Delete current line.
delete n lines
(DD)
ndd Delete "n" consecutive lines; e.g., 4dd is same as D4 in SPF Edit.
d'a delete from current line to line marked `a' .
:/-/d Delete next line with a "-" in it.
delete to end of file dG Delete from current line to end of file.
delete to start of file d1G Delete from current line to first line.
delete to character df? Delete from cursor to next "?" on current line.
delete to text pattern d/pattern Delete text from cursor to next "pattern" .
d?pattern Delete text from cursor to previous "pattern" .
:%s/pattern1.*pattern2//g Delete pattern of text that begins with "pattern1" and ends with "pattern2" .
delete block of text ma mb `ad`b To delete an arbitrary text block (instead of complete lines), mark start of text with label `a' and mark the character AFTER the last character to delete with `b' ; `ad`b deletes marked text block).
move line
(M)
dd
(p || P)
dd deletes line; p or P puts deleted line below or above cursor. Unless you delete to named buffer, you must use p/P to put text back to another spot before doing another dd or yy move/copy.
:m$ Move current line to end of file.
block move n lines
(MM)
ndd
(p || P)
ndd deletes "n" lines; p pastes deleted lines below cursor, P pastes the text above cursor; e.g. 4dd p is the same as M4 in SPF Edit.
:'a,'bm. Move from line marked "a" to line marked "b" after current line.
delete to named buffer "andd "a is one of 26 buffers named a-z; "n" is number of lines to delete, default of 1 line.
"Andd Delete "n" lines, append it to buffer "a" content.
delete text block to named buffer ma mb `a"cd`b To delete an arbitrary text block (instead of entire lines) to named buffer, mark start of text with label `a' and mark character AFTER the last character to delete with `b' ; `a"cd`b deletes the marked text block to buffer "c" .
paste deleted text from named buffer "ap || "aP Paste buffer "a" contents after or before current line.
paste from delete buffer
(restore deleted text)
"np || "nP "n" is buffer number 1-9 storing past 9 deletions; last delete is saved in buffer 1; only works for deleted lines, not deleted strings of text.
"1pu.u.u.u.u.u.u.u.u Step through the contents of all 9 delete buffers. Useful if you accidentally deleted text recently that you want to get back; "u" undoes each delete buffer restoration; "." puts contents of another delete buffer below current line.
transpose two character xp Swap character with following character.
transpose two words dwwP Swap word starting at cursor with next word.
transpose two lines ddp Swap position of current line with next word.
delete lines having pattern :g/pattern/d Delete all lines in file with "pattern" .
:g!/pattern/d || :v/pattern/d Delete all lines in file without "pattern" .
:/pattern1/,/pattern2/d Delete from first line having "pattern1" to next line having "pattern2" .
d/pattern1/;/pattern2/ Delete from first line having "pattern1" up to (but not including) next line having "pattern2" .
:g/pattern/-3,-1d|+1,+2d For all occurrences of "pattern" , delete 3 lines above and 2 lines below it; if "pattern" at top or bottom of file, use :4,$-2g/pattern/-3,-1d|+1,+2d instead; to also display lines having occurrences of "pattern", use :4,$-2g/pattern/-3,-1d|p|+1,+2d.
move lines having a pattern :g/pattern/mo$ Move all lines with "pattern" to end of file.
delete columns of text
(=>C ALL P'=' '' f l)
:%!colrm f l Delete all text in columns "f" through "l".
:'a,.!colrm f l Delete all text in columns "f" to "l" from line marked `a' to current line.
:2,10!colrm 1 4 Delete all text in columns 1 to 4 for lines 2 to 10; this can be use to shift text to the left.
blank out text columns
(=>C ALL P'=' ' ' f l)
:.,$!column f l From current line to end of file, blank out columns "f" to "l" with spaces.
:'a,'b!column 20 From line marked `a' to line `b' , fill columns 20 to end of line with blank spaces.
:%!column 34 55 - For all lines in file, fill columns 34 to 55 with character "-".
overlay text onto
other lines of text
(C OO)
:.!yo
(:16,26!po)
Yank current line of text to buffer and overlay it onto lines 16 through 26.
:'a,'b!yo
(:'c,'d!po)
Yank lines marked `a' through `b' and overlay them on block of lines marked `c' and `d' .
!!yo
(:'a,.!po || !'a po)
Overlay line of yo-yanked text onto lines starting from line marked `a' to current line.
LINE COMMANDS :: COPY TEXT
copy file
(=>COPY file)
:r file || :read file Copy contents of "file" after current line.
:r !sed -n 50,75p file Copy lines 50 to 75 of "file" after current line; equivalent command using awk is :r !awk 'NR >= 50 && NR <= 75' file .
:r !sed -n "/pattern1/,/pattern2/p" file Copy after current line all text in "file" that is between an occurrence of "pattern1" and occurrence of "pattern2" .
copy a file after all pattern occurrences :g/pattern/r file A copy of "file" is placed after every "pattern" .
copy a command output after every pattern :g/pattern/r !Unixcommand "Unixcommand" output is placed after every "pattern" .
copy a command output into current file :r !Unixcommand Copy "Unixcommand" output after current line.
copy n numbers of words nyw
(p || P)
Copy "n" number of words starting at cursor and put after or before cursor.
copy to end of line y$
(p || P)
Copy text from cursor to end of line and put below or above cursor.
copy to start of line y0
(p || P)
Copy text from cursor to start of line and put below or above cursor.
copy to end of sentence c)
(p || P)
y( copies to start of sentence.
copy a range of columns yn|
(p || P)
Copy from cursor to column "n" and put after or before cursor.
copy a line
(C)
yy
(p || P)
yy yanks line; p or P puts yanked line below or above cursor; unless you yank to named buffer, you must use p/P to put the text back to another spot before doing another dd or yy move/copy.
block copy
n lines
(CC)
nyy
(p || P)
Yank "n" consecutive lines; p or P pastes yanked lines; e.g., 4yy is same as C4 in SPF Edit.
y'a (p || P) Yank from current line to line marked `a' ; p or P pastes the yanked text.
:'a,'by
(p || P)
Yank from line marked `a' to line `b' .
:'a,'bco. Copy from line marked `a' to line marked `b' after current line.
copy a text block ma mb `ay`b
(p || P)
To yank an arbitrary text block (instead of complete lines), mark start of text with label `a' and mark the character AFTER the last character to to yank with label `b' ; `ay`b yanks marked text block; p or P pastes it back.
repeat a line
(R)
yy
(p || P)
Yank line, paste back below or above current line.
repeat line n times
(Rn)
:1,ng/^/'aco'a To repeat line "n" times, either yy yank and then use p "n" number of times, or mark the line as `a' and :1,ng/^/'aco'a will duplicate "n" copies of that line; e.g., :1,34g/^/'aco'a will add 34 more copies of line marked `a' ; "n" must be no greater than the number of lines in the file.
repeat text block
(RR)
:'a,'bco'b Repeat the text block marked `a' on first line and `b' on last line; the repeated block is placed beneath original text block.
repeat text block "n" times
(RRn)
:1,ng/^/'a,'bco'b Repeat the text block marked `a' on first line and `b' on last line "n" number of times; "n" copies of repeated text block will be appended below original text block; "n" should be no greater than the number of lines in the file.
yank to buffer
(copy to named buffer)
"anyy "a is one of 26 buffers named a-z; "n" is number of lines to yank, default of 1 line.
"Anyy Yank "n" lines, append it to buffer "a contents.
yank a text block to named buffer ma mb `a"cy`b To yank an arbitrary text block (instead of whole lines) to named buffer, mark start of text with label `a' and mark character AFTER the last character to yank with label `b' ; `a"cy`b yanks marked text block to buffer "c" .
paste yanked text from named buffer "ap || "aP Put contents of buffer `a' after or before current line.
yank lines having pattern :g/pattern/y a Yank all lines having "pattern" and store in buffer "a" .
:g/pattern/y A Yank all lines having "pattern" and append to buffer "a" .
store often-used ex command into buffer and execute buffer whenever the command is needed "add @a || "ayy @a "add deletes line containing a vi or ex command sequence and stores it in buffer "a" (or a-z); @a executes stored command in command mode; can restore delete buffer with "ap if command needs changing. When using "ayy , enter command on last line and use 1,$-1 as line address to avoid running the command on itself; @ buffer commands may not be more than 512 characters long.
:*a Equivalent ex execution of buffer "a" .
repeat last @ command @@
LINE COMMANDS :: REFORMAT TEXT
concatenate text lines J Join next line to end of current line.
nJ Join "n" consecutive lines into one line.
:j n || :join n Join "n" consecutive lines into one line.
:j! n || :join! n Like :j , but whitespace is not eliminated.
text flow
(TFnn)
!a}fmt -nn "a" is number of paragraphs to format; "nn" is maximum allowed line length; format only a few paragraphs at a time.
justify and
block text
:%!format -b -w72 Format all lines both left and right justified and 72-columns wide.
:'a,'b!format -i4 -w68 -l Format text between lines `a' and `b' to be 68-columns wide, indented 4 spaces (for right margin of 72 columns), and left justified.
:1,7!format -c -w80 Format lines 1 to 7 so they are centered within 80-column wide lines.
:%!perl -pe 'print " " x int((81-length())/2)' Center all lines down the middle between columns 1 and 80.
:,8!perl -pe 'print " " x int((73-length())/2)' Center from current line to line 8 down the middle between columns 1 and 72.
shift lines left/right
( )
<< || >> Each shift is 8 spaces. Use :set shiftwidth=n to shift line n spaces.
. Repeat previous shift.
block shift n lines
(( ))
n<< || n>> Shift "n" consecutive lines.
. Repeat previous shift.
>'a Shift current line to line marked `a' to the right.
:8,12s/^/   /g Shift lines 8 to 12 left 3 spaces.
insert empty line between every line :%s/$/Ctrl-V[Return]/ Ctrl-V/[Return] generates "^M" on substitution.
split text up so a new line is made at every occurrence of pattern :%s/Example:/Example:Ctrl-V[Return]/g Ctrl-V/[Return] generates "^M" on substitution. Text is split after all occurrences of "Example:".
split text up so each line has only one left-justified word :%s/[ ^I][ ^I]*/Ctrl-V[Return]/g For all lines, substitute any tabs or blanks for newline breaks. If no tabs exist, you can use:
Q :%s/  */Ctrl-V[Return]/g
" ^I" is one [Space] followed by one [Tab].
delete leading spaces in front of every line :%s/^ *\(.*\)/\1/ || :%s/^[ ^I]*// ^ * searches for one or more spaces at start of line; \(.*\)/\1 restores rest of line without any leading spaces; can use this to prepare text for embedding of nroff-troff commands. "^I" is a Tab.
delete spaces and tabs at ends of lines and on blank lines :%s/[ ^I]*$// Remove blanks or tabs at ends of all lines. Blank lines with invisible blanks or tabs also trimmed. " ^I" is one [Space] followed by one [Tab].
delete all
blank lines
:g/^$/d || :v/./d Delete all blank lines which are empty.
:g/^[ ^I]*$/d Delete all blank or white-space-only lines. " ^I" is one [Space] followed by one [Tab].
change multiple blank lines to single blank lines :v/./.,/./-1join
:%s/[ ^I]*$//
:%!cat -s
Substitution first compresses blank lines having spaces to empty lines; !cat command then squeezes out all multiple blank lines. " ^I" is one [Space] followed by one [Tab].
convert single text column into 4 columns !}pr -4t If needed, use !}expand -8 to align columns.
switch columns
of data in a
column-oriented table
:'a,'b!awk '{print $2" "$1" "$3" "$5" "$4}' From lines marked `a' to `b' , move 2nd field to 1st column of so that 1st field is now 2nd filed, and swap the 4th and 5th fields; assumes 5 fields, each separated by 2 blanks.
:%!awk '{printf "\%10s\%10s\%20s\n", $3, $2, $1}' For all lines containing 3 fields separated by blanks, reverse the order of entries, printing in order 3rd, 2nd, and 1st fields right-justified in formatted columns of 10, 10, and 20 spaces wide.
:%s/\(...\)\(.......\)\(....\)\(.....\)/\4\3\2\1/ For all lines in file with four columns of data 3, 7, 4, and 5 columns wide, rearrange the columns such that 4th and 1st columns are swapped and 2nd and 3rd columns are swapped; unlike awk examples above, this swaps exact columns (with spaces).
reverse order
of lines in file
:g/^/mo0
sort the lines in file :%!sort Sort file in ascending order.
:%!sort -r Sort file in descending order.
:'a,'b!sort +2 Sort 3rd field between the lines marked `a'/`b' .
:%!perl -00 -e 'print sort <>' Sort entire file by paragraphs.
add line numbers to start of each line :%!nl || :%!cat -n Inserts line numbers in columns 1-6 followed by a tab character. Remove numbers using :%!colrm 1 7 .
:%!pr -t -n Inserts line numbers in columns 1-5 followed by a tab character; remove numbers with :%!colrm 1 6 .
add line numbers to end of each line 1G
!Gawk '{printf "\%s\%8d\n", $0, NR}'
1G first moves to start of file; awk adds line numbers to end of each line; if spacing of numbers is not okay, "u" undo, and execute command again using some spacing other than "%8".
transpose matrix of values :%!transpose Transpose entire file contents (matrix of values); 8x5 matrix becomes 5x8 matrix.
translate characters to other characters :%!tr "[A-Z][a-z]" "[N-Z][A-M][n-z][a-m]" Encrypts all lines to ROT13 format.
:%!tr "[N-Z][A-M][n-z][a-m]" "[A-Z][a-z]" Translates all lines with ROT13 encryption.
tr '\015' '\012' < file > file1 Translate all carriage returns to line feeds; useful if "file" is too long for vi to accept as a single line; run in Unix and output to "file1" .
regularize spacing and case of sentences :%s/\([.?!]\) *\([a-zA-Z0-9]\)/\1 \U\2/g Change any . ? ! punctuation followed by at least one space followed by an alphanumeric character to uniform two spaces between sentences, capitalizing any lowercase letter that begins a sentence; this, however, will not capitalize letters at the start of a line that should be capitalized.
:%s/\([^.?!]\) *\([^.?!]\)/\1 \2/g Change spacing between any character that is not a . ? ! punctuation and any non[.?!] character to a uniform one space separation.
run spelling checker on the file :w
:$r !spell %
Save file first. Append mispelled words at bottom.
draw a ruler
(COLS)
map _
o^[i----+----1----+----2----+----3----+----4----+----5----+----6----+----7-^V|--+----8^[0
Place this in your .exrc file to draw an SPF-EDIT COLS-styled ruler below the current line when you press "_" in command mode; "^[" is Escape character and "^V" is made by entering Ctrl-V twice.
exclude text block from current file
(XX)
:'a,'b!exclude
(!!exclude)
Exclude from line marked label `a' to line marked `b' and then enter !!exclude on the folded text to expand it back out again. Warning: text must be expanded prior to exiting current edit session.
EX COMMANDS
quit vi, invoke ex Q
quit ex, return to vi :vi
cancel current partial ex/search command Ctrl-U [Backspace]
display line number :.=
display total number of lines in the file :=
:/pattern/= Show line number of first line with "pattern" .
display lines with their line numbers :number || :nu || :#
(address)number(count)
Display current line with line number. If preceded with address or followed by count, displays range of lines and their numbers.
display lines showing tabs and end-of-lines :list || :l
(address)list(count)
Display current line with tabs shown as "^I" and end-of-lines marked "$" . If preceded with address or followed by count, displays range of lines.
display filename, line number, total lines Ctrl-G || :f
run command
(=>TSO COMMAND)
:!Unixcommand Special characters used in "Unixcommand" may need to be preceded with "\" to escape the normal shell meaning, including...
! & | % + - * ? / ^ > < ( ) && || << >> # ; $
:!! Execute most recent shell escape command.
:!! arguments Repeat last shell command, appending supplied "arguments" to command.
filter text through Unix command as standard input, replacing the text with command's standard output :.!UnixCommand Filter current line through "Unixcommand" . The line addresses given are replaced by standard output of "Unixcommand" .
!!UnixCommand Filter current line through "Unixcommand" and replace with it with command output. May want to open up a new line first to insert command output.
n!!UnixCommand Filter "n" consecutive lines starting with current line through "Unixcommand" . The "n" lines are replaced with command output.
!!!UnixCommand Filter current line through the last "Unixcommand" used and replace with command output.
!}UnixCommand Filter paragraph of text through "Unixcommand" . The general form is:
!(times)(textblock)
where "times" is number of "textblocks" to process, "textblock" is {} () [[ ]] + - G `"label", '"label", H, M, L
:'a,'b!Unixcommand1 | Unixcommand2 | Unixcommand3 Filter text block from line marked `a' to `b' through three different Unix commands. Text block is replaced with output from "Unixcommand3" .
:map key 1G/pattern!/pattern/command Recursively map "key" to filter all occurrences of "pattern" in file through "Unixcommand" .
send file contents to standard input of Unix command :w ! Unixcommand Can input file contents to script or C program.
define a string as an abbreviation to be translated to other text :ab string replace_text Abbreviate "replace_text" as "string" ; "string" changes to "replace_text" after a non-alphanumeric character is entered unless character is quoted with Ctrl-V ; [Return] or [Escape] will trigger the conversion; "replace_text" cannot end as "string" ; i.e. abbreviation cannot be recursive.
:una string Cancel "string" as an abbreviated text string.
change working directory :cd directory || :chdir directory || :chd directory Change current working directory that vi writes to using :w or read from using :e ; if no directory argument is specified, new directory is $HOME.
copy lines
using ex
:co || :copy || :t
(address)co(destination)

:.,.+4co28 Copy current line to 4th line below current line after line 28.
:'a+2,$-4t. Copy 2nd line after line marked as `a' through 4th line before last line in file after current line.
:%co$ Copy entire buffer file after last line of file; same as Unix "cat file >> file".
delete lines
using ex
:d || :delete
(address)d(bufferletter)

:d b 4 Delete 4 consecutive lines, store in buffer "b" .
:'a,'bd Delete all lines between the line marked `a' to line marked `b' .
:%d Delete all lines in file.
:g/^/+d Delete every other line in a file.
display saved buffers :display buffers || :di b NVI: display all buffers (named/unnamed/numeric).
display all background screens :display screens || :di s NVI: display filenames of all background screens.
display the tags stack :display tags || :di t NVI: display the tags stack.
display ex help info :exusage [ex command] || :exu [ex command] NVI: display usage info for a ex command, if given as argument; otherwise, display all ex usage info.
display vi help info :viusage [vi command] || :viu [vi command] NVI: display usage info for a vi command, if given as argument; otherwise, display all vi usage info.
display short help line :help || :he NVI/VIM: display brief help message.
map a key to commands to be executed in command mode :map [k] command Map key [k] to commands in command mode; "command" cannot use "k" in its definition and cannot be more than 100 characters.
:unmap [k] || :unm [k] Cancel key [k] that was previously mapped.
map a key to commands to be executed in input mode :map! [k] replacementcommand Map key [k] to commands in input mode; "command" cannot use "k" in its definition and cannot be more than 100 characters; do not make input-mode keymaps recursive.
:unmap! [k] || :unm [k] Cancel key [k] that was previously mapped.
mark current line with a letter label :ma x || :mark x || :k x Assign marker `x' (single lowercase letter) to a line to use as command address; go to this line using `x or 'x .
move lines
using ex
:m || :move
(address)m(destination)
Same as copy with delete or delete with put.
:m 'a Move current line to line marked `a' .
:2 m 15 Move line 2 to below line 15.
:.,.+4m0 Move current line through 4th line after current line to top of file.
create exrc file from currently set maps, abbreviations, and options :mkexrc exrc_file || :mk exrc_file NVI: write all current maps, abbreviations, and options to "exrc_file" in form source'able by ex; if "exrc_file" exists, mkexrc will fail unless "!" is appended to command to override.
preserve current buffer in case of write error :pre || :preserve Use "vi -r filename" to recover later on.
edit previous file from argument list :prev || :previous NVI: edit previous file from argument list.
display lines using ex :p || :P || :print
(address)p(count)

restore previously deleted or yanked text :pu || :put
(address)pu(buffername)
If (buffername) is deleted, the last deleted or yanked text is restored.
recover file from system save area after aborted edit session :rec || :recover Use after system crash or after using :pre; equivalent to starting vi with "vi -r file" .
create a new shell
from vi
:!sh || :!csh || :!ksh
exit || Ctrl-D To quit shell and resume editing current file.
exit from vi to current shell Ctrl-Z || :stop || :st || :suspend || :su
(fg)
Temporarily suspend vi and return to Unix prompt of current shell; enter `fg` at prompt to resume vi; if autowrite set and file was changed, a file save is done unless :stop! or :suspend! is used.
execute ex commands stored in file Q :so filename || Q :source filename Enter :vi to return to vi mode; may be used to initiate additional maps stored in a file.
background current split screen :bg NVI: background current screen; it is replaced by neighboring screen; cannot background your only screen in the window.
foreground a screen that was backgrounded :fg [file] NVI: foreground the first screen in the list of backgrounded screens; with a file argument, the requested file screen replaces the current screen, which is in turn backgrounded.
resize split screens :resize +/-size || :res +/-size NVI: resize split screens by increasing/decreasing number of rows when using "+/-" (e.g. :res +10 increases current screen by 10 lines) or setting absolute number of rows (e.g. :res 30 sets current screen to 30 lines, if window is large enough).
create a ctags file for use later by vi ctags prog* Create a file "tag" in current directory with pointers to segments of code in all programs whose names start with "prog" .
ctags *.c *.h ~/lib/*.h Create file "tag" with pointers to all program segments in all C and header files in current directory along with all header files in "lib" .
edit tagged program segment (very quick way to hop around in up to three different segments of code that may be in other files or even other directories) :ta Segmentnametag || :tag Segmentnametag Ctags must have been run to make tags file.
:vi -tSegmentname Start vi in file with the tagged code segment.
Ctrl-] If cursor is placed on first character of a tagged program function name, pressing Ctrl-] will open up the file containing that tagged code segment. :rew returns to original place you were editing prior to Ctrl-]
If you use Ctrl-] on a function name from the file that the first Ctrl-] placed you in, you may be placed into yet a third file. Ctrl-^ will toggle back and forth between this file and the one opened by the first Ctrl-] ; :rew will return you back to original edit spot.
undo all changes made by last editing command :u || :undo Equivalent to vi "u" undo command.
print vi program version :ver || :version
yank lines using ex :ya || :yank || :y
(address)ya(bufferletter)

:y a 4 Yank 4 consecutive lines, store in buffer "a" .
:12,19 y Yank lines 12-19 to general buffer.
shift lines left/right in ex :(address)<(count) || :(address)>(count)
:> Shift current line one shiftwidth to right.
:<8 Shift 8 consecutive lines one shiftwidth to the left.
line address of ex commands none Execute ex command on current line only.
$ Last line in file.
. Current line in file.
- Line above current line of cursor.
--- Three lines above current line of cursor.
+ Line below current line of cursor.
++ Two lines below current line of cursor.
n "n"th line in file.
% All lines in file; same as 1,$ .
g Global or all lines in file; same as % .
.-n "n"th line before the current line.
.+n "n"th line after the current line.
'a Line previously marked as `a' .
'' Line of previous context where cursor was.
/pattern/ First line in forward search direction having "pattern" .
?pattern? First line in backward search direction having "pattern" .
a,b All lines from line `a' to line `b' .
'a,'b All lines from line marked `a' to line marked `b' ; label `b' must not precede label `a' .
a+n,a-n "n" lines after or before `a' where `a' is any address described above; second address must not precede first address.


VI OPTION SETTINGS

All toggle flag options can be disabled by adding prefix 'no' to option name Options may also be specified using the abbreviations shown in brackets.

:set
Display only options changed from default setting.

:set all
Display all current option settings.

:set option
Set specified "option".

:set option?
Display set value of specified "option".

:set altwerase
NVI: Change how words are erased during input. Text is broken into classes: alphanumerics and underscore, other nonblank characters, and blank characters.
Def: noaltwerase.

:set autoindent (ai)
Good for programming; indent next line same distance distance as previous line; Ctrl-T or Ctrl-D (input mode) add or remove indent levels based on tabstop setting.
Def: noai.

:set autoprint (ap)
Display changes after each editor command.
Def: ap.

:set autowrite (aw)
Automatically write file if changed before opening another file with :n or before giving Unix command with :! . Useful when editing two or more files simultaneously.
Def: noaw.

:set beautify (bf)
Ignore control characters during input (except tabs, newlines, and formfeeds).
Def: nobf.

:set cdpath=":"
NVI: Specify colon-separated list of directories used as path prefixes for relative pathnames used in the ':cd' command.
Def: CDPATH variable if set, or current directory. To reference current directory, use either empty string or "." in CDPATH variable.

:set columns=?? (co)
NVI: Number of columns in screen; setting causes ex/vi to reset COLUMNS variable.
Def: co=80.

:set comment
NVI: If first non-empty line of file begins with "/*" , nvi skips to end of that C comment block before displaying file.
Def: nocomment.

:set directory=? (dir)
Store buffer files in specified directory.
Def: /tmp.

:set digraph
NVI

:set edcompatible
Use ed-like features on substitute commands.
Def: noedcompatible.

:set errorbells (eb)
| Sound bell when error occurs. Def: errorbells.

:set exrc (ex)
NVI: If 'noexrc' is set in the system or $HOME .*exrc files, local .*exrc files are never read (unless they are the same as the system or $HOME .*exrc files). Turning 'exrc' on has no effect; the normal local .*exrc files checks are done.
Def: noexrc

:set extended
NVI: Regular expressions are extended (i.e. egrep) format.
Def: noextended.

:set flash
NVI: Flash screen instead of beep keyboard on error.
Def: flash.

:set hardtabs=? (ht)
Define boundaries for terminal hardware tabs.
Def: ht=8.

:set ignorecase (ic)
Disregard case of characters in searches.
Def: noic.

:set keytime=?
NVI: 10th's of a second ex/vi waits for full keymap sequence.
Def: keytime=6.

:set leftright
NVI: Scroll screen left-right for long lines instead of folding lines at right margin.
Def: noleftright.

:set lines=? (li)
NVI: Number of lines in screen. Setting this causes ex/vi to reset LINES variable.
Def: li=24.

:set lisp
Insert indents in appropriate lisp format.
Def: nolisp

:set list
Display tabs as ^I and ends of lines as $ .
Def: nolist

:set magic
Wildcard characters . * [] ~ have special meaning when used in patterns.
Def: magic.

:set matchtime=?
NVI: 10th's of a second ex/vi pauses on matching character when showmatch set.
Def: matchtime=7.

:set mesg
Permit system messages to display on terminal while editing, which may disrupt display; use Ctrl-L to restore screen display.
Def: mesg.

:set modeline
After vi reads EXINIT variable and .exrc file, first and last 5 lines of edit file are read for extra ex commands; embedded commands must begin with "ex:" or "vi:" and must be valid ex editor commands; separate multiple commands with "|" ; each line must be terminated with :
Def: nomodeline.

:set number (nu)
Display line numbers left of screen.
Def: nonu.

:set octal
NVI: Display unknown characters as octal numbers, instead of default hexidecimal.
Def: nooctal.

:set open
Allow entry to open or visual mode from ex.
Def: open.

:set optimize (opt)
Abolish carriage returns at end of lines when printing many lines; speeds output on dumb terminals when displaying lines with leading white spaces (blanks or tabs).
Def: noopt.

:set paragraphs=??? (para)
Define paragraph delimiters for movement by {} . Pair of characters used in value are nroff/troff macros that begin paragraphs.

:set prompt
Display ex prompt (:) when vi Q command given.
Def: prompt.

:set readonly (ro)
Any file writes will fail unless ! is used after the write (using w, ZZ, or autowrite).
Def: noro.

:set redraw (re)
Redraw screen whenever edits are made. Noredraw useful on slow dumb terminals; deleted lines show up as @ and inserted text appears to overwrite existing text until [Escape] pressed.
Def: depends on line speed and terminal.

:set remap
Allow nested map sequences.
Def: remap.

:set report=?
Display message on prompt line whenever edit is made that affects at least a certain number of lines.
Def: report=5.

:set ruler
NVI: Display row/column on command line.
Def: noruler.

:set scroll=??
Amount of lines to scroll.
Def: half of window.

:set sections=?? ??
Define section delimiters for movement by [[ ]] . Pair of characters used in value are nroff/troff macros that begin sections.

:set shell=???? (sh)
Define pathname of shell used for shell escape ':!' and shell command ':sh' .
Def: SHELL variable.

:set shiftwidth=? (sw)
Define number of spaces for backward tabs when autoindenting or shifting lines with <</>> command.
Def: sw=8.

:set showdirty
NVI: Display asterisk on command line if file has been modified.
Def: noshowdirty.

:set showmatch (sm)
Good for programming; when ) or } is entered, cursor moves briefly to matching ( or { ; if no match made, error bell rings. NVI: also matches <> pairs.
Def: nosm.

:set showmode
NVI: Display current edit mode on command line.
Def: noshowmode.

:set sidescroll=??
NVI: Set number of columns shift to left-right when using leftright scrolling and left-right margin is crossed.
Def: sidescroll=16.

:set slowopen (slow)
Hold off display during insert.
Def: depends on line speed and terminal type.

:set sourceany
Start vi using other person's startup files; security risk, so do not use!
Def: nosourceany.

:set tabstop=? (ts)
Define number of [Tab] spaces.
Def: ts=8.

:set taglength=? (tl)
Define number of characters significant for tags.
Def: tl=0, all characters significant.

:set tags=?? ???
Define pathname of files containing tags.
Def: system searches /usr/lib/tags and file "tag" in current directory.

:set term=vt???
Define terminal type.

:set terse
Display shorter error messages.
Def: noterse.

:set tildeop
NVI: Modify ~ command to take associated motion.
Def: notildeop.

:set timeout (to)
Time out a keyboard map after 1 second; useful for vi versions that allow mapping a keystroke sequence.
Def: to.

:set ttywerase
NVI: Change how words are erased during input. Option breaks text into two classes, blanks and non-blank characters.
Def: nottywerase

:set ttytype=vt???
Define the terminal type.

:set verbose
NVI: Display error message on command line instead of ringing bell for all errors.
Def: noverbose.

:set warn
Display warning "No write since last change".
Def: warn.

:set window=?? (w)
Display specified number of lines on screen.
Def: depends on line speed and terminal type.

:set wrapmargin=? (wm)
Define right margin as number of spaces from end of line; automatically inserts carriage returns to break lines.
Def: wm=0.

:set wrapscan (ws)
Continue search around either end of a file.
Def: ws.

:set writeany (wa)
Allow saving to any file.
Def: nowa.

OTHER NOTES ABOUT VI
© Copyright 1993-2012 Jeff W
Send additions, corrections, comments to jeffw@jeffw.com