Welcome To My Blog
here i will try to collect as much as i can of articles and
toutorials talking about linux and open source software

if you want to share me this and be an author Contact me
subscribe to RSS or subscribe to Email Newsletter

Beginner's Guide to the Vi editor

Posted by ahmedhamdy_27 Tuesday, December 15, 2009

Buzz It

Beginner's Guide to the Vi editor

Topics covered in this guide:

  1. Getting into Vi
  2. Typing In Your Text
  3. What the $!#^*& happened??!!
  4. Inserting Text
  5. Deleting, Copying and Changing
  6. Single Key Movements
  7. Sample Use of the Single Key Movements
  8. Searching and Replacing text
  9. GETTING OUT OF VI:

I. Getting into Vi

Suppose that you want to write a paper about guitar music. First, you need to think of a name for your file. The name can be anything descriptive, but must NOT have spaces in it, and as a rule of thumb should only use letters and numerals. In this case the name "guitar" will do just fine. At your Unix prompt (usually a $ or % character), type:
vi guitar RETURN
that is the word vi followed by your chosen name and hit the RETURN key. If the file is new, vi responds by telling you so, and by giving you a column of ~ (tildes) in the first column. The blinking cursor is placed at the beginning of the file.
As an important sidenote, there is a section near the end of this article titled, "GETTING OUT OF VI." Do NOT simply turn off the terminal to get out of vi, you should follow the instructions in that section.

II. Typing In Your Text

Whenever you are using vi, you are in one of two modes: "insert mode" or "command mode". When you are in "insert mode" the keys you press cause those characters to be typed into your file. When you are in "command mode" the keys you press cause actions like moving from place to place in your file and making changes to what you have typed. When you first start vi (like right now), you are in "command mode". Since your file is empty there isn't anything interesting you can do except switch to insert mode so you can begin typing.

III. What the $!#^*& happened??!!

VI allows you to perform many tasks with very few keystrokes. This is good for those who get tired of typing lots of keystrokes to perform editing operations. This can be bad for those who make lots of typing mistakes. I say "can be bad" because VI allows you to recover from typing mistakes by un-doing operations that insert/delete text in a document. Operations that alter a document are explicit in VI. There is a definite starting point, and a definite ending point. This is what allows VI to "know" how to undo what you last did. As long as you only make one mistake at a time, you can undo that mistake by typing a 'u' (for undo) keystroke while in COMMAND mode. This is perhaps the most appreciated feature of VI. There is another key stroke, 'U', which also allows you to Undo mistakes. It will Undo all changes made to the current line, providing the cursor has not left that line since the changes were made.
Undo commands:
  • u — undo last command ONLY
  • U — undo all changes to the current line you are working on

IV. Inserting Text

VI incorporates several methods of inserting text into a document. There are three different methods you can use while you are in COMMAND mode. Typing an 'i' (for INSERT mode) keystroke allows you to insert characters into the document at the left edge of the cursor. As mentioned above, typing the (or escape) keystroke allows you to exit (or escape) from INSERT mode back into COMMAND mode. Since there are many different places where a person might want to insert text, there are keystrokes other than 'i', that place the editor directly into INSERT mode, after moving the cursor. These are outlined below.
Insert commands - These are the only commands which will allow you to enter text before the BEGINNING of a line.
i Inserts text to the left of the cursor.
IInserts text at the beginning of the line, no matter where the cursor is positioned on the current line.
Append commands - These are the only commands which will allow you to enter text AFTER the END of a line.
aBegins inserting after the character (append) on which the cursor is positioned.
ABegins inserting at the end of the current line, no matter where the cursor is positioned on that line.
Open commands
oBegins inserting text on a new, empty line that is opened for you, below the current line. This is the only command that will allow you to insert text BELOW the LAST line of the file.
OBegins inserting text on a new, empty line that is opened for you, above the current line. This is the only command that will allow you to insert text ABOVE the FIRST line of the file.
There are other commands that place you in INSERT mode. These commands are used to perform substitutions of text. That is, the deletion of old text and the insertion of new text, all in a single operation. These commands will be discussed later because the are actually variations on the change command.

V. Deleting, Copying and Changing

The next three operations we will discuss will be deleting, copying, and changing. These three will be discussed together because the methods of describing the text that these commands operate on is identical.
There are well over 30 different ways that you can tell VI to move the cursor to a new location in the document. These movements can also be used to describe sections of the document that you wish to perform the delete, copy or change operation on. Typically, you will type a single keystroke which describes the type of operation you wish to perform, (e.g. 'd' to delete), then you type the cursor movement command that will tell vi on which piece of text you would like that operation to work. For example, if 'w' moves one word forward, 'dw' will delete a word, while 'cw' will change a word.
These editing commands are outlined below:
Figure 1.
dDelete text. (see explanation above)
yCopy text (that is, yank it into a holding area for later use). (see explanation above)
cChange text from one thing to another, which you will type. (see explanation above)
!Filter text through a program.
<Shift a region of text to the left.
>Shift a region of text to the right.
In addition to the functions described above, each of these keystrokes when doubled become editing commands which operate on entire lines. For example, '3dd' deletes the next three lines including the current line, while '2yy' yanks a copy of the next two lines including the current line into a paste buffer.

VI. Single Key Movements

Following one of the commands identifying keystrokes listed in Figure 1 above, you must tell VI on which portion of the document to perform the operation. This is done by typing a keystroke that indicates a movement command. Most of these are outlined below. The more complicated movements will be described later on.
hMove cursor to the left one character.
lMove cursor to the right one character.
jMove cursor down one line.
kMove cursor up one line.
^Move cursor to the beginning of the line.
$Move cursor to the end of the current line.
1GMove cursor to the first line of your document. Other numbers will move to the line specified by number (ex. '50G' goes to the 50th line).
GMove cursor to the last line of your file.
CTRL UMove cursor up in file 12 lines. Hold down the key marked CTRL (stands for "control") and type 'U'. CTRL is like another shift key.
CTRL DMove cursor down in file 15 lines.
wMove cursor forward to the next word, stopping at punctuation.
WMove cursor forward to the next word, ignoring punctuation.
eMove cursor forward to the end of the word, stopping at punctuation.
EMove cursor forward to the end of the word, ignores punctuation.
bMove cursor backwards to the previous word, stopping at punctuation.
BMove cursor backwards to the previous word, ignores punctuation.
HMove cursor to the top line of the screen, (as opposed to the top of the document which may not be the same place).
MMove cursor to the middle of the screen.
LMove cursor to the last line on the screen.
%Move cursor to the matching parenthesis, bracket or brace. Great for debugging programs.
(Move cursor to the beginning of the previous sentence (where a punctuation mark and two spaces define a sentence).
)Move cursor to the beginning of the next sentence.
{Move cursor to the beginning of the current paragraph.
}Move cursor to the beginning of the next paragraph.
;Repeat the last f or F command (see below).
Almost Single Key Movements
The following key movements use additional information or input. That is, although they are single key movements their correct operation depends on what came before or what follows.
' Move cursor to a previously marked location in the file. (ex. ma marks the location with the letter 'a', so 'a (apostrophe 'a') moves back to that location).
f Find the character corresponding to the next keystroke typed. Move the cursor to the next occurrence of that character (on the current line only).
F Same as 'f' but movement is backwards.
You probably will not adopt the immediate use of all of these movements, but it is possible to gain proficiency in their use only by using them.

VII. Sample Use of the Single Key Movements

Perhaps some sample uses of these movements will make their use a little more obvious. Typically, a VI manual resolves to give the reader a list of the most common keystroke combinations, without trying to describe the real reasoning behind the keystrokes. This is part of the reason that VI seems so foreign to some people, they never discover the relationship of all the keystrokes to one another. However, since I have outlined the basic relationship of the keystrokes, I feel that I can provide a similar chart without causing much confusion. The notation means that you may type an optional number before the command to indicate the number of times you would like that command to be repeated. e.g. 5dw will delete five words, 35dd will delete thirty five lines, etc.
Some handy dandy commands
x Delete character(s) to the right of the cursor, starting with the one beneath it.
r Replace the character under the cursor with the next character you type. This can be a very useful command. If you wanted to split up a line between two words, you might put the cursor on the blank space before the word you would like to go on the next line and type r . This would replace the space between the words with a carriage return and put the rest of the line onto a new line.
J Join lines; the opposite of the line splitting operation above. This will join the current line with the next line in your file. Also very useful.
R Replace lines; puts you in INSERT mode but types over the characters that are already on the current line.
p Paste line(s) you deleted (or yanked) back into the file. This is an excellent command if you want to move a few lines somewhere else in your file. Just type '3dd' to delete three lines, for example, and then move to where you want those lines to be and type 'p' to paste the lines back into your file below the cursor.
. The period "." command repeats the last text modification command, whatever it may have been (insert, deletion, etc).
:r filename RETURN Read a file into the current file being edited. The file be added gets placed below the current cursor position. Please note the colon ":" before the "r" in this command.
CTRL L Redraw the screen. If somebody writes to you while you are in the middle of vi and junk appears all over your screen, don't panic, it did not hurt your file, but you will have to hold down the CTRL key and type 'L' to clean it up (CTRL L).
Common Keystroke Combinations
d$ Delete (including the current character), to the end of the line.
d^ Delete (excluding the current character), to the beginning of the line.
dw Delete a word(s), stops at punctuation.
dW Delete a word(s), ignoring punctuation.
de Delete to the end of next word.
dd Delete a line(s).
dG Delete from the current line to the end of the document. CAREFUL: Slightly dangerous.
dH Delete from the current line to the line shown at the top of the screen.

VIII. Searching and Replacing text

Search and replace are another set of commands that can be extremely useful in word processing. Unfortunately, they are usually somewhat confusing to understand and use. In this section, I will give some examples of some useful search and replace commands. A subsequent help article (coming soon) will contain a more complete guide to understanding and using the vi search and replace commands (sometimes called "regular expressions"). You must be in COMMAND mode to use these commands. When you type the first character of the command (":", "/", "?") the cursor should jump to the last line of the screen and the rest of the command will appear down there. If this does not happen make sure that you have typed ESC first to get you into command mode and that you have typed the proper first character for the command.
Search and Replace
/the Finds the next occurence of "the". This will also find "their", "them", "another", etc.
?the Finds the previous occurence of "the".
n Repeats the last search command. Finds the Next occurence.
d/the Deletes until the next occurence of "the". This is to demonstrate how the delete prefix can be used with any cursor movement command.
:g/oldword/s//newword/gc This will find all occurences of "oldword" and replace them with "newword". The optional "c" at the end of the command tells vi that you would like to "confirm" each change. Vi will want you to type in "y" to make the change or "n" to skip that replacement. Great for spelling fixes.

IX. GETTING OUT OF VI:

To save your paper and exit vi, you should type:
ESC :wq RETURN
That is, hit the ESC key to make sure you are in command mode. Type the colon ":" and the cursor should jump to the bottom line of the screen. If the colon appears in your text instead, you probably did not hit ESC first. Next the "wq", which stands for Write and Quit, and finally hit RETURN. This will save your file, exit from vi and return you to Unix.
Side Note: It's a good idea if you are doing a lot of work on a file to periodically type "ESC :w RETURN" (without the "q") to save your latest changes without quitting. This is a precaution in case something seriously wrong happens to your file while you are editing, then you will only lose the changes since the last time you saved the file.
BAILING OUT OF VI: Imagine that it's 3:00am and you just accidentally deleted half of your thesis and it's due tomorrow at 8:00am... don't panic. If you are careful about how you leave vi, you can return your file to the way it was the last time it was saved. If you have been saving it periodically you may not lose much work. In a situation like this, where what you have in the editor is badly damaged and what you have in storage is much more valuable, what you want to do is to leave the editor without writing modifications on top of what is in storage. To leave the vi editor WITHOUT SAVING modifications, use this:
ESC :q! RETURN (does NOT save modifications)
You will lose all your changes since the last time the file was saved, but in special cases this will be better than living with the results of a serious editing error.

Blog Widget by LinkWithin
Add to Technorati Favorites
blog comments powered by Disqus
Loading...

BEST WAY TO SAY THANKS

Labels

ubuntu apache mysql backup gnome audio players compile kernel grub restore security themes web hosting 3d games Clonezilla centos cpanel database fun games gmail gzip kernel linux games mod_deflate monitoring tools music making open ssh recovery redhat reinstall grub rsync ssh * Apt-Get * Howto 3d acceleration AMANDA Ardour Bacula Duplicity E-Books Extract files from ISO FlyBack Graphics Card IP Failover and Web Cluste IP Failover and Web Cluster IPv6 Jokosher K9Copy KDE Karmic Linux Linux Set Date and Time Linux Tools Linux backup tools Linux commands Networking Nginx Open VPN Operating system PATH ReZound Remote Desktop Solutions for Linux Reverse Proxy Load Balancer SLAMPP Samba Sweep Time Vault Traverso DAW Ubuntu Tweak Webmin Windows vs Linux antivirus audi studio auto mount bash block ip block users blog editor boot caching check mail dangerous .caution dd deadly commands debian directory listing dns docks dvd easyapache error 18 fedora find fixing partitions table fork() bomb glxinfo hacking handbrake help image initrd install linux iptables jack jaunty lamp ldap lfs linus linux live linux vs windows log mac osx man mod_rewrite mount network boot ntfs open courseware open source books opengl openshot own distro packup php print in linux print over wireless ptr recompile redirect restore disk restore mbr reverse dns rip dvd screen server share desktop speed up linux spf ssmtp stream desktop swatch syslog syslog-ng top toutorials useful applications vi video editor vim vlc vmlinuz wallpapers whm xsplash

Recent Posts

archive

BEST WAY TO SAY THANKS