< Day Day Up > |
As mentioned earlier, the vi editor is the most popular editor in the world of UNIX/Linux programmers. Even after Emacs was introduced, many programmers still continued to use the vi editor. There is one simple reason for that: One who masters the vi editor will find it very difficult to forget. However, the learning (and mastering) takes longer than other editors. In this section, we will focus on how we best can use the vi editor by discussing the most commonly used commands. All the possible options and features are not going to be discussed here, because the discussion is aimed at providing a good quick-start to a person new to the vi editor. Once users understand the concepts and memorize the commands, they can further explore more commands. In addition, a small set of commands is always easy to remember. More information in this regard may be obtained from the manual pages of the command.
The vi Editor is invoked by the command vi at the command prompt. If we provide a file name along with the command, it will attempt to open the file if it already exists; if not, it will create and open the file for entry. Along with the file name, we may also provide the full path or absolute path; however, if the path provided with the file does not exist or if we don’t have write permission to the directory where the file needs to be saved, we will not be able to save the file, although we will be able to edit it. A few ways to invoke the vi editor are provided here. In these examples, the $ symbol is assumed to be the shell prompt.
$ vi <file name(s)> $ vi new_file1.txt $ vi edit_demo/new_file2.txt $ vi /edit_demo/new_file3.txt $ vi
The first line provides a general form of the command. You may open multiple files with single execution of the command. When opening more than one file at a time, there should be at least one space or tab between the file names (as in <file1> <file2>). If a comma is used, it is considered as part of the file name. Multiple file names may also be specified by using wild card characters (as in <file1*> or <new??file2>). Whichever method is used, when multiple files are opened, the editor keeps the files in a queue and presents one file at a time. After closing the current file (either saving or discarding the changes), the next file is automatically presented.
The second line opens the file in the current directory. The third and fourth line open the respective files in the specified relative directory (from current directory) and absolute directory, respectively. In all cases, if you do not have write permission, you will not be able to save the file. If you do not specify a file name with the command—as in the fifth line—the editor is opened with an empty buffer. Later, you can provide the file name while saving.
After the file is opened for editing, the editor functions mainly in two modes: in the command mode, and in the insert mode. When the file is opened, the editor is in command mode by default. When you type the ‘:’ character, a separate command line is displayed at the bottom of the current file and accepts specific line commands. This mode of commands is also known as ex mode commands because ex is a line editor versus vi, the screen editor, and forms the foundation of the latter. Figure 3.1 displays a screenshot of the vi editor in ex command mode.
From the figure, it is clear that the ex command mode shows the : command prompt. Any of the ex editor commands may be executed in this command mode. The other command mode is known as the vi command mode, which is exclusive to the vi screen editor. To summarize, vi operates in three different modes. Two of them are command modes—the ex command mode and the vi command mode—and the third mode is the insert mode.
The editor is automatically closed when the file is closed (either saving or discarding the changes) and there are no more files in the queue being processed by the editor. The commands to save changes, save and quit, and save without quitting are all ex commands. The command prompt for the ex commands is the colon character, and hence all the ex mode commands will be preceded by the colon : character. The ex mode is invoked by pressing the colon ‘:’, and then the command should be typed and the ENTER key should be pressed. Before attempting to switch to the ex command mode, the file should be in vi command mode. At the ex command mode, the command x saves the file and quits. It is also equivalent to type ‘wq’ to save (or write) the file and quit. To just save the file without quitting, ‘w’ is to be typed at the ex command mode, while typing ‘q’ attempts to quit without saving. But when an attempt is made to quit without saving, the editor checks if there were changes made to the file after the last time we saved it. If there were no changes after the last save point, the quit without save will work, and the editor closes the file. But if there were any changes made and not yet saved, a message is displayed accordingly, and one of the two actions should be performed; either type ‘wq’ to save and quit or ‘q!’ to quit forcibly without saving. The ! character after the q indicates the editor that the changes should be discarded and the file should be closed. To save the current file with a different file name type ‘w <new file name>’ at the ex command prompt. In this case, the file is saved with the new name. If a file already exists with the name specified as the new file, then a message will be displayed accordingly, and we can override this situation and forcibly save the file with the new name by typing ‘w! <New file name>’. Once the file is saved with the new name, the new file becomes the currently opened file in the editor.
In vi editor, only one mode is active at any time, either the command mode or the insert mode. When in command mode, you cannot enter any text or change the existing text. In order to enter or change the text, you need to switch to the insert mode. Typing any of the insert commands in Table 3.1 will switch to the insert mode. Always press the ESC key to switch to the command mode.
Command Character |
Command Description |
---|---|
i (lowercase) |
Start inserting characters from (before) the current cursor position in the file. To insert characters somewhere in the middle of the file, the cursor has to be navigated to that position, and then type lowercase ‘i’. The mode is changed immediately, and any characters typed from then on will be added in the text. As an example, consider the following line of text as existing in the file and the file in command mode. |
It is going to be a beautiful_tomorrow. |
|
We realize that something is missing after the word ‘beautiful.’ So we navigate the cursor to the position where it is shown in the above line (navigation commands are discussed in the following section). The underscore character represents the position of the cursor. We intend to type the word ‘day’ after ‘beautiful’ with a space character separating the two words. Start typing the characters ‘i day’. The character ‘i’ switches to the insert mode, and then the characters ‘day’ are inserted there, making the line look as shown here. |
|
It is going to be a beautiful day_tomorrow. |
|
Press the ESC key to switch back to the command mode. |
|
a (lowercase) |
Starts inserting text after the current cursor position in the file. In the previous example, typing ‘aday ’ would also give the same result. Notice that the space character is given after the word ‘day’, because the command ‘a’ starts inserting after the current cursor position, which is a space character. |
I (uppercase) |
Starts inserting before the beginning (or before the first character) of the current line. If you are somewhere in the middle of a line and want to enter something before the beginning of the line, this command saves you navigation time, and directly jumps to the line’s beginning for entry. |
A (uppercase) |
Starts appending the current line (obviously at the end). This command also saves navigation time. |
r (lowercase) |
Replaces the character at the current position with the character that is typed immediately after the ‘r’. After replacing the character, the file is automatically switched to the command mode. |
R (uppercase) |
Starts replacing characters from the current cursor position, until the mode is switched back to the command mode by pressing the ESC key. |
o (lowercase) |
Adds an empty new line below the current line, and the cursor is positioned at the beginning of the new line. Any characters entered after the ‘o’ command are typed in the new line until the ESC key is pressed. |
O (uppercase) |
Adds an empty new line above the current line, and the cursor is positioned at the beginning of the new line. Any characters entered after the ‘O’ command are typed in the new line, until the ESC key is pressed. |
Once changed to the insert mode, any character typed is used only as text in the file and not as a command. It is important to understand that the same character may work as a command in the command mode while being considered as a text character in the insert mode. Also, the commands that switch to the insert mode are all single-character commands. This concept can seem tricky and confusing to beginners, but once you are used to it, this is a very convenient editor.
While the file is in insert mode, there are a few commands that can be used in the edit process. However, these commands are combined with the CTRL key, because in the insert mode, single character commands are disabled and whichever character you type is used as part of the text being edited. Keeping the CTRL key down, press the ‘J’ key (case-insensitive) to break the current line at the cursor position and move everything onwards from the cursor position to the next line. This is equivalent to pressing the RETURN key while in insert mode. Similarly, CTRL+I will insert a tab at current cursor position. Both these commands do not switch from the insert mode.
The navigation commands are as important as insert mode commands. These commands provide you the opportunity to quickly move across the file back and forth so as to position the cursor wherever you need it. Table 3.2 describes the navigation commands most commonly required by the vi user.
Command Character(s) |
Command Description |
---|---|
h (lowercase) |
Move the cursor position left by one character. If the cursor is at the first position of the current line, then no action takes place. On a Linux desktop, the left arrow key also does the same thing. |
l (lowercase) |
Move the cursor position right by one character. If the cursor is already at the last character position in the line, then no action takes place. The same result is achieved through the right arrow key. |
k (lowercase) |
From the current cursor position, move the cursor up by one line. While moving to the line above, the relative position within the line is preserved. For example, if the cursor is currently positioned at the fifth character in the fourth line, then the command k moves the cursor to the fifth character position in the third line. The up arrow key can do the same thing. |
j (lowercase) |
From the current cursor position, move the cursor down by one line. The command j also preserves the relative position of the cursor within the line. This can also be done by using the down arrow key. |
w (lowercase) |
Move the cursor to the first character in the next word (forward motion). The scope of the command is to the end of the file from the current position. It means that if the cursor is at the last word in a line, then the command w attempts to move the cursor to the first word in the next line. If there are no more words following the current word in the file, then no action takes place. Words are separated by whitespaces and tabs. In addition, special characters such as the period ., comma ,, question mark ?, and exclamation mark ! are also treated as separate words. |
b (lowercase) |
Move the cursor to the first character in the previous word (backward motion). The scope of the command is to the beginning of the file from the current position. It means that if the cursor is at the first word in a line, then command b attempts to move the cursor to the last word in the previous line. If there are no more words preceding the current word in the file, then no action takes place. Words are separated by whitespaces and tabs. In addition, special characters such as the period ., comma ,, question mark ?, and exclamation mark ! are also treated as separate words. |
W (uppercase) |
Move the cursor forward by word, very similar to the command w, except that the special characters are treated as part of the word with which they are attached. If there are spaces on both sides of the special characters, then they are treated as separate words. For example, in the text ‘apples, oranges, and other fruits …’ the comma is considered as part of the word ‘apples,’; however, if you put a space between the word and the comma as in ‘apples ,’ then they are treated as two words. |
B (uppercase) |
Move the cursor backward by word, very similar to the command b, and the rules are very similar to the command W. |
( |
Move the cursor to the beginning of the current sentence (based on where the cursor is positioned currently). Separation of sentences is identified by the period character .. |
) |
Move the cursor to the beginning of the next sentence (based on where the cursor is positioned currently). Separation of sentences is identified by the period character .. |
{ |
Move the cursor to the beginning of the current paragraph (based on where the cursor is positioned currently). |
} |
Move the cursor to the beginning of the next paragraph (based on where the cursor is positioned currently). |
<n>G |
Type a number and command G (uppercase) to :n move the cursor to the specific line (as identified by the line number ‘n’). The same result is achieved by executing the ex command :n. |
G |
Move the cursor to the last line in the file. |
CTRL+F |
Pressing the CTRL key and ‘F’ (case-insensitive) together will move the cursor position (or scroll the screen) by one screen forward. |
CTRL+B |
Pressing the CTRL key and ‘B’ (case-insensitive) together will move the cursor position (or scroll the screen) by one screen backward. |
CTRL+D |
Pressing the CTRL key and ‘D’ (case-insensitive) together will move the cursor position (or scroll the screen) by half screen forward. |
CTRL+U |
Pressing the CTRL key and ‘U’ (case-insensitive) together will move the cursor position (or scroll the screen) by half screen backward. |
CTRL+E |
Scroll the screen up by one line, so that one more line is shown in the bottom of the screen (and the first line in the screen goes out of view). |
CTRL+Y |
Scroll the screen down by one line, so that one more line is shown in the top of the screen (and the last line in the screen goes out of view). |
z+RETURN |
Press ‘z’ (lowercase) and then press the RETURN key to scroll the screen upward so that the line at which the cursor is currently positioned is displayed at the top of the screen as the first line. |
z+. |
Press ‘z’ (lowercase) and then press the period ‘.’ to scroll the screen (up or down as required) so that the line at which the cursor is currently positioned is displayed in the middle of the screen. |
z+- |
Press ‘z’ (lowercase) and then press the hyphen ‘-’ to scroll the screen downward so that the line at which the cursor is currently positioned is displayed at the bottom of the screen as the last line. |
The next set of useful commands assists in searching for a specific pattern of text within the file. This feature is similar to the Find (and Find & Replace) feature found in most Windows-based applications. These commands are discussed in Table 3.3.
Command Character(s) |
Command Description |
---|---|
/<pattern> |
The most commonly used search command is /. After typing the / character, type the text to be searched. If the pattern is found in the file, the cursor is positioned at the first occurrence of the pattern. The search is performed |
/<pattern> |
from the current cursor location. To locate the next occurrence of the same pattern, just type ‘n’ (lower case) or ‘/’ for forward search, and ‘N’ (upper case) or ‘?’ for backward search. |
?<pattern> |
This command is similar to the /<pattern> command, but works in the backward direction. The next occurrence in the backward direction is found by typing the n command and the next occurrence in the forward direction is found by typing the N command. |
/<pattern>/n |
This command will position the cursor at the ‘n’th line from the first occurrence of the pattern. The search is performed from the current cursor position. |
?<pattern>?-n |
This command is similar to the /<pattern>/n command but works in the backward direction. |
:s/<pattern1>/ |
Substitute (or replace) all the occurrences of pattern1 <pattern2>/g with pattern2. The /g at the end indicates a global change, which means throughout the file. Use /gc for a confirmation before making the substitution. |
:<n1>,<n2>s/ |
In this form of substitution, the pattern replacement <pat1>/<pat2> is performed only for pattern occurrences between lines n1 and n2. |
Table 3.4 describes the set of most commonly used miscellaneous commands.
Command Character(s) |
Command Description |
---|---|
:<n1>,<n2>co<n3> |
Copy lines n1 through n2 after line n3 |
:<n1>,<n2>d |
Delete lines from line number n1 through line number n2. |
:<n1>,<n2>w <file> |
Write contents of the current file from line number n1 through line number n2 to the file specified as <file>. |
Dw |
Delete current word (where the cursor is positioned) |
<n1>d |
Delete <n1> number of lines from the current cursor position (in the forward direction). |
Dd |
Delete entire current line (where the cursor is positioned). |
D |
Delete rest of the line from the current cursor position. |
d$ |
Same as the command D. |
d} |
Delete the rest of the paragraph from the current position. |
N |
Delete the character where the cursor is currently positioned. |
X |
Delete the character to the left of the current cursor position. |
<n>x |
Delete the next <n> characters from (and including) the current cursor position |
J (uppercase) |
Append the next line at the end of the current line. |
u |
Execute an undo of the most recently executed command. |
:r <file name> |
Read the file mentioned in <file name> into the current file after the current cursor position. Note that this is an ‘ex’ mode command. |
:!<command> |
Execute a shell command without leaving the file. |
:r <!command> |
Execute the shell command and write the output of the command in the current file after the current cursor position. |
yy (lowercase) |
Copy the current line into the buffer. This may be pasted at some other location in the file using the p command. The command <n>yy will copy ‘n’ number of lines from current line (where the cursor is positioned). |
p (lowercase) |
Paste the lines copied by the yy command, after the current line. Use the command P (uppercase) to paste the lines before the current line. After executing the yy or <n>yy command, the mode should not be changed before executing the p or P command. If the mode was changed (to insert mode) accidentally, the contents of the buffer will be lost. |
The vi editor is configurable and is preset with default configuration. The preset options may be changed using the :set command. Simply type ‘:set all’ to display all the available options with their default values. You can change individual options using the syntax ‘:set <option>=<value>’. For example, there is an option called tabstop, which indicates the number of character positions the TAB key should advance. The default value for this option is 8. To change this setting to 4 characters, type the command ‘:set tabstop=4’. This will change the tabstop setting to 4 for the current vi editor session. To save the options on a permanent basis, they should be saved to the .exrc file in the user’s home directory. This file is automatically created when the user is created. When saving the settings in this file, the preceding colon should not be used, because that is only used in an editing session.
You should now be familiar with most commonly used vi commands, although there are still a number of commands not described here. On Linux, the open source edition of this popular editor—known as vim (vi improved)—is supplied instead of the traditional vi command. A file may be opened in ‘Read-only’ mode in order to prevent accidental change to the contents of the file, by specifying the –R command-line option while invoking the vi or vim editor as shown here.
$ vi –R file5.txt $ vim –R file5.txt
The view command opens the file in read-only mode (without the –R option); and we can use all the navigation and pattern matching commands without harming the contents of the file. Even if we accidentally change the contents of the file when opened in the read-only mode, we will not be allowed to save the file. It is the vim command that is invoked whether we type ‘vi’ or ‘vim’ or ‘view’ at the command prompt, because vi and view are provided as soft links to the vim program. However, when the view command is invoked, the file is automatically opened in read-only mode.
< Day Day Up > |