Vim Fundamentals
Vim is a modal text editor with three core modes:
- Normal Mode: The default mode when launching Vim. Used for navigation, searching, and editing.
- Insert Mode: Used for adding or modifying text content.
- Command Mode: Used for executing commands, saving files, and configuring editor settings.
Entering Insert Mode
| Shortcut | Description |
|---|---|
i |
Insert before cursor |
a |
Insert after cursor |
o |
Create new line below and enter insert mode |
s |
Delete character under cursor and enter insert mode |
I |
Insert at the beginning of the current line |
A |
Insert at the end of the current line |
O |
Create new line above and enter insert mode |
S |
Delete entire current line and enter insert mode |
Navigating in Normal Mode
Jumping to Line Positions
gg- Move to the first line of the documentG- Move to the last line of the document[n]G- Jump to line number[n](e.g.,150Gjumps to line 150)
Returning to Normal Mode
Pres Esc twice to exit insert mode or any other mode and return to normal mode.
Copying and Pasting
yy- Copy the current line[n]yy- Copy[n]consecutive lines (e.g.,5yycopies 5 lines)p- Paste below the current lineP- Paste above the current line
Deleting and Cutting
In Vim, dd serves as both a cut and delete operation:
dd- Delete the current line (cut if followed by paste)[n]dd- Delete[n]lines starting from cursor positionD- Delete from cursor position to end of line (leaves empty line)
Undo and Redo
u- Undo the last operationCtrl + r- Redo what was undone
Command Mode Operations
Enter command mode by typing : from normal mode. Search mode is entered by typing /.
Saving and Quitting
| Command | Description |
|---|---|
:w |
Save file without exiting |
:q |
Quit (only if file is saved) |
:wq |
Save and quit |
:wq [filename] |
Save to specified filename and quit |
:q! |
Force quit with out saving |
Searching
- Press
/to enter search mode - Type your search term and press
Enter - Navigate through results with
n(next match) orN(previous match)
Search and Replace
Replace first occurrence on current line:
:s/old_text/new_text
Replace all occurrences on current line:
:s/old_text/new_text/g
Replace first occurrence in entire file:
:%s/old_text/new_text
Replace all occurrences in entire file:
:%s/old_text/new_text/g
Display Line Numbers
:set nu
Practical Workflow
Opening a file:
vim filename
- If the file exists, it opens for editing
- If the file doesn't exist, Vim creates it in memory
Basic editing session:
- Open the file with
vim filename - Make your changes in insert mode
- Press
Esctwice to return to normal mode - Type
:wqto save and exit
To discard changes and exit, press Esc twice, then type :q!
Run vimtutor in your terminal for an interactive tutorial.