Linux: Editing Text with the VI Editor

From ReceptiveIT
Jump to: navigation, search

Beginner's Guide to the Vi editor

Vi for the Masses Revised: October 2003.

Adapted from a paper by Gregg Wonderly, Oklahoma State University. Revisions made by Paul Zakian and UCSD Instructional Computing, AP&M 2113. Topics covered in this guide:

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.

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.

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 

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 <ESC> (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.
   I	—	Inserts 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.
   a	—	Begins inserting after the character (append) on which the cursor is positioned.
   A	—	Begins inserting at the end of the current line, no matter where the cursor is positioned on that line.
   Open commands
   o	—	Begins 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.
   O	—	Begins 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.

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.
   d	—	Delete text. (see explanation above)
   y	—	Copy text (that is, yank it into a holding area for later use). (see explanation above)
   c	—	Change 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.

   h	—	Move cursor to the left one character.
   l	—	Move cursor to the right one character.
   j	—	Move cursor down one line.
   k	—	Move cursor up one line.
   ^	—	Move cursor to the beginning of the line.
   $	—	Move cursor to the end of the current line.
   1G	—	Move 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).
   G	—	Move cursor to the last line of your file.
   CTRL U	—	Move 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 D	—	Move cursor down in file 15 lines.
   w	—	Move cursor forward to the next word, stopping at punctuation.
   W	—	Move cursor forward to the next word, ignoring punctuation.
   e	—	Move cursor forward to the end of the word, stopping at punctuation.
   E	—	Move cursor forward to the end of the word, ignores punctuation.
   b	—	Move cursor backwards to the previous word, stopping at punctuation.
   B	—	Move cursor backwards to the previous word, ignores punctuation.
   H	—	Move cursor to the top line of the screen, (as opposed to the top of the document which may not be the same place).
   M	—	Move cursor to the middle of the screen.
   L	—	Move 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.

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 <n> 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
   <n>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 <RETURN>. 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.
   <n>dw 	— 	Delete a word(s), stops at punctuation.
   <n>dW 	— 	Delete a word(s), ignoring punctuation.
   <n>de 	— 	Delete to the end of next word.
   <n>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.

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.

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.