This page will serve as a place to store my notes on using vi as a programming editor. And when I mean vi, I really mean vim, but these days I think it’s pretty safe to assume vi=vim. I’m placing these notes on the web in the hopes that it may help other programmers new to vi, as I currently am. I will update this page with information I find useful.

The Two Modes

The most important concept to understand about vi is that it has two separate modes - command mode and insertion mode. This originally struck me as rather cumbersome, and I found my self working nearly completely in insertion mode. You can get along like this. You can also write C++ code in Microsoft Word. There’s a really good reason for this separation - because command mode is separate, the commands are much simpler. For example, navigating around the document is really easy:

j - Move one row up  
k - Move one row down  
h - Move one column left  
l - Move one column right  
w - Move to the start of the next word  
b - Move to the start of the previous word  
e - Move to the end of the next word  
0 - Move to the beginning of the line  
$ - Move to the end of the line  
1G - Move to the beginning of the file  
G - Move to the end of the file  
% - Move cursor to matching bracket  

The jkhl commands may seem quite stupid. There are arrow keys after all. But if you know how to touch type, you’ll find that this really improves your productivity. It takes a bit getting used to, but it really pays off, in my opinion.

Like many commands, you can add a number before a navigation, so that 4j moves you four rows down.

Undo & Redo

u - undo last change  
Ctrl+R - redo  

Copy & Paste

v - enter visual selection mode. Moving the cursor will select text for later actions, such as:  
y - yanks the selected text. aka, copy  
yy - yanks the current line  
p - paste text  

Multiple Windows

:split filename \- split a window and open filename  
:vsplit filename \- split a window and open filename  

Running Shell Commands

:!make - executes a shell command, such as make  
:r !ls - executes a shell command and pastes the output into the file  

Search & Replace

/expression - Searches for expression  
:%s/expression/newtext/g - Searches for expression and replaces it with newtext  

Configuring The Environment

:set nu - shows the line numbers  
:set nonu - don't show the line numbers  
:colorscheme  \- changes the color scheme  
:set sw=4 - sets the tab size to be 4 spaces  

All these commands can be placed in ~/.vimrc

References

  1. Yolinux is always a good source
  2. Run vimtutor for a good hands-on tutorial

Updated: