Tuesday, December 06, 2011

A Quick Introduction to Vi (GVIM) for Programmers

Vi is an awesome editor. A bit of a learning curve, but this little tutorial will get you going.

[Important note: Vi is not an IDE. Two developers in a row made some very strange comments about Vi and compiling code. Vi is just an editor.]

An Editor of Two Minds (or Modes as it were)

Vi has two modes: typing mode and command mode. Command mode turns the entire keyboard into a bunch of function keys.
Vi starts in command mode. To switch into typing mode press (for example) the i key (i for input). To exit typing mode (and go back to command mode) press Esc.
When in typing mode, type, as normal. This is the behaviour most people are used to, it is command mode that is somewhat unique to Vi.

Command Mode

Command mode turns the entire keyboard into function keys: not keys with which to enter text.
Some frequently used commands:
Command Key Result
i switch to typing mode; start at the current cursor position
Esc exit typing mode
a switch to typing mode, start after the current cursor position
d delete the character at the current cursor position
D delete from the cursor to the end of the line
dd delete the current line
dG delete from the current line to the end of the file
. repeat the last edit
[Note: eventually you will realize this command is bloody awesome and one of the main reasons to use vi]
o open up a newline (after the current cursor position) and enter typing mode
j move the cursor down a line
k move the cursor up a line
h move the cursor left
l move the cursor right
u undo last edit (this is repeatable command)
G go to the bottom of the file
Y yank; copy the current line into the buffer
3Y yank 3 lines into the buffer (note many command can be prefixed with a count)
p put the contents of the buffer (as line(s) after the current line
M move the cursor to the middle of the current screen
:2,9 s/in/out/ from lines 2 to 9 substitute the first occurrence of in on each line with out (press Enter to execute)
The best vi editors:
General: vim.org
For Visual Studio: viemu.com
For Eclipse: viplugin.com
For NetBeans: jvi.sourceforge.net/