Vi has two modes: command mode and insert mode. Command mode is for issuing commands like moving the cursor, saving files, finding/replacing text, and copying/pasting. Insert mode is for inserting text. You switch between the two modes using keyboard shortcuts like Esc or Ctrl-[ to exit insert mode. Common commands in command mode include hjkl to move, x/dd to delete characters/lines, u to undo, and p to paste. Search and replace uses regex, and files can be saved, quit, or opened with commands like :w, :q, :e.
2. 2 Modes
Command Mode
vi starts in command mode. In command mode, everything you
type is a command to do something, like:
• move the cursor around
• save, quit, open a new file
• find and replace
• copy and paste, etc.
Insert Mode
While in insert mode, everything you type is inserted into the
document you’re editing.
3. Command Mode Insert Mode
i - ...at the current cursor position
I - ...at the beginning of the current line
a - ...at the next character
A - ...at the end of the current line
o - ...below the current line
O - ...above the current line
... plus lots more ways to get into insert mode
Esc
Ctrl-[
Ctrl-c
Get into insert mode:
Get into command mode:
You switch between
these two modes a lot
as you’re editing
4. Editing in command mode
• h j k l – Move cursor left, down, up, right
• x – Delete a character
• 5x – Delete 5 characters
• dd – Delete a line
• 5dd – Delete 5 lines
• dj – Delete the line below the cursor
• dk – Delete the line above the cursor
• u - Undo
5. Copy and Paste
Every time you delete something in vi, it gets
stored in a buffer that can then be pasted into
the file with p or P.
To put something into the copy buffer without
deleting it, you “yank” it using a variation of the
y command.
• yy – Yank the current line into the copy
buffer
6. Search and Replace
• /search_string<Enter> - Search for
“search_string” in the document. Type n to
jump to the next search result if there’s more
than 1
• :%s/aaa/a/g<Enter> - Replace all
occurrences of “aaa” with “a”.
Search and replace commands use a regex
language that supports wildcards, etc.
7.
8. Saving, quitting, and opening files
• :w, :wq, :q, :q! – Save, save-quit, quit.
Add a ! to any of these commands to force-
save or force-quit.
• :e file.js – Start editing a new file
• :sp file.js, :vsp file.js – Open a
new file in a split window, horizontally or
vertically. To move between windows, type
Ctrl-w then a direction key (h,j,k,l).