Eric's vi notes (and vim notes!)

Important commands

exit :q!
exit ZZ
write the file :w
read a file :r
refresh a file from disk :e
execute a shell command such as ls :!ls back to command mode from text entry mode [ESC] or CTRL-c
refresh screen CTRL-r
undo U
display cursor position CTRL-g
repeat the last stuff .

Text insertion

insert text at cursor i
append text after cursor a
add a new line below cursor and enter insert mode o
add a new line at cursor and enter insert mode O
add the contents of a file at the cursor r [filename]

delete stuff

single character x
delete a return J
line dd
current line to EOF dG
cursor to start of line d0
cursor to end of line d$
word forward dw
word backward db
7 lines 7dd
5 words 5dw
etc

Change stuff

change word cw
change word backwards cb
transpose characters xp
change case of character and advance cursor ~
etc

Indent and unindent

set how many spaces to indent :set sw=2
select range of text V
indent it >
unindent it <
restore previous selection gv

replace stuff

one char r
keep replacing R

cursor movement

up k
down j
down 4 lines 4j
left h
right l
beginning of line 0
end of line $
word forward w
word backward b
8 words forward 8w
end of word e
Jump to beginning of file 1G
jump to end of file G
jump to top of current screen H
jump to middle of current screen M
jump to bottom of current screen L
page up CTRL-B
page down CTRL-F
Forward some lines CTRL-D
Back the same amount of lines CTRL-U
Center cursor vertically zz

Cutting and pasting

copy 3 lines 3yy
cut 6 lines 6dd
copy word yw
copy to end of line y$
paste p or P

searching

Jump forward to some text /
Jump backward to some text ?
Jump to the next hit forward n
Jump to the next hit backward N
Remove all the highlighting :noh

search and replace

delete blank lines: g/^$/d
prepend # to each line:
:foo,bar s/^/#/
(foo = beginning line number, bar = ending line number)
global search and replace is like these examples:
:%s/old/new/g
:%s,/path/to/old,/path/to/new,g
:%s\/path\/to\/old/\/path\/to\/new/g
to remove ^M from a file, use this:
:%s/^V^M$// or :%s/^\^M//
(note: ^V means CTRL-V)
to repeat some varying text, such as a number in every line, like: abc 123
:%s/\([0-9]\+$\)/\1 \1/g

to touch only a few lines, instead of :%s/abc/def/ you can replace the % with start,finish.
"%" means the whole file. This can be replaced by [start],[end]

more advanced use

Working with multiple files: To open them do vi *.txt
Save and move to the next file :wn
Show filename and position in file ^g
Edit a block of text, multiple lines, at the same time (select with CTRL-V): I (then your text, then ESC)
Enter hex mode :%!xxd
Leave hex mode :%!xxd -r
Show line numbers: :set number (or :set nu)
Remove highlighting: :noh
Insert the output of a command into the file: :r! ps -ef
Delete all empty lines :g/^$/d
Set UTF-8 encoding :set enc=utf-8

vim stuff

To allow the mouse to move the cursor: :set mouse=a

Thanks for visiting! ---Eric