Xah Lee, 2005-10, …, 2012-01-01
This page is a basic tutorial for vi or vim.
vi is one of unix's fuckup. Sometimes in a emergency situation you are forced to deal with vi, and fucking unix admins refuse to install emacs. Here's your help:
vi myfile.txt• Use arrow keys to move the cursor.
To insert text, move your cursor to the right place, then press i, then type your text. After you are done, type Esc to exit the insertion mode.
To delete text, move cursor to the right place and press x. (if x is inserted, that means you forgot to exit the insert mode. Type Esc to exit insertion mode. Type u to undo.)
When something doesn't work, or if you accidentally typed something and have no idea what is going on, try press Esc, then type u for undo. If a cat jumped onto your keyboard and you cannot exit vi, type the shell suspend command 【Ctrl+z】, which should get you back on the unix command prompt, then you can kill. (by first find out the pid by ps auwwx | grep vi, then kill -9 ‹pid›).
Congratulation! You've learned emergency vi.
It may be confusing, but with the above you can edit any text files with vi.
Remember, in vi, it has modes. At any one time, you are either in command mode or text insertion mode. To go to the command mode, just press Esc. To go into editing mode, press i.
| Key | Meaning |
|---|---|
| i | insert |
| a | insert after cursor (append) |
| o | insert a new line |
| Key | Meaning |
|---|---|
| u | undo |
| 【Ctrl+r】 | redo |
| Key | Meaning |
|---|---|
| j | down |
| k | up |
| h | left |
| l | right |
| w | next word |
| b | prev word |
| 0 | beginning of line |
| $ | end of line |
| :n | line n |
| :$ | end of file |
| 【Ctrl+f】 | page down |
| 【Ctrl+b】 | page up |
| Key | Meaning |
|---|---|
| x | delete char |
| 9x | delete 9 chars |
| dw | delete word |
| 9dw | delete 9 words |
| D | delete from cursor to end of line |
| dd | delete whole current line |
| Key | Meaning |
|---|---|
| yy | copy current line |
| 3yy | copy 3 lines |
| p | paste |
Note that when you delete a word or many words, the word is automatically put into the clipboard.
| Key | Meaning |
|---|---|
| /aa | search forward for text “aa” |
| ?aa | search backward for text “aa” |
| n | next occurrence |
| N | previous occurrence |
| :s/aa/bb/gc | search and replace “aa” by “bb”. “g” (global) means do it in all these lines, not just only first occurrence of each line. “c” means ask for confirmation before each replaement. |
| :20,30s/aa/bb/gc | search and replace “aa” by “bb” in line 20 to 30. |
| Key | Meaning |
|---|---|
| :set syn=lang | the “lang” can be perl, c, cpp, html, php, javascript, python etc. |
| :syntax on | Turn on syntax coloring |
| :syntax off | Turn off syntax coloring |
| Key | Meaning |
|---|---|
| :set number | Turn on line numbers |
| :set nonumber | Turn off line numbers |