Have you ever been stuck in a terminal text editor or a merge commit message while your boss looks over your shoulder wondering why he hired you? No? Me either.
If you get stuck in a terminal text editor, there’s a good chance it’s Vim or its father Vi. Once you understand Vim it’s a brilliant tool to have, but its learning curve can be steep.
Vim is a mode-based editor
Vim works based on three fundamental modes:
- Normal (command)
Normal, or command, mode is the default mode for vim. If you open or create a file in Vim it will open in normal mode. This mode lets you run commands like save/quit or copy/paste. You can return to this mode by pressing
ESC on your keyboard.
Insert mode allows you to edit the actual contents of the file. The key to enter insert mode is
i. Once you’re in insert mode, you are free to type and change the contents of the file as you see fit.
Visual mode is the selection mode in Vim. The key to enter visual mode is
Shift-V for line mode). Visual mode lets you select characters or lines to copy, move, or delete.
Basic Vim Commands
Okay, let’s start with some basic commands. Remember, to enter commands you need to be in normal (command) mode. Press
ESC to return to normal mode.
You can enter all these commands in normal mode.
Save / quit / undo
:q – Quit the document
:q! – Quit the document and discard any changes you have made to it
:w – Write-out (save) the document
:wq – Write-out (save) and then close the document
:x – Shorthand for
u – undo the last command
CTRL + r – redo the last command
v – Enters visual mode and allows you to select one character at a time
Shift - V – Enters visual mode and allows you to select lines at a time
y – After selecting text in visual mode, copy (yank) the text to the keyboard
d – After selecting text in visual mode, cut the text
p – After copying or cutting text, paste the text
yy – Copy the current line
dd – Delete the current line
gg – Move the cursor and window to the top of the document
G – Move the cursor and window to the bottom of the document
CTRL + F – Jump forward one page
CTRL - B – Jump backward one page
f [character] – Jump to the next occurrence of the specified character in the document
/[string] – Search for the specified string in the document
:%s/[find]/[replace] – Search the document for the
[find] string and replace the results with the
n – After searching, pressing n moves to the next search result
N – After searching, pressing N moves to the previous search
More advanced Vim commands
:color – Changes the color scheme of vim. My favorite (if you have a dark terminal background) is
:set number – Toggles line numbers
:earlier [n] – revert the document by n minutes
:later [n] – fast-forward the document by n minutes
That’s enough commands to get you started with Vim. Once you master these, my favorite website for Vim commands is Learn X in Y minutes which has a great list of Vim commands.