Slackware Linux Essentials - Chapter 16 VI
Warning: file_get_contents(http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=1TJ8QTQ6ZFCVAJ3X1T02&AssociateTag=ii0c3-20&Operation=ItemSearch&SearchIndex=Books&ResponseGroup=Small,Images&Keywords=backup) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/manusia2/public_html/wp-content/plugins/amazonfeed/php/amazonfeed.class.php on line 271
vi(1) is the standard Unix text editing program, and while mastering it is not as essential as it once was, is still a very rewarding goal. There are several versions (or clones) of vi available, including vi, elvis, vile, and vim. One of these is available on just about any version of Unix, as well as on Linux. All of these versions include the same basic feature set and commands, so learning one clone should make it easy to learn another. With the variety of text editors included with Linux distributions and Unix variants these days, many people no longer use vi. Still, it remains the most universal text editor across Unix and Unix work-alikes. Mastering vi means you should never be sitting at a Unix machine and not be comfortable with at least one powerful text editor.
vi includes a number of powerful features including syntax highlighting, code formatting, a powerful search-and-replace mechanism, macros, and more. These features make it especially attractive to programmers, web developers, and the like. System administrators will appreciate the automation and integration with the shell that is possible.
On Slackware Linux, the default version of vi available is elvis. Other versions - including vim and gvim - are available if you’ve installed the proper packages. gvim is an X Window version of vim that includes toolbars, detachable menus, and dialog boxes.
16.1 Starting vi
vi can be started from the command line in a variety of ways. The simplest form is just:
% vi
Figure 16-1. A vi session.

This will start up vi with an empty buffer. At this point, you’ll see a mostly blank screen. It is now in “command mode”, waiting for you to do something. For a discussion of the various vi modes, see the Section 16.2. In order to quit out of vi, type the following:
:q
Assuming that there have been no changes to the file, this will cause vi to quit. If there have been changes made, it will warn you that there have been changes and tell you how to disregard them. Disregarding changes usually means appending an exclamation point after the “q” like so:
:q!
The exclamation point usually means to force some action. We’ll discuss it and other key combinations in further details later.
You can also start vi with a pre-existing file. For example, the file /etc/resolv.conf would be opened like so:
% vi /etc/resolv.conf
Finally, vi can be started on a particular line of a file. This is especially useful for programmers when an error message includes the line their program bombed on. For example, you could start up vi on line 47 of /usr/src/linux/init/main.c like so:
% vi +47 /usr/src/linux/init/main.c
vi will display the given file and will place the cursor at the specified line. In the case where you specify a line that is after the end of the file, vi will place the cursor on the last line. This is especially helpful for programmers, as they can jump straight to the location in the file that an error occurred, without having to search for it.
16.2 Modes
vi operates in various modes, which are used to accomplish various tasks. When you first start vi, you are placed into command mode. From this point, you can issue various commands to manipulate text, move around in the file, save, quit, and change modes. Editing the text is done in insert mode. You can quickly move between modes with a variety of keystrokes, which are explained below.
16.2.1 Command Mode
You are first placed into command mode. From this mode, you cannot directly enter text or edit what is already there. However, you can manipulate the text, search, quit, save, load new files, and more. This is intended only to be an introduction to the command mode. For a description of the various commands, see Section 16.7.
Probably the most often used command in command mode is changing to insert mode. This is accomplished by hitting the i key. The cursor changes shapes, and – INSERT – is displayed at the bottom of the screen (note that this does not happen in all clones of vi). From there, all your keystrokes are entered into the current buffer and are displayed to the screen. To get back into command mode, hit the ESCAPE key.
Command mode is also where you move around in the file. On some systems, you can use the arrow keys to move around. On other systems, you may need to use the more traditional keys of “hjkl”. Here is a simple listing of how these keys are used to move around:
h
move left one character
j
move down one character
k
move up one character
l
move right one character
Simply press a key to move. As you will see later, these keys can be combined with a number to move much more efficiently.
Many of the commands that you will use in command mode begin with a colon. For example, quitting is :q, as discussed earlier. The colon simply indicates that it is a command, while the “q” tells vi to quit. Other commands are an optional number, followed by a letter. These commands do not have a colon before them, and are generally used to manipulate the text.
For example, deleting one line from a file is accomplished by hitting dd. This will remove the line that the cursor is on. Issuing the command 4dd would tell vi to remove the line that the cursor is on and the three after that. In general, the number tells vi how many times to perform the command.
You can combine a number with the movement keys to move around several characters at a time. For example, 10k would move up ten lines on the screen.
Command mode can also be used to cut and paste, insert text, and read other files into the current buffer. Copying text is accomplished with the y key (y stands for yank). Copying the current line is done by typing yy, and this can be prefixed with a number to yank more lines. Then, move to the location for the copy and hit p. The text is pasted on the line after the current one.
Cutting text is done by typing dd, and p can be used to paste the cut text back into the file. Reading in text from another file is a simple procedure. Just type :r, followed by a space and the file name that contains the text to be inserted. The file’s contents will be pasted into the current buffer on the line after the cursor. More sophisticated vi clones even contain filename completion similar to the shell’s.
The final use that will be covered is searching. Command mode allows for simple searching, as well as complicated search-and-replace commands that make use of a powerful version of regular expressions. A complete discussion of regular expressions is beyond the scope of this chapter, so this section will only cover simple means of searching.
A simple search is accomplished by hitting the / key, followed by the text that you are searching for. vi will search forward from the cursor to the end of the file for a match, stopping when it finds one. Note that inexact matches will cause vi to stop as well. For example, a search for “the” will cause vi to stop on “then”, “therefore”, and so on. This is because all of those words do match “the”.
After vi has found the first match, you can continue on to the next match simply by hitting the / key followed by enter. You can also search backwards through the file by replacing the slash with the ? key. For example, searching backwards through the file for “the” would be accomplished by typing ?the.
16.2.2 Insert Mode
Inserting and replacing text is accomplished in insert mode. As previously discussed, you can get into insert mode by hitting i from command mode. Then, all text that you type is entered into the current buffer. Hitting the ESCAPE key takes you back into command mode.
Replacing text is accomplished in several ways. From command mode, hitting r will allow you to replace the one character underneath the cursor. Just type the new character and it will replace the one under the cursor. You will then be immediately placed back into command mode. Hitting R allows you to replace as many characters as you’d like. To get out of this replacement mode, just hit ESCAPE to go back into command mode.
There is yet another way to toggle between insertion and replacement. Hitting the INSERT key from command mode will take you into insert mode. Once you are in insert mode, the keyboard’s INSERT key serves as a toggle between insert and replace. Hitting it once will allow you to replace. Hitting it once more will once again allow you to insert text.
16.3 Opening Files
vi allows you to open files from command mode as well as specifying a file on the command line to open. To open the file /etc/lilo.conf:
:e /etc/lilo.conf
If you have made changes to the current buffer without saving, vi will complain. You can still open the file without saving the current buffer by typing :e!, followed by a space and the filename. In general, vi’s warnings can be suppressed by following the command with an exclamation mark.
If you want to reopen the current file, you can do so simply by typing e!. This is particularly useful if you have somehow messed up the file and want to reopen it.
Some vi clones (for example, vim) allow for multiple buffers to be open at the same time. For example, to open up the file 09-vi.sgml in my home directory while another file was open, I would type:
:split ~/09-vi.sgml
The new file is displayed on the top half of the screen, and the old file is displayed in the bottom half of the screen. There are a lot of commands that manipulate the split screen, and many of these commands start to resemble something out of Emacs The best place to look up these commands would be the man page for your vi clone. Note that many clones do not support the split-screen idea, so you might not be able to use it at all.
16.4 Saving Files
There are several ways to save files in vi. If you want to save the current buffer to the file randomness, you would type:
:w randomness
Once you’ve saved the file once, saving it again is as simple as typing :w. Any changes will be written out to the file. After you’ve saved the file, you are dumped back into command mode. If you want to save the file and quit vi (a very common operation), you would type :wq. That tells vi to save the current file and quit back to the shell.
On occasion, you want to save a file that is marked as read-only. You can do this by adding an exclamation point after the write command, like so:
:w!
However, there will still be instances where you cannot write the file (for example, you are attempting to edit a file that is owned by another user). When this happens, vi will tell you that it cannot save the file. If you really want to edit the file, you’ll have to come back and edit it as root or (preferably) the owner of that file.
16.5 Quitting vi
One way to quit vi is through :wq, which will save the current buffer before quitting. You can also quit without saving with :q or (more commonly) :q!. The latter is used when you’ve modified the file but do not wish to save any changes to it.
On occasion, your machine might crash or vi might crash. However, both elvis and vim will take steps to minimize the damage to any open buffers. Both editors save the open buffers to a temporary file on occasion. This file is usually named similarly to the open file, but with a dot at the beginning. This makes the file hidden.
This temporary file gets removed once the editor quits under normal conditions. This means that the temporary copy will still be around if something crashes. When you go back to edit the file again, you will be prompted for what action to take. In most cases, a large amount of your unsaved work can be recovered. elvis will also send you a mail (from Graceland, oddly enough
telling you that a backup copy exists.
16.6 vi Configuration
Your vi clone of choice can be configured in several ways.
A variety of commands can be entered while in command mode to set up vi just how you like it. Depending on your editor, you can enable features to make programming easier (like syntax hilighting, auto-indenting, and more), set up macros to automake tasks, enable textual substitutions, and more.
Almost all of these commands can be put into a configuration file in your home directory. elvis expects a .exrc file, while vim expects a .vimrc file. Most of the setup commands that can be entered in command mode can be placed in the configuration file. This includes setup information, textual substitutions, macros, and more.
Discussing all these options and the differences between the editors is quite an involved subject. For more information, check out the man page or web site for your preferred vi editor. Some editors (like vim) have extensive help within the editor that can be accessed with the :help command, or something similar. You can also check out the O’Reilly book Learning the vi Editor by Lamb and Robbins.
Many common programs in Linux will load up a text file in vi by default. For example, editing your crontabs will start up vi by default. If you do not like vi and would like another editor to be started instead, all you need to do is set the VISUAL environment variable to the editor you prefer. For information on setting environment variables, see the section called Environment Variables in Chapter 8. If you want to make sure that your editor will be the default every time you login, add the VISUAL setting to your .bash_profile or .bashrc files.
16.7 Vi Keys
This section is a quick reference of many common vi commands. Some of these were discussed earlier in the chapter, while many will be new.
Table 16-1. Movement
Operation
Key
left, down, up, right
h, j, k, l
To the end of the line
$
To the beginning of the line
^
To the end of the file
G
To the beginning of the file
:1
To line 47
:47
Table 16-2. Editing
Operation
Key
Removing a line
dd
Removing five lines
5dd
Replacing a character
r
Removing a character
x
Removing ten characters
10x
Undo last action
u
Join current and next lines
J
Replace old with new, globally
%s’old’new’g
Table 16-3. Searching
Operation
Key
Search for “asdf”
/asdf
Search backwards for “asdf”
?asdf
Repeat last search forwards
/
Repeat last search backwards
?
Repeat last search, same direction
n
Repeat last search, opposite direction
N
Table 16-4. Saving and Quitting
Operation
Key
Quit
:q
Quit without saving
:q!
Write and quit
:wq
Write, without quitting
:w
Reload currently open file
:e!
Write buffer to file asdf
:w asdf
Open file hejaz
:e hejaz
Read file asdf into buffer
:r asdf
Read output of ls into buffer
:r !ls
Tags: backup, cron, slackware, Slackware Linux Essentials