VIM Quick Guide


linux

Whenever I use Vim to edit files on Linux, I need to relearn how to use it. Years ago I found a thread on Stack Overflow with two simple and extremely useful answers that helped me make sense of Vim. So here it is.

Sections

  1. Vim Commands
  2. Making sense of Vi (and Vim)
  3. Reference

In my search for a tutorial or guide to help me understand how Vim works, I came upon this Stack Overflow thread with excellent answers. My favorite of these are below, but feel free to dive deep at the original link.

Vim Commands

KeyEffect
:qto quit (short for :quit)
:q!to quit without saving (short for :quit!)
:wqto write and quit
:wq!to write and quit even, force write is file has only read permission
:xto write and quit (similar to :wq, but only write if there are changes)
:qato quit all (short for :quitall)
:cqto quit without saving and make Vim return non-zero error (i.e. - exit with error)

Making sense of Vi (and Vim)

Pictures are worth a thousand Unix commands and options:

Vi Diagram.

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 — COMMAND, INSERT, EX.

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 on key press:

KeyEffect
igo to INSERT in the place of the cursor
Shift + igo to INSERT mode at the beginning of the line
aappend after the cursor
Shift + aappend at the end of line
oopen a new line below the current line
Shift + oopen a new line in the place of the current line
Escgo to COMMAND mode

Now, exiting. You can exit vi from EX mode:

KeyEffect
:qquit if you haven’t made any modifications, or saved them beforehand
:q!ignores any modifications and quit
:wqsave and quit
:xthis is equal to wq

w and x accept a 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, going to COMMAND mode, and then colon (:) to go to EX mode. If you are unsure, push Esc and that will bring you to command mode.

So, the robust method, which saves your file and quits, is to hit Esc, type :x, then hit Enter.