Notes to Self

Alex Sokolsky's Notes on Computers and Programming

vi cheat sheet

vi in wikipedia, original article.

Command Line

Command Action
vi file edit file
view file view file
vi -r file view file
vi -R file view file
vi + file edit file, cursor at last line
vi +n file edit file, cursor at line n

Modes: Command & Input

vi starts in command mode. Navigation commands operate in command mode. To switch to input mode enter one of the input commands. Once in input mode, any character you type is added to the file. To exit the input mode, press the Esc key.

graph LR
    A[Start] --> B(Command Mode)
    B -- Navigation --> B
    B -- Deletion --> B
    B -- Input Command --> D(Input Mode)
    D --Esc--> B

Open

Key Action
:e file Open file for editing
:e! file Discard changes, open file for editing

Save, Exit

While in command mode…

Key Action
:x Save and exit
:q Quit
:q! Discard changes, quit
:e! Discard changes since last save
:w Save
:w! Save, overwrite protection
:w file Save as file
:wq Save the file, exit vi

While in Command Mode…

Key Action
H Upper left corner (home)
M Middle line
L Lower left corner
h Back a character
l Forward a character
  Word navigation
w One word forward
b One word back
  Line navigation
^ Beginning of line
$ End of line
j Down a line
k Up a line
G go to the last line
1 G go to the first line
n G go to line n
: n go to line n
Ctrl+G display line

Viewport

Key Action
z [Enter] Cursor at top
z. Cursor in the middle
z- Cursor at bottom

Search & Replace

Searches are case sensitive by default.

Search case sensitivity Command
Ignore case :set ic
Respect case :set noic

Special characters in search pattern:

Character Matching
^ Beginning of line
$ End of line
\< Beginning of word
\> End of word
. Wildcard characters
Key Action
fc Find c
; Repeat find (find next c)
/ pattern Forward
/ Repeat forward
? pattern Reverse
? Repeat reverse
n Next occurrence in the direction of search
N Prev occurrence in the direction of search
:g/from/s//to/g Global replace
:g/from/s//to/g Global replace, consult

Deletion Commands

While in command mode…

Key Action
dd Delete a line
n dd Delete n lines
d) Delete to end of sentence
db Delete the previous word
D Delete to the end of line
x Delete a character

Undo commands

Key Action
u Undo last change
U Undo all changes on line

Input Commands

These force transition to input mode. To get back into command mode, press Esc.

Key Action
i Insert before
a Insert after
I Insert at the beginning of line
A Insert at the end of line
o Open line below
O Open line above
:r file Import a file
:12r file Import a file at line 12