Vim Commands Cheat Sheet


Invoking Vim
Exiting Vim
Switching Modes
Editing a File
Moving Around
Inserting Text
Inserting a File
Word Completion
Deleting Text
Changing (or Replacing) Text
Copying (Yanking) and Moving Text
Undo/Redo/Repeat
Searching
Substituting (Searching and Replacing)
Selecting Text (Visual Mode)
Marks
How to Suspend
Status
Shell Works
Macros
Abbreviations
Setting Options


Invoking Vim

vi {file} Invoke vim editor on {file}.
vi {file1} {file2}... Invoke vim editor on files sequentially. After saving {file1} enter :n for the next file.
view {file} Invoke vim editor on {file} in read-only mode.
vi -R {file} Invoke vim editor on {file} in read-only mode.
vi -r {file} Recover {file} and recent edits after system crash.
vi + {file} Open {file} at last line.
vi +n {file} Open {file} at line n.
vi +/{pattern} {file} Open {file} at {patern}.


Exiting Vim

:q[uit] Quit Vim. This fails when changes have been made.
:q[uit]! Quit without writing.
:cq[uit] Quit always, without writing.
:wq or
:x
Write the current file and exit.
:wq! Write the current file and exit always.
:wq {file} Write to {file}. Exit if not editing the last
:wq! {file} Write to {file} and exit always.
:[range]wq[!] [file] Same as above, but only write the lines in [range].
ZZ Write current file, if modified, and exit.
ZQ Quit current file and exit (same as ":q!").


Switching Modes

i Enter insert mode and proceed to insert text before the current cursor position. Command mode
a Enter insert mode and proceed to insert text after the current cursor position (a is short for "append"). Command mode
I Position the cursor at the start of the line and then enter insert mode. Command mode
A Append text to current line (ie go to end of line and then enter "insert mode"). Command mode
v Enter visual mode. Visual or insert mode
<Esc> Enter command mode. Visual or insert mode
R Enter replace modes. Command mode
<Insert> Enter insert mode (from command mode) or switch between insert mode and replace mode (in insert/replace mode). Command mode or insert/replace mode


Editing a File

:e[dit] Edit the current file. This is useful to re-edit the current file, when it has been changed outside of Vim.
:e[dit]! Edit the current file always. Discard any changes to the current buffer. This is useful if you want to start all over again.
:e[dit] {file} Edit {file}.
:e[dit]! {file} Edit {file} always. Discard any changes to the current buffer.
:we! Re-edits current file saving changes.
gf Edit the file whose name is under or after the cursor. Mnemonic: "goto file".
:w Write changes to current file.
:w {file} Write to specified file.
:w! {file} Force write to {file}.
:n,mw {file} Saves lines n through m to {file}.
::n,mw>>{file} Appends lines n through m to the end of {file}.


Moving Around

Basic motion commands:

        k              
      h   l          
        j             

h or
<Left Arrow>
[count] characters to the left (exclusive).
l or
<Right Arrow> or
<Space>
[count] characters to the right (exclusive).
k or
<Up Arrow> or
CTRL-P
[count] lines upward.
j or
<Down Arrow> or
CTRL-J or
<NL> or
CTRL-N
[count] lines downward (linewise).
| To the [count] column in the line.
0 To the first character of the line (exclusive).
<Home> To the first character of the line (exclusive).
^ To the first non-blank character of the line.
$ or
<End>
To the end of the line and [count - 1] lines downward.
g0 or
g<Home>
When lines wrap ('wrap on): To the first character of the screen line (exclusive). Differs from "0" when a line is wider than the screen. When lines don't wrap ('wrap' off): To the leftmost character of the current line that is on the screen. Differs from "0" when the first character of the line is not on the screen.
g^ When lines wrap ('wrap' on): To the first non-blank character of the screen line (exclusive). Differs from "^" when a line is wider than the screen. When lines don't wrap ('wrap' off): To the leftmost non-blank character of the current line that is on the screen. Differs from "^" when the first non-blank character of the line is not on the screen.
g$ or
g<End>
When lines wrap ('wrap' on): To the last character of the screen line and [count - 1] screen lines downward (inclusive). Differs from "$" when a line is wider than the screen. When lines don't wrap ('wrap' off): To the rightmost character of the current line that is visible on the screen. Differs from "$" when the last character of the line is not on the screen or when a count is used.
f{char} To [count]'th occurrence of {char} to the right. The cursor is placed on {char} (inclusive).
F{char} To the [count]'th occurrence of {char} to the left. The cursor is placed on {char} (inclusive).
t{char} Till before [count]'th occurrence of {char} to the right. The cursor is placed on the character left of {char} (inclusive).
T{char} Till after [count]'th occurrence of {char} to the left. The cursor is placed on the character right of {char} (inclusive).
; Repeat latest f, t, F or T [count] times.
, Repeat latest f, t, F or T in opposite direction [count] times.
- <minus> [count] lines upward, on the first non-blank character (linewise).
+ or
CTRL-M or
<CR>
[count] lines downward, on the first non-blank character (linewise).
_ <underscore> [count] - 1 lines downward, on the first non-blank character (linewise).
% Match parenthesis.
<C-End> or
G
Goto line [count], default last line, on the first non-blank character.
<C-Home> or
gg
Goto line [count], default first line, on the first non-blank character.
<S-Right> or
w
[count] words forward.
<C-Right> or
W
[count] WORDS forward.
e Forward to the end of word [count].
E Forward to the end of WORD [count].
<S-Left> or
b
[count] words backward.
<C-Left> or
B
[count] WORDS backward.
ge Backward to the end of word [count].
gE Backward to the end of WORD [count].
Ctrl-b Scroll backward a screen (page up).
Ctrl-f Scroll forward a screen (page down).
Ctrl-u Scroll up half a screen.
Ctrl-d Scroll down half a screen.
Ctrl-y Scroll up one line.
Ctrl-e Scroll down one line.
H Top [count] lines of the screen.
M Middle line of the screen.
L Bottom [count] lines of the screen.
Ctrl-I Redraw screen.
z<CR> Make the [count] line the top line on the page.
z. Make the [count] line the middle line on the page.
z- Make the [count] line the bottom line on the page.
These commands move over words or WORDS.

A word consists of a sequence of letters, digits and underscores, or a sequence of other non-blank characters, separated with white space (spaces, tabs, <EOL>). This can be changed with the 'iskeyword' option.

A WORD consists of a sequence of non-blank characters, separated with white space (ignores punctuation). An empty line is also considered to be a word and a WORD.

( [count] sentences backward.
) [count] sentences forward.
{ [count] paragraphs backward.
} [count] paragraphs forward.
]] [count] sections forward or to the next '{' in the first column. When used after an operator, then the '}' in the first column.
][ [count] sections forward or to the next '}' in the first column.
[[ [count] sections backward or to the previous '{' in the first column.
[] [count] sections backward or to the previous '}' in the first column.


Inserting Text See also Inserting a File

a Append text after the cursor [count] times (Esc when finish).
A Append text at the end of the line [count] times.
i Insert text before the cursor [count] times.
I Insert text before the first non-blank in the line [count] times.
gI Insert text in column 1 [count] times.
o Begin a new line below the cursor and insert text, repeat [count] times.
O Begin a new line above the cursor and insert text, repeat [count] times.
Ctrl-v{char} While inserting, ignore special meaning of char (e.g., for inserting characters like Esc and Ctrl) until Esc is used.
Ctrl-i or
TAB
While inserting, inserts one shift width.
<< Shift [count] lines left by one shift width.
>> Shift [count] lines right by one shift width.
<{motion} Shift multiple lines left.
>{motion} Shift multiple lines right.
<Esc> Exit insert/repace mode and go back to command mode.


Inserting a File

:r[ead] [name] Insert the file [name] below the cursor.
:r[ead] !{cmd} Execute {cmd} and insert its standard output below the cursor.


Word Completion

Ctrl-N or
Ctrl-P
Complete part of a word that has been typed; can be repeated until matching the wanted one.


Deleting Text

<Del> or
x
Delete [count] characters under and after the cursor.
X Delete [count] characters before the cursor.
d{motion} Delete text that {motion} moves over.
dd Delete [count] lines.
D Delete the characters under the cursor until the end of the line.
J Join next [count] lines.
Ctrl-h or
<Backspace>
While inserting, delete previous character.
Ctrl-w While inserting, delete previous word.
Ctrl-r While inserting, delete to start of inserted text.
{Visual}x or
{Visual}d
Delete the highlighted text (for {Visual} see Selecting Text).
{Visual}CTRL-H or
{Visual}
When in Select mode: Delete the highlighted text.
{Visual}X or
{Visual}D
Delete the highlighted lines.
:[range]d[elete] Delete [range] lines (default: current line).
:[range]d[elete] {count} Delete {count} lines, starting with [range].

Examples for d{motion}


        dw          Delete [count] words
        dG          Delete from the current position to the end of the file
        d1G         Delete from the current postion to the start of the file
        d$          Delete from current postion to the end of the line (same as D)
        dn$         Delete from current line the end of the nth line


Changing (or Replacing) Text

r{char} replace the character under the cursor with {char}.
R Enter Insert mode, replacing characters rather than inserting.
cw Changes text from current location of current or next [count] words.
c$ Changes text from current position to end of [count] lines.
C Changes to end of line (same as c$).
cc Changes current line.
s Substitutes text for (next) [count] characters.
S Substitutes text for (next) [count] lines.
~ Switch case of the character under the cursor and move the cursor to the right. If a [count] is given, do that many characters.
~{motion} switch case of {motion} text.
{Visual}~ Switch case of highlighted text.


Copying (Yanking) and Moving Text

"{a-zA-Z0-9.%#:-"} Use register {a-zA-Z0-9.%#:-"} for next delete, yank or put (use uppercase character to append with delete and yank) ({.%#:} only work with put).
:reg[isters] Display the contents of all numbered and named registers.
:reg[isters] {arg} Display the contents of the numbered and named registers that are mentioned in {arg}.
:di[splay] [arg] Same as :registers.
["x]y{motion} Yank {motion} text [into register x].
["x]yy Yank [count] lines [into register x].
["x]Y Yank [count] lines [into register x] (synonym for yy).
["x]y$ Yank the current position to the end of the line [into register x].
{Visual}["x]y Yank the highlighted text [into register x] (for {Visual} see Selecting Text).
{Visual}["x]Y Yank the highlighted lines [into register x].
:[range]y[ank] [x] Yank [range] lines [into register x].
:[range]y[ank] [x] {count} Yank {count} lines, starting with last line number in [range] (default: current line), [into register x].
["x]p Put the text [from register x] after the cursor [count] times.
["x]P Put the text [from register x] before the cursor [count] times.
["x]gp Just like "p", but leave the cursor just after the new text.
["x]gP Just like "P", but leave the cursor just after the new text.
:[line]pu[t] [x] Put the text [from register x] after [line] (default current line).
:[line]pu[t]! [x] Put the text [from register x] before [line] (default current line).

Vi uses 26 named (registered) buffers identified by letters of the alphabet. If not identified, vi uses unamed buffer.

To move text, at first delete text (text will be put to unamed/named buffer) and then paste it.


Undo/Redo/Repeat

u Undo [count] changes.
:u[ndo] Undo one change.
CTRL-R Redo [count] changes which were undone.
:red[o] Redo one change which was undone.
U Undo all latest changes on one line. {Vi: while not moved off of it}.
. Repeat last change, with count replaced with [count].


Searching

/{pattern}[/] Search forward for the [count]'th occurrence of {pattern}.
/{pattern}/{offset} Search forward for the [count]'th occurrence of {pattern} and go {offset} lines up or down.
/<CR> Search forward for the [count]'th latest used pattern.
//{offset}<CR> Search forward for the [count]'th latest used pattern with new. If {offset} is empty no offset is used.
?{pattern}[?]<CR> Search backward for the [count]'th previous occurrence of {pattern}.
?{pattern}?{offset}<CR> Search backward for the [count]'th previous occurrence of {pattern} and go {offset} lines up or down.
?<CR> Search backward for the [count]'th latest used pattern.
??{offset}<CR> Search backward for the [count]'th latest used pattern with new {offset}. If {offset} is empty no offset is used.
n Repeat the latest "/" or "?" [count] times.
N Repeat the latest "/" or "?" [count] times in opposite direction.
:set ic Ignore case when searching.
:set noic Pay attention to case when searching.

The string in the command [ / ] or [ ? ] can be a regular expression.

         .          Matches any single character except newline.
         \          Escapes any special characters.
         *          Matches 0 or More occurances of the preceding character.
         []         Matches exactly one of the enclosed characters.
         ^          Match of the next character must be at the begining of the line.
         $          Matches characters preceding at the end of the line.
         \<         Matches beginning of word.
         \>         Matches end of word.
         [^]        Matches anything not enclosed after the not character.
         [-]        Matches a range of characters.
Examples:
         c.pe       Matches cope, cape, caper etc
         c\.pe      Matches c.pe, c.per etc
         sto*p      Matches stp, stop, stoop etc
         car.*n     Matches carton, cartoon, carmen etc

         xyz.*      Matches xyz to the end of the line.
         ^The       Matches any line starting with The.
         atime$     Matches any line ending with atime.
         ^Only$     Matches any line with Only as the only word in the line.
         b[aou]rn   Matches barn, born, burn.

         Ver[D-F]   Matches VerD, VerE, VerF.
         Ver[^1-9]  Matches Ver followed by any non digit.
        the[ir][re] Matches their,therr, there, theie.
  [A-Za-z][A-Za-z]* Matches any word.


Substituting (Searching and Replacing)

:[range]s[ubstitute]/{pattern}/{string}/[c][e][g][p][r][i][I] [count] For each line in [range] replace a match of {pattern} with {string}.
:[range]s[ubstitute] [c][e][g][r][i][I] [count] :[range]&[c][e][g][r][i][I] [count] Repeat last :substitute with same search pattern and substitute string, but without the same flags. You may add extra flags.

Range:
   nothing or .     work on current line only
   number           work on the line whose number you give (such as .+3, -3)
   start,end        work on the lines from start to end
   $                the last line
   %                the whole file (all lines from beginning to end)
Arguments:
[c]  Confirm each substitution.  Vim positions the cursor on the matching
  string.  You can type:
      'y'      to substitute this match
      'n'      to skip this match
      <Esc>    to skip this match
      'a'      to substitute this and all remaining matches {not in Vi}
      'q'      to quit substituting {not in Vi}
      CTRL-E   to scroll the screen up {not in Vi}
      CTRL-Y   to scroll the screen down {not in Vi}.
[e]     When the search pattern fails, do not issue an error message and, in
  particular, continue in maps as if no error occurred.  
[g]  Replace all occurrences (global) in the line.  Without this argument,
  replacement occurs only for the first occurrence in each line.
[i]  Ignore case for the pattern.  
[I]  Don't ignore case for the pattern.  
[p]  Print the line containing the last substitute.
Examples:

         :1,$s/the/The/g      Search the entire file and replace the with The.
         :%s/the/The/g        % means the complete file. (Same as above).
         :.,5s/^.*//g         Delete the contents from the current to 5th line.
         :%s/the/The/gc       Replace the with The but ask before substituting.
         :%s/^....//g         Delete the first four characters on each line.
         :%s/^V^M$//g         Delete ^M at the end of lines (seen in files created in Windows)
                              (cat oldfile | tr -d '\r' > newfile)
If the [ g ] directive is not included then the change is performed only on the first occurance of a match on each line.

Re-use the original search string in the replacement result (you could also retype the command on the line.)

         :1,5s/help/&ing/g    Replaces help with helping on the first 5 lines.
         :%s/ */&&/g          Double the number of spaces between the words.
Using the complete match string has its limits hence vi uses the escaped parentheses [
( ] and [
) ] to select the range of the substitution. Using an escaped digit [
1 ] which identifies the range in the order of the definition the replacement can be build.
         :s/^\(.*\):.*/\1/g   Delete everything after and including the colon.
         :s/\(.*\):\(.*\)/\2:\1/g    Swap the words either side of the colon.


Selecting Text (Visual Mode)

To select text, enter visual mode with one of the commands below, and use motion commands to highlight the text you are interested in. Then, use some command on the text.

The operators that can be used are:
  ~  switch case
  d  delete
  c  change
  y  yank
  >  shift right
  <  shift left 
  !  filter through external command 
  =  filter through 'equalprg' option command 
  gq  format lines to 'textwidth' length 
v Start Visual mode per character.
V Start Visual mode linewise.
<Esc> Exit Visual mode without making any changes.


Marks

m{a-zA-Z} Set mark {a-zA-Z} at cursor position (does not move the cursor, this is not a motion command).
m' or
m`
Set the previous context mark. This can be jumped to with the "''" or "``" command (does not move the cursor, this is not a motion command).
:[range]ma[rk] {a-zA-Z} Set mark {a-zA-Z} at last line number in [range], column 0. Default is cursor line.
:[range]k{a-zA-Z} Same as :mark, but the space before the mark name can be omitted.
'{a-z} To the first non-blank character on the line with mark {a-z} (linewise).
'{A-Z0-9} To the first non-blank character on the line with mark {A-Z0-9} in the correct file.
`{a-z} To the mark {a-z}.
`{A-Z0-9} To the mark {A-Z0-9} in the correct file.
:marks List all the current marks (not a motion command).
:marks {arg} List the marks that are mentioned in {arg} (not a motion command).


How to Suspend

CTRL-Z Suspend Vim, like ":stop". Works in Normal and in Visual mode. In Insert and Command-line mode, the CTRL-Z is inserted as a normal character.
:sus[pend][!] or
:st[op][!]
Suspend Vim. If the '!' is not given and 'autowrite' is set, every buffer with changes and a file name is written out. If the '!' is given or 'autowrite' is not set, changed buffers are not written, don't forget to bring Vim back to the foreground later!


Status

:.= Show current line number.
:= Show number of lines in file.
Ctrl-g Show filename, current line number, total lines in file, and % of file location.
:l (letter "l") Display tab (^l) backslash (\) backspace (^H) newline ($) bell (^G) formfeed (^L^) of current line.


Shell Works

:!{cmd} Execute shell command {cmd}; you can add these special characters to indicate: % name of current file, # name of last file edited.
!!{cmd} Execute shell command {cmd}; place output in file starting at current line.
:!! Execute last shell command.
:r!{cmd} Read and insert output from {cmd}.
:f {file} Rename current file to {file}.
:w!{cmd} Send currently edited file to {cmd} as standard input and execute {cmd}.
:cd {dir} Change current working directory to {dir}.
:sh Start a sub-shell (Ctrl-d returns to editor).
:so {file} Read and execute commands in {file} ({file }is a shell script).
!{motion} {cmd} Send text from current position to {motion} to shell command {cmd}.
!}sort <CR> Sort from current position to end of paragraph and replace text with sorted text.


Macros

:map {key} {cmd_seq} Define {key} to run {cmd_seq} when pressed.
:unmap {key} Remove macro definition for key.
:map Display all created macros on status line.

Map allows you to define strings of Vim commands. If you create a file called ".vimrc" in your home directory, any map or set command you place inside this file will be executed every time you run Vim. To imbed control characters like Esc in the macro, you need to precede them with Ctrl-v. If you need to include quotes ("), precede them with a \ (backslash). Unused keys in vi are: K V g q v * = and the function keys.

Example: map v /I Ctrl-v Esc dwiYou Ctrl-v Esc Esc when v is pressed, search for "I" (/I Esc), delete word (dw), and insert "You" (iYou Esc). Ctrl-v allows Esc to be inserted.


Abbreviations

:ab Display all abbreviations.
:ab {str} {string} When {str} is input, replace it with {string}.
:una {str} Unabbreviate {str}.


Setting Options

:set all Print all options to the screen.
:set {option} Turn on {option}.
:set no{option} Turn off {option}.
:set ai Turn on auto indentation.
:set ap Print line after d c J m :s t u commands.
:set bf Discard control characters from input.
:set eb Precede error messages with a bell.
:set dir=tmp Set directory for buffer file.
:set ic Ignore case when searching.
:set lisp Modify brackets for Lisp compatibility.
:set list Show tabs (^l) and end of line ($).
:set magic Allow pattern matching with special characters.
:set mesg Allow others to send messages.
:set nu Show line numbers.
:set opt Speed output; eliminates automatic RETURN.
:set prompt Prompt for command input with :.
:set re Simulate smart terminal on dumb terminal.
:set report Indicate largest size of changes reported on status line.
:set ro Change file type to "read only."
:set scroll=n Set n lines for Ctrl-d and z.
:set sh=shell_path Set shell escape (default is /bin/sh).
:set showmode Indicate input or replace mode at bottom.
:set sw=n Set shift width to n characters.
:set term Print terminal type.
:set terse Shorten messages with terse.
:set timeout Eliminate one-second time limit for macros.
:set tl=n Set significance of tags beyond n characters (0 means all).
:set ts=n Set tab stops to n for text input.
:set wa Inhibit normal checks before write commands.
:set warn Warn "no write since last change."
:set window=n Set number of lines in a text window to n.
:set wm=n Set automatic wraparound n spaces from right margin.


Ref:
- http://www.fprintf.net/vimCheatSheet.html
- http://www.denison.edu/mathsci/software_docs/vi_cheatsheets.pdf
...

Collected Feb 29, 2004 Nien V Lam. Last change: Thu Aug 19 21:19:12 JST 2004