Tuesday, May 17, 2011

Get started using VI

To start editing using VI, type vi filename at the command line.
In linux/Unix you can specify what type of file you are creating, thus

vi snake.py [enter]

will create a python file named snake.py automatically

VI has 2 modes: command and insert. In command mode, keys you press will not be output to the screen, instead you are able to move around, and to edit text pretty much which ever way you want



 In Command mode:
To move around
h - moves one character to the left
j -  moves down one line at a time
k - moves up one line at a time
l - moves one character to the right

To start editing 
a - enters insert mode, the character you type will go into the first position after the current cursor location
A - enters insert mode at the end of the current line. Think of a configuration file, the appended text will go after the current configure line
i - enters insert mode, replacing the current character where your cursor is located
I - enters insert mode, adding text at the beginning of the line. Add to the beginning of a file, leaving the current line intact

To save 
Press Escape, then colon (:), and the following sequence:
:wq saves and quit
:wq! force save and quit (in case of permissions conflicts)
:q! force quit without saving

Thus if you have the following example file:
# comment
# comment
add such and such repository local
add such and such repository universal
#add PPA

Then to enable the PPA line, navigate to it with h, j, k, l, and position your cursor on the #, press x to delete the character, then press Escape, and :wq to save and quit.
If you also wanted to add another line, then after deleting the # use l to move to the end of the line, press o and you will be in insert mode on a new line beneath the last line. When done, again press Escape and :wq to save and quit