vim commands

A Vim cheat sheet, listing some useful, essential and most often used Vim commands.

# open new file
:e filename

# save changes to a file
:w

# quit vim
:q

# quit vim and don\'t save
:q!

# save file and quit
:wq

# if changes were made, save and exit, if not just exit
:x

# insert
i

# insert to the start of current line
I

# append after cursor
a

# append to end of current line
A

# open a new line below and insert
o

# open a new line above and insert
O

# change the rest of the current line
C

# overwrite one character, then go back to command mode
r

# enter insert mode but replace characters rather than inserting
R

#exit insertoverwritevisual mode and go back to command mode (ESC key)
ESC

# delete characters under the cursor
x

# delete characters before the cursor
X

# delete current line
dd
# or
:d

# start highlighting characters
v

#start highlighting lines
V

# undo
u

# undo all changes to current line
U

# redo
CTRL + r

# search for pattern
pattern

# scan for next search match in the same direction
n

# scan for next search match but opposite direction
N

# substitute foo with bar
#r determines range and a determines arguments
# range (r) can be nothing (current line), line number, or % (whole file)
#arguments (a) can be: 
# g -> replace all occurrences in the line
# i -> ignore case for search pattern
# I -> don\'t  ignore case for search pattern
# g -> replace all occurrences in the line
# c -> confirm each substitution
:rsfoobara

# examples
# replace the first occurrence of the word foo with bar on line number 452
:452sfoobar

# replace every occurrence of the word foo with bar on current line
:sfoobarg

# replace every occurrence of the word foo with bar in the whole file
:%sfoobarg

# the same as above, but ignore the case of the pattern
# this replaces foo, FOO, Foo...
:%sfoobargi

# confirm every substitution
:%sfoobargc

# foreach line in file, replace first occurrence of foo with bar
# and confirm every substitution
:%sfoobarc