13 August, 2007

HowTo understand Vi ( Vim ) editor

"Vim (Vi Improved) is very powerful editor..."
It is true, I know, I like it. Vi is the best editor for the Linux/Unix console.

Have you tried to understand Vi?

Most people don't understand Vi, because they don't like console and command line, it is needlessly for theirs.
Vi is good for servers, embedded and non-GUI systems;
for admins, linux developers and gurus,
but not for normal people, at first look.

You may execute vimtutor in your command line in order to understand Vi.
Vimtutor is great tutorial.

Also Vi supports highlighting for many types of files.


I've created consolidated list of Vi commands and hot keys:

Navigation
h move cursor left
j move cursor down
k move cursor up
l move cursor right
i, INSERT edit mode
R replace mode
ESC normal mode
CTRL-g show filename, current location in the file and status
SHIFT-g goto the end of file
number+SHIFT-g goto to the line number
% goto the matching pair for brackets [, ], {, }, (, )
:syntax on switch text highlight on
:help command help for the command

Search
/ search text
n search text again
? search in the backward direction
SHIFT-N search text again in opposite direction
:set ic search ignore cases

Edit
x delete character under cursor
de delete to the end of word
dw delete to the end of word+space
d$ delete to the end of line
d^ delete to the begin of line
dd delete a whole line

ce,w,$,^ do the same as delete command, but also switch to edit mode

u undo the last command
U restore line to it's original state
CTRL-R redo the last command

p put the last deletion after the cursor
o,O open new empty line below/above the cursor and switch to the edit mode
a append text after the cursor
A append text to the end of a line


Replace
r+character replace character under cursor
:s/old/new replace old text with new text (once)
:s/old/new/g replace all old text with new text in the line
:s/old/new/gc replace all old text with new text in the line, but ask to confirmation
:%s/old/new/g replace all old text with new text in the file
:#,#s/old/new/g replace all old text with new text between lines in the range #,#

Common
number+command repeat command number of times (e.g.: 2dd deletes two lines, 5j moves five lines down)


File
:q! exit without changes
:w save file
:wq save and exit
:w filename save file as filename
:#,# w filename save part of file between lines in the range #,#
:r filename insert the contents of the file
:!command execute external command

This article is created in Vi!

There are some programs which syntax is partially compatible with Vi: ed, sed (stream editor) and others.
E.g.:
command cat file.txt |sed -e '1,10s/a/A/g' replaces all 'a' with 'A' from 1 to 10 line.

No comments: