Vim — Modes and Moving Around
Sooner or later you'll be logged in to a server with no graphical editor, and a file will need changing. Vim, or its older relative vi, is installed almost everywhere. Newcomers often get stuck in it because they don't know one fact: the keys do different things depending on which mode you're in.
The rule
In Vim, keys are commands until you press i.
Open Asha's notes with:
$ vim ~/garden/notes.txtVim starts in Normal mode. Here, letters don't type text. Each one is a command: j moves down a line and x deletes a character. There are three modes to know:
| Mode | How you get there | What keys do |
|---|---|---|
| Normal | the starting mode; Esc from anywhere |
move, delete, copy, paste |
| Insert | i, a or o from Normal |
type text, like any editor |
| Command-line | : from Normal |
save, quit, search and replace |
Three ways into Insert mode:
iinserts before the cursor.aappends after the cursor.oopens a new line below and starts typing there.
To get out of a file:
| Type (in Normal mode) | Result |
|---|---|
:w then Enter |
write (save) the file |
:q |
quit; refuses if you have unsaved changes |
:wq |
save and quit |
:q! |
quit and throw away the changes |
Moving in Normal mode:
hjklmove left, down, up and right. The arrow keys usually work too.wjumps to the next word andbgoes back a word.0goes to the start of the line and$to the end.gggoes to the first line,Gto the last, and5Gto line 5.
The shortcut
When in doubt, press Esc. It always brings you back to Normal mode, and pressing it twice does no harm. From Normal mode, every exit is a colon followed by a letter or two.
Open
vim ~/garden/notes.txt. She is in Normal mode, and typing letters now would run commands.
The classic trap is starting to type the moment Vim opens. Letters like d, x and G quietly change the file or move the cursor. If that happens, press Esc and then u to undo, or leave with :q! to discard everything.
Drills
Answer fast — trust the rule.
Which mode is Vim in right after it opens a file?
You've made changes you don't want. How do you quit without saving?
In Normal mode, which key opens a new line below the cursor and starts Insert mode?
You're not sure which mode you're in and want to save. What's the reliable key sequence?
Which keys take you to the last line of the file, then to the end of that line?
Remember
- In Vim, keys are commands until you press i (or a, or o).
- When in doubt, press Esc. Then
:wsaves,:qquits,:wqdoes both and:q!discards. - Don't type as soon as Vim opens. If something goes wrong,
Escthenuundoes it.
