1. Modes
| Key | Mode | Description |
|---|---|---|
ESC |
Normal Mode | Default mode. Used for navigation and simple editing. |
i |
Insert Mode | Insert and edit text. |
: |
Command Mode | Run commands like save, quit, search, etc. |
2. Basic Commands
-
Open File
vi <file> -
Quit
:q! -
Insert Text
i -
Save File
:w -
Save and Quit
:wq
3. Navigation
-
Enable Line Numbers
:set number -
Jump to Line
:<line_number>
Example:
:8
- Jump to End of File
ESC :$
4. Editing
-
Delete Line
dd -
Undo
u -
Create New Line
o -
Paste
p
5. Selection
- Select Text
v
Then move cursor.
-
Indent / Unindent
> < -
Copy (Yank)
y
6. Search
- Search Text
:/<keyword>
Example:
:/main
- Next Result
n
7. Split Window
-
Split Screen
:split <file> -
Switch Between Windows
Ctrl + ww
8. Practice
- Practice 1 — Basic Editing
- Create a file:
vi test.txt
- Enter Insert mode:
i
- Type:
Hello Vim
Learning Vim is fun
- Save and quit:
ESC
:wq
- Practice 2 — Navigation
- Open file:
vi test.txt
- Enable line numbers:
:set number
- Jump to line 2:
:2
- Practice 3 — Editing
Delete a line:
dd
Undo:
u
Add a new line below:
o
- Practice 4 — Search
Search for a word:
:/Hello
Next match:
n
- Practice 5 — Copy & Paste
Enter visual mode:
v
Copy:
y
Paste:
p
- Practice 6 — Quick way to comment/uncomment lines
Put your cursor on the first # character, press CtrlV (or CtrlQ for gVim), and go down until the last commented line and press x, that will delete all the # characters vertically. For commenting a block of text is almost the same: First, go to the first line you want to comment, press CtrlV. This will put the editor in the VISUAL BLOCK mode. Then using the arrow key and select until the last line Now press ShiftI, which will put the editor in INSERT mode and then press #. This will add a hash to the first line. Then press Esc (give it a second), and it will insert a # character on all other selected lines.
Refer: https://stackoverflow.com/questions/1676632/whats-a-quick-way-to-comment-uncomment-lines-in-vim