vim usage tips
Pictures worth a thousand unix commands and options:
I draw this to my students each semester and they seem to grasp vi afterwards.
vi is a finite state machine with only three states.
======== ======
VIM has 3 modes of operation: Input mode, Command mode & Ex mode.
Input mode - everything that you type, all keystrokes are echoed on the screen.
Command mode or Escape mode - everything that you type in this mode is interpreted as a command.
Ex mode - this is another editor, ex. It is a line editor. It works per line or based on a range of lines. In this mode, a :
appears at the bottom of the screen. This is the ex editor.
In order to exit vim, you can exit while you are in either the ex mode or in the command mode. You cannot exit vim when you are in input mode.
Exiting from ex mode
-
you need to be sure that you are in the Command mode. To do that, simply press the Escape key.
-
Go to the ex mode by pressing the
:
key -
Use any of the following combinations in ex mode to exit:
:q
- quit :q!
- quit without saving :wq
- save & quit or write & quit :wq!
- same as wq, but force write incase file permissions are readonly :x
- write & quit :qa
- quit all. useful when multiple files are opened like: vim abc.txt xyz.txt
Exiting from command mode
-
Press the escape key. You probably have done this already if you are in command mode.
-
press capital ZZ (
shift zz
) - save & exit -
press capital ZQ (
shift zq
) - exit without saving.
Upon starting, vi goes into COMMAND mode, where you can type short, few character commands, blindly. You know what you are doing, this isn't for amateurs.
When you want to actually edit text, you should go to INSERT mode with some one-character command:
- i: go to INSERT in the place of the cursor
- I: go to INSERT mode at the beginning of the line
- a: append after the cursor
- A: append at the end of line
- o: open a new line below the current line
- O: open a new line in the place of the current line
Now, answering the question: exiting.
You can exit vi from EX mode:
- q: if you haven't made any modifications, or saved them beforehand
- q!: ignores any modifications and quit
- wq: save and quit
- x: this is equal to wq
w and x accept file name parameter. If you started vi with a filename, you need not give it here again.
At last, the most important: how can you reach EX mode?
EX mode is for long commands that you can see typing at the bottom line of the screen. from COMMAND mode, you push colon, : and a colon will appear at the bottom line, where you can type the above commands.
From INSERT mode, you need to push ESC, i.e. the Escape button, going to COMMAND mode, and then : to go to EX mode.
If you are unsure, push ESC and that will bring you to command mode.
So, the robust method is ESC-:-x-Enter which saves your file and quits.