Vim: survival basics
Modes, open, save and quit, moving around and editing in vim. The minimum you need to edit a config file without panic.
Why vim?
vi/vim is on every Linux server, also on minimal systems and in rescue mode where nano may be missing. You don’t need to love it, but you should be able to edit a file with it. On Ubuntu, vi starts vim.
Tip: Prefer something simpler?
nanois installed on Ubuntu too. Make it the default forsudoedit,visudoandcrontab -ewithsudo update-alternatives --config editor.
The one idea: modes
Vim has modes. Keys do different things depending on the mode. Most confusion comes from typing while in the wrong mode.
| Mode | You are here when… | Get there with |
|---|---|---|
| Normal | you move around and give commands (start mode) | Esc (press it whenever you’re lost) |
| Insert | you type text | i (before cursor), a (after), o (new line below) |
| Visual | you select text | v (characters), V (lines), Ctrl+V (block) |
| Command line | you type : commands at the bottom | : from normal mode |
The bottom line shows -- INSERT -- or -- VISUAL -- when you’re not in normal mode.
Open, save, quit
| What | Keys |
|---|---|
| Open a file | vim /etc/hosts (root-owned: sudoedit /etc/hosts) |
| Open at line 42 | vim +42 file |
| Save | :w |
| Save and quit | :wq or ZZ |
| Quit (no changes) | :q |
| Quit and discard changes | :q! |
| Save a root-owned file you opened without sudo | :w !sudo tee %, then :q! |
Moving around (normal mode)
| Keys | Moves |
|---|---|
h j k l | left, down, up, right (arrow keys work too) |
w / b | next / previous word |
0 / $ | start / end of line |
gg / G | first / last line |
42G or :42 | line 42 |
Ctrl+D / Ctrl+U | half a page down / up |
% | jump to the matching bracket |
Editing (normal mode)
| Keys | Does |
|---|---|
x | delete the character under the cursor |
dd | delete (cut) the line |
dw | delete to the end of the word |
D | delete to the end of the line |
cw | change the word (delete and go to insert mode) |
r + char | replace one character |
u | undo |
Ctrl+R | redo |
. | repeat the last change |
>> / << | indent / unindent the line |
Numbers repeat a command: 3dd deletes 3 lines, 5j moves 5 lines down.
Learn more
Run vimtutor. It is installed with vim and takes about 30 minutes.
Next: Vim: copy and paste.