What is Vim?

You probably have some idea what Vim is since you're here reading this, but just to make certain that you know what we're taking about I'll explain it. Vim (pronouced: 'vee-eye improved') is a highly configurable text editor built for speedy text editting. It is an improved version of Vi, which is a text editor that comes bundeled with most *nix distrobutions.

Why would I want to learn Vim?

There are many reason to learn Vim. The fact that it is one of the most powerful text editors available should be enough reason to get you interested. If you're working with *nix machines it is also nice to know the basics of Vim, since it is (almost) always available and if you've had a computer crash or something similair it might be that Vim is the only editor that will function. When accessing other computers via telnet or ssh Vim also good to know, since you can be almost certain that Vi will be on the machine (as long as it is a *nix machine that is) and you can then easily edit files on the remote machine since Vim works perfectly in a terminal window.

What do I need before starting?

To start learing Vim you need access to Vim in one form or another and an interest in learing it. If you don't have Vim allready installed on your computer you can download it from www.vim.org. There are version of Vim available for most OS' (and the source is available so you can compile it if you don't find a suitable binary), as well as both a GUI version and 'terminal' version. For this tutorial it won't matter which version you use since I won't cover any of the specific GUI options and I'll cover the differences between the different OS' as good as possible.

The first steps

So you've gotten your hands on Vim and are ready to try it for the frist time? Good. To make things easier in the future you should add the path to the vim-executable to your $PATH. This isn't necessary if you did a standard installation on *nix since the executable file has been placed in the $PATH. On a Windows machine it is a little work, but it ins't that hard (search Google for how to do it). Once that is done you're ready to start Vim. The magical command to use is 'vim' if you're on a *nix machine, on a Windows machine the commmand is 'gvim.exe'. If you want to use the GUI in the *nix machine all you have to do is add a '-g' option at the end of the command, so the new magical command becomes 'vim -g'. On Windows the GUI version is started by default.

Vim velcome screen
Figure 1: VIM Welcome Screen

The first screen that greets you should look something like this. You can just ignore the text there for the moment, I'll come back to what those commands do. The little square in the top-left corner shows where your cursor currently is positioned. The tildes bellow symbolize that those lines doesn't exsist in the current file, they are only show there to 'fill the window'. Now you're probably thinking that it is just to start typing whatever text you might have in mind, but it isn't that easy.

One of the things that makes Vim as powerful as it is the fact that the program has different modes. There are six different modes available. The ones I'll introduce you to in this tutorial are Normal mode (the one you're in right now), Insert mode, Command mode and Visual mode.

There is a lot of ways to enter Insert mode, but the "easiest" is by pressing i (i for insert text). An important thing to notice when issuing commands is that Vim is case sensitive, so i isn't the same as I. You're now in Insert mode and you can start typing text like in any other text editor except for one little detail. Vim will not insert a line break when you reach the end of the 'screen width' even though the cursor will move to the line bellow it. To insert a line break in Vim you have to press <Enter>. It is easier to see where there are line breaks when you turn line numbering on, something that is explained later on under 'Configuring Vim'.

To get back to Normal mode you press <ESC>. A nice thing to know is that if you're ever unsure what mode you're currently in you can just press <ESC> to get back to Normal mode. If you press <ESC> while in Normal mode the window will either blink or you'll get an anoying beep from the computer, so now harm done there either.

Another way to enter Insert mode is to use the a command (a for append). At first glance you might think that they do the same, but the truth is that i starts inserting the text in front of the cursors current position, while a start inserting the text behind the cursor.

Moving around

You've now written a litte text. After a couple of lines you notice something you want to change in what you've previously written. The most natural way to do this for those not used to Vim would be to move the cursor there using the arrows, remove what is there using backspace or delete and then write what is supposed to be there. But as you might suspect, the most efficient way of doing it in Vim is different.

First you enter Normal mode by pressing <ESC>, then you move the cursor to wherever you want it to be. To move the cursor you shouldn't use arrow keys, but you should these keys: h to move left, j to move down, k to move up and l to move right. These are the standard movement keys in Vim. The reason you should use these keys instead of the arrow keys are that they are allready under your fingertips when you're typing so you won't have to move you hand. On some keyboards the arrow keys are also placed on peculiar places, so it is easier to not use them since you're hand won't have to search for them. It migth not seem like much, but if you consider that you might move the hand from the letters to the arrow keys a couple of hundred, if not thousand, times a day that sums up to be a lot of 'miss-used' energy. It also reduces the amount of the stress your wrist is exposed to since it won't be moving as much.

It might be difficult to remeber these keys in the beginning. One way to memorize them is; h is on the left, j is a hook down, k points up and l is on the right. Writing it down on a post-it note and placing it on your monitor might not be a bad idea either.

One of the powers of most commands in Vim is that you can repeat the command n number of times by typing n+command. So to move the cursor three lines down you would type (in Normal mode) 3j. That tells Vim to execute the j (move cursor one line down) command three times. This way you can easily move around the file, covering big distances with a single command.

There is also a lot of other commands for moving around. To jump to the beginning of the next word you use the w command. This command accepts a number in front as well, so 3w would move the cursor to the beginning of the third word.

Another way of moving around that is very nice to know when programming is the % command. What this command does is find the (),{},[], /* */ under the cursor (Vim also checks a couple of other pairs, but these are the most used ones), if none of them is under the cursor it uses the next one on the same line, and moves the cursor to its match. That might be a little hard to understand the first time around, so I'll give you an example.

A simple class
Figure 1: VIM Welcome Screen

On this image the cursor is placed over the first 'o' in classFoo. If I now press % the cursor will jump to the last }. This is because Vim first checks if the character beneeth the cursor is one of the allowed item, and since it isn't it moves along the line until it finds one. The first one it finds is the { at the end of the line. Vim then moves the cursor to the matching item. This is a nice way to check if the clause is closed where you want it to close, because if it isn't closed you'll get a a little beep from the computer (or the screen will flash) and if it is closed, but at the wrong place you'll see it since the cursor will be moved there. There are other ways as well to check if a bracket is closed, but that will be left for another tutorial to cover.

A movement command that I use a lot is f, and it's twin F. f moves the cursor to the next occurence of the character you type after f. So if you type fa the cursor will be moved to the next 'a' in the document. F is almost identical except that it moves the cursor to the previous occurance of the character.

Other movement commands that are very nice to know are the $ and ^ commands. The $ moves the cursor to the end of the line, while ^ moves the cursor to the beginning of the line. Those familiar with regualar expression probably recognise these as the signs used for the beginning and end of a line.

The last movement command that I'll cover in this tutorial is the G command. Preceded by a number it moves the cursor to the beginning of that line. If you don't add a number in front it will move the cursor to the beginning of the last line in the file.

Deleting stuff

To delete a character you place the cursor over the character and in Normal mode press x. This will delete the character currently under the cursor. The reason x is used is from the old typewriter days when you typed xxxx over the word you wanted to delete. It is also possible to add a number in front of this command, so 4x would be the same as if I had typed xxxx.

Deleting large amounts of text this way is cumbersome. Vim has therefore introduced another way of deleting things as well.

What I'm taking about is the d command (d for delete). The easiest use of the d command is to simply press it twice (dd). This will delete the line you are currently on.

If you press d then move the cursor with one of the movement commands that I covered earlier you will delete everything that the cursor passes over. So if you press dj you you will delete the line you're on and the following line. To only delete the line you're currently on you use the dd command. To delete a whole class enclosed in you could place the cursor at the beginning of the class declaration (for example the 'c' in class on the previous picture) and then type d%. This would first move the cursor to the first { and then move it to the matching }, and since that is done in one motion everything it passes over would be deleted.

Undo and Redo

Now that you've started deleting stuff it might happen that you accidentially delete something that wasn't supposed to be deleted. Despair not, Vim has both an undo and a redo command. The undo command is placed under the u-key while the redo function is accessed through CTRL-R (when using CTRL the case of the following letter is irellevant, so CTRL-r is the same as CTRL-R). By default Vim has stores the last 1000 changes in memory.

Copy and Paste

As with everything else in Vim there are numerous ways to copy and paste things. One way of doing it is first delete the the text with one of the delete commands I showed you earlier. You can then paste whatever you deleted back into the text with the p or P command. p for put, not paste as you would have thought. The reason for this is that it acctually takes things from a registry and puts it into the text, but that part will be saved for another tutorial to explain. The difference between them is that p puts the text after the cursor, while P puts the text before the cursor. If you have deleted a whole line (or more) the p command will put the text on the line bellow your current one, while P will put it between your current line and the line above.

When you type your brain is often a couple of steps ahead of your fingers, so you end up with typos like teh instead of the. An easy way to fix this in Vim is to put the cursor over the 'e' and then press xp. What this does is remove the character under the cursor (in this case the 'e') and place it after the next character. So teh magically becomes the.

It is also possible to copy/paste text without deleting it first. You do this with the y+motion command (y for yank). For our simple purposes the y command works just like the d command, except that it doesn't delete the text. Once you've yanked the text you can put it back in with either the p or P command. One thing that might be akward for the beginner with this command is that it doesn't give you any visual clue about what text has been yanked. So you'll for example press y4j to yank the four letters to the left of your current posision, but after you've pressed them nothing will happen. This is ok, Vim has stored the text in memory, it just doesn't bother telling the user about it.

Many users prefere to see what text they are copying, so that is also possible to do in Vim. To do this one first has to enter Visual mode. This is done by pressing v while in Normal mode. There are acctually three different Visual modes available, but I'll only talk about one of them here. By default you won't get any message that anything has happened, even though you have entered Visual mode. If you know move your cursor around you'll see that the text you pass over becomes marked. You can now do operations on the marked text, for example delete it (d) or copy it(y).

Search and Replace

The search and replace functionality of Vim is very powerful. One of the reasons for this is that you can use regular expression when searching and replacing text.

To start searching you type /. You will now see a / at the bottom line of the screen and the cursor has been moved to the spot behind it. You can now type your search criteria behind the / and when you're done you press enter to let Vim start the search. Vim will now search forward from the cursors position and stop once it finds a match. If the match it found wasn't the one you where looking for you can use the n command to repeat the last search. Vim will now contiune searching through the document, once it reaches the bottom of the file it will jump to the top and continue there.

If you want to start the search backwards from the cursors current postion you replace the / with a ?. It is also possible to 'turn the current search around' without having to retype it. Lets say you start searching forward for the word 'web'. The search command would then look something like /web. You press n a couple of times to move the search along. If you now realise that the place you wanted to reach was the previous hit, you can turn the search around with the N command. What this does it repeat the last search, but replace / with ? or vica versa.

But what if you want to search and replace something? This isn't much harder than searching. Instead of starting with a / or ? you now start with a :. There wil now be a : at the bottom of your screen, with the cursor behind it. The mode you're now in is called Command mode, I'll cover some more uses of this mode later on. The first thing you have to do when starting a search/replace is to specify the range of it. The two easiest to remeber ranges are: n1, n2 (which ranges from line n1 to line n2) and % (which cover the entire file). So if you want the search/replace to cover the entire file your bottom line should look something like : %. The space between the : and the % is just there for easier reading, you don't need to type it. What follows this is s/<searchpattern>/<replacepattern>. This is the easiest form of search/replace available. If you have a text and you want to replace every occurance of 'Pippin' with 'Peregrin' the search/replace string would look something like : %s/Pippin/Peregrin.

Loading, saving and quitting

When you start Vim you can start it with a file allready loaded. The way to do this is to add the path and filename behind the executable when you start Vim. If you've allready started Vim and want to load a file you can use the : e <filename> command.

If you were editing another file when you decided to load a new file, the first file you were editing will be put into a buffer. To view which files are in the buffer use the : buffers command. The number in front of the filename is that files current 'buffer number'. To switch between the various files in the buffer you use the : n buffer command, where n is the files 'buffer number'.

To save the changes you've made to a file you use the : w command. This wil write the changes to the file without changing the file name. If you want to save the new file under a different name you would add the new file name behind the w command, for example : w new_file.txt.

Quitting Vim is done with the : q command. If you've done some changes to the current file and you try to quit before saving them you'll get an error message saying soemthing like 'changes done since last buffer save'. If you're sure you want to quit before saving you add an ! behind the command so the quit command would become : q!. What that one does is tell Vim that you know that it will cause a warning, but you want to do it anyway.

Configuring Vim

Most of Vim's configuration can be done through the Command mode. To enter this mode you type a : when in Normal mode. This will put a : at the lower left corner of the window and place your cursor behind it.

When coding it is very nice to see what line you're currently on. This can be accomplished in Vim by typing :set nu, nu is short for number. That command wil turn on line numbering, and if you type it again line numbering will be turned off.

Indention is also a handy tool when programming. To set how much each tab indents the text you can use the :set tabstop=n to set the tab size to n. If you change tabstop from the default 8 you should also change shiftwidth to the same number. This is done with :set shiftwidth=n. Shiftwidth is used for autoindention and some other functions in Vim.

There are three different types of autoindention available in Vim by default. These are 'cindent', 'smartindent' and 'autoindent'. 'cindent' uses standard c indention rules. 'smartindent' and 'autoindent' don't follow any specific indention rules, but mainly keeps your current indention level when you start a new line. There are some differrences between 'smartindent' and 'autoindent', but I won't cover them here. To turn one of the indentinos schemes on you type :set cindent (change cindent with the indention 'rules' you want).

Another very nice option to know is the :set nocompatible. This will allow you to use Vim commands that are not compatible with the old Vi. Another very good thing about this command that you'll notice at once is that when you're in any mode, except Normal mode, there will be a little note in the bottom-left corner telling you which mode you're in. When you're in Insert mode, it will say -- XIM INSERT-- and likewise for visual mode. In Command mode it doesn't say anything since the cursor will then be down there behind a colon.

If you tire of writing these commands everytime you start Vim you can make a file called .vimrc (_vimrc on Windows) in your homedirectory (placed in vim's install path on Windows machines). This file will be read every time Vim starts so if you put the commands there, without the : in front, you'll have Vim ready configured at startup. A basic .vimrc script with the commands that you've learnt so far(pluss two others that are very nice to know) might look something like this:

" Basic .vimrc file " Everything behind a double-quote is treated as a comment set nocompatible set nu set tabstop=4 set shiftwidth=4 set cindent set ruler " show the line, column number of the cursor on the bottom line set showcmd " show partially finnished commands

For more examples of what a .vimrc file might contain you should check out the example file that came with your vim installation.

That's all Folks

An important detail to remeber is that the help file of vim is very comprehensive and covers almost any question you might have. To access the help file type :help command. The command at the end is the command you might want help about. If you omit a command you'll be taken to the index help page.

I know that it can be a lot to remeber all these commands in the beginning, so I've created a short list with the commands that we've been through (pluss two new ones!) with a short explanation. Keep a copy of the table beside your keyboard until you've grown accustomed to them. It will save you alot of time from having to check out the commands in thelp file or checking this tutorial again.

Vim Commands
Command Explanation
<ESC> Exit current mode and enter Normal mode
i Start inserting text in front of current cursor position
a Start inserting text after current cursor position
I Start inserting text at the beginning of the current line
A Start inserting text at the end of the current line
h, j, k, l Vim's arrow keys
% Move to matching bracket ({}, (), [] etc.)
fn Move to next occuranse of n
Fn Same as f, except moves to previous occuranse
$ Move to end of line
^ Move to beginning of line
w, W Move to the next beginning of the next word
nG Move to beginning of line n, with a number in front it moves the cursor to the last line
x Deletes the character under the cursor
dmotion Deletes everything that the cursor passes over during the motion
ymotion Yanks(copies) everything that the cursor passes over during the motion
p Put what was last deleted or yanked behind the current cursor position
P Same as p, but puts it in front of the current cursor position
u Undo
CTRL-r Redo
/<pattern> Search for <pattern> forward from the cursor position
?<pattern> Search for <pattern> backward from the cursor position
n Repeat previous search
N Repeat previous search, but change the direction of the search
: <range> s/<pattern>/<substitute> Search for <pattern> in <range> and replace it with <substitute>
: e <filename> Open <filename>, if no filename is specified it opens a new file
: w Save changes to the current file
: q Quit Vim

That's it for now. You've seen some of the power hidden beneeth Vim's simple looks as well as learnt enough to use it. For more information about Vim look in the help files, do some googling or ask on the discussion board.