Text Editors


- 16 -

Text Editors

by Peter MacKinnon and Kamran Husain

IN THIS CHAPTER

It's time to look at editors. This chapter will show you

What Are Editors and Why Do I Need One?

A text editor is one of the most essential tools provided with the Linux (or virtually any) operating system. With an editor, you can create and modify text files that have a wide variety of applications:

These are but a few of the many types of text files you will use when working with Linux. Basically, editors enable you to insert, delete, move, and search text ranging from individual characters to thousands of lines.

Two of the most popular editors for the Linux system are emacs and vi. Both these editors are full-screen text editors. Put simply, they use every row and column of your terminal screen to display the textual contents of a file. Both of these editors feature a rich set of commands. The essential commands for manipulating text can be learned reasonably quickly; the more sophisticated commands might take a little longer to master. You will likely appreciate this investment, however, as you see how much time these powerful tools can save you. A less known, though quite powerful, editor is joe. It too attempts to use all the screen space it can, but it offers an online help menu and an easy-to-use command set.

Choosing one editor over another can be a matter of taste. Both emacs and vi are efficient and can handle virtually any size of file. The emacs editor is better suited to complex editing tasks and comes with an online help facility, but for simple editing jobs, either editor is equally good. If you are coming from the DOS world or have used WordStar, you will find joe very easy to use. It really just comes down to choosing the one you feel more comfortable using.

The Editing Functions

Although the various text editors for Linux have different interfaces, they all basically do the same things. Any useful text editor should support the following features at a minimum.

Inserting and Deleting Text

The most intrinsic function of a text editor is to enable you to enter and erase characters as you see fit. This also implies that you have complete control over the movement of the cursor and its placement in the text.

Reading and Writing Files

Because you will want to save the text files you create for future use, an editor can write your text to an external file. Whenever you need to make changes to your file, an editor can read the file from disk. A handy feature is that text editors are designed to accommodate ASCII formatted files, so an editor (such as emacs) can read any file written by another editor (such as vi).

Searching Text

Personally scanning line after line of a large file for instances of a particular word is either a great way to improve your powers of concentration or an exercise in self-torture. That is why text editors provide sophisticated search capabilities. These include the use of regular expressions as well as fixed strings. Remember that regular expressions include metacharacters (such as ., ?, and *) that replace and expand unknown text patterns.

Editors also support search-and-replace functions that enable you to change multiple instances of a string pattern with a single command.

Copying and Moving Text

Because there is no guarantee that the way text is initially typed into a file is the way it should forever remain, editors provide you with the means to copy, cut, and move (or paste) blocks of text. These blocks can range in size from a single character to several pages. The distinction between copying and cutting text is that cutting deletes the selected block of text after it has been copied to a buffer, whereas copying does not remove the text block.


NOTE: Imagine having to retype Dickens's A Tale of Two Cities after realizing that you have somehow placed "It was the best of times, it was the worst of times" at the end of the file and not the start!

Editing Buffers

What is a buffer, you ask? Buffers are places in the memory of the editing program where text can reside as you make changes to a file. For example, the first time you edit a file, the text you have entered actually exists in a buffer that is written to an external file when you perform a save. Buffers can also be used at other times in editing, particularly when it is necessary to temporarily move a block of text to memory as you make changes (in other words, when you're cutting and pasting). Many editors enable you to manage multiple buffers simultaneously.

These editors have many commands that are not fully detailed in this chapter. Before engaging in any long and arduous editing task, consult the man page for the editor you are using. There might be an easier way of doing whatever it is you want to do. As you gain experience with an editor, you will discover convenient shortcuts and functions to perform your most tedious editing chores.

The vi Editor

The vi editor is installed with virtually every UNIX system in existence. Because of this, vi is considered by many to be the default text editor of the UNIX system (on which Linux is based). vi has two modes of operation and terse commands, both of which make it a somewhat more difficult editor to learn than emacs. It is, however, a useful editor to learn if emacs has not been installed on your Linux system.

Starting vi

You invoke vi from the command line by typing vi.

The screen clears and a column of tildes (~) appears in the leftmost column. You are now editing an empty, unnamed file. Whatever text you place in this file exists in a buffer until you write the contents of the buffer to some named file. The tilde is vi's way of telling you that the line where the tilde appears is empty of text.

vi can also be started with a file or a list of files to edit, like this:

vi filename1 filename2 filename3 ...

Typically, you will probably edit only one file per vi session. If you are editing a list of files, vi edits the files in the order in which they appear on the command line.

Alternatively, vi can be invoked from the command line as

vi +n filename

where n represents the line number where vi will place its cursor in filename. This alternative is useful for programmers debugging large source-code files who need to jump quickly to a known line containing an error.

Another example will be of use in illustrating the vi editor. If you still have a vi session on your screen, exit it by pressing Esc and then typing :q!. To start a new vi session, enter

vi asong

at the command line.

vi Modes

At the bottom of the screen in the left corner, you will see this:

"asong" [NEW FILE] 1 lines, 1 characters

The messages displayed on this status line tell you what vi is doing or has just done. In this case, vi is telling you that it has opened an empty buffer whose contents will be saved (whenever you do a save) to the file asong.

At this moment, you are in the command mode of vi. This is the major conceptual leap required in working with this editor. When editing text, you must remember whether you are in command mode or text mode. In command mode, any character sequences you enter are interpreted as vi commands. In text mode, every character typed is placed in the buffer and displayed as text on-screen.

Four commands are echoed at the bottom of the screen on the status line:
/ Searches forward
? Searches backward
: Is an ex command (ex is a standalone line-based editor used within vi)
!
Invokes a shell command
You enter each of these types of status-line commands by pressing Enter. This is not true for other types of vi commands, such as the ones that perform insertions.


TIP: To find out whether you are in command mode, use the set showmode preference described in the section titled "Setting Preferences," later in this chapter.

Inserting Text

So knowing that you are in command mode, let's insert some text. Basically, two commands can be used for entering text on the current line: the letters i and a. These lowercase letters insert (i) text to the left of the cursor or append (a) text to the right of the cursor. As with many vi commands, the uppercase versions of these letters have similar effects with subtle differences: uppercase I and A insert and append at the beginning and end of the current line.

After you press either of these letters, you are placed in input mode. Any text entered after this point is displayed on-screen.

Press i and then type the following text:

Down I walk<Enter>

by the bay,<Enter>

Where I can<Enter>

hear the water.<Enter>

Down we walk<Enter>

by the bay,<Enter>

My hand held<Enter>

by my daughter.<Enter>

To exit from input mode, press Esc. Notice that you did not see the letter i displayed before you entered the text, meaning that the i was correctly interpreted as a command. Also, it is important to note that it was not necessary to press Enter after pressing i for input mode.

Quitting vi

Now that you have some text for your file, let's quit the editor to see the results. The commands used for saving the file and exiting vi are slightly different from the i and d commands used in editing text: you must precede the command with a colon (:).

In this case, you want to perform a save and exit, which are actually combined in one command. Press :. In the lower-left part of your screen, you will notice that a colon has appeared. vi has recognized that you are about to enter an ex command, and it will echo the remaining characters of the command after the colon. Type wq and press Enter. vi quickly informs you that it has written the file to disk and tells you how many lines the file contains. If the file is small and you have a fast system, this message might appear and be erased so quickly that you won't catch it. Don't worry--the file has been saved if you issued the command properly. vi exits and you find yourself back at the shell prompt. Another way to save and exit is to type ZZ. The difference between this method and using wq is that ZZ writes the file only if it has been modified since the last save.

You can quit vi by typing :q if no changes have been made to the file you opened. This method doesn't work if the file has been modified. If you are sure you don't want to save what you have done, enter :q!. This command forces vi to quit, regardless of any edits.

To make sure that vi saved the file asong correctly, use the cat command to quickly view the file's contents:

$ cat asong

Down I walk

by the bay,

Where I can

hear the water.

Down we walk

by the bay,

My hand held

by my daughter.

$

Everything is exactly as you typed it in the file, so there are no surprises here.

Moving the Cursor

Moving the cursor around in vi essentially involves the following four keys:
h Moves the cursor one space to the left
j Moves the cursor down one line
k Moves the cursor up one line
l
Moves the cursor one space to the right
These keys can perform their operations only when vi is in command mode. For convenience, most implementations of vi map these keys to their directional counterparts on the keyboard arrow keys.

vi enables you to move through a file in bigger "leaps" as well. Following are some commands for scrolling more than one line at a time:
Ctrl U Scrolls up a half screen
Ctrl D Scrolls down a half screen
Ctrl F Scrolls down one full screen
Ctrl
B Scrolls up one full screen
The size of these movements largely depends on the terminal settings.

It is also possible to move the cursor to a specific line in a file. If you want to move to the 10th line, type 10G or :10 in command mode. G by itself moves the cursor to the end of the file. The cursor does not move if the number given is not applicable (for example, typing :10 in an eight-line file has no effect).

vi also enables you to move the cursor a word at a time. A word is defined as any sequence of non-whitespace characters. To move to the beginning of the next word or punctuation mark on the current line, press w. Press b to move the cursor to the beginning of the current or preceding word or punctuation mark.

Deleting Text

vi has commands for deleting characters, lines, and words. Deletion means that the selected text is removed from the screen but is copied into an unnamed text buffer, from which it can be retrieved.

To delete a word, use the dw command. If you want to delete the word to the right of the cursor, type dw. If you are in the middle of a word, this command deletes from the cursor position to the end. You can also delete several words at a time. For example, the command 4dw deletes the next four words on the current line.

You can delete lines individually or specify a range of lines to delete. To delete the current line, type dd. The command 4dd deletes four lines (the current line and three below it). dG deletes all lines from the current one to the end of the file.

On the current line, you can delete in either direction: d^ deletes backward to the beginning of the line, and d$ (or D) deletes forward to the end of the line.

To delete individual characters, x deletes the character underneath the cursor, and X deletes the character to the left of the cursor. Both of these commands accept a number modifier: for example, 4x deletes the current character and the four characters to the right.

Unwanted changes such as deletions can be immediately undone by the u command. This "rolls back" the last edit made.


TIP: Not sure what command you just typed? When in doubt, press Esc and then enter the command again.

Copying and Moving Text

Moving sections of text around in a file basically requires three steps:

1. Yank the text into a buffer.

2.
Move the cursor to where you want to insert the text.

3.
Place the text from the buffer at the new location.

Yanking text means to copy it into either a named or an unnamed buffer. The unnamed buffer is a temporary storage space in memory that is continually overwritten by successive yanks. vi has 26 named buffers that correspond to each letter of the alphabet.

To yank the current line into the unnamed buffer, the command is yy or Y. These commands can be modified by a number indicating how many lines beneath the cursor are to be yanked. For example, the command 3yy in your file asong (with the cursor on the top line) yanks the following text into the temporary buffer:

Down I walk

by the bay,

Where I can

This text could also be yanked into the named buffer a by the following command:

"a3yy

The quotation mark (") tells the yank command to overwrite the contents of the named buffer a. If you had typed a capital A instead of a lowercase a, the three lines would have been appended to the end of the a buffer. This overwrite-versus-append concept works the same for all the named buffers.

If you move the cursor to the end of the file using the :$ command, you can then paste the contents of the unnamed buffer to the end of the file. This is done with the p command, which pastes the contents of a buffer to the right of the cursor (P pastes to the left of the cursor). The paste command can also specify a named buffer in the same way as the yank command, like so:

"ap

Yanks can also be performed on words using the command yw. This command also can use named buffers and accepts numeric modifiers.

Searching and Replacing Text

Text searches in vi can be performed in either direction: forward or backward. Searches are always started from the current cursor location and continue from the top or bottom of the file depending on which direction you use. In other words, searches "wrap around" the file.

You can use your file asong to illustrate searches. To search forward through asong for the word "bay," you would type

/bay

and press Enter. Notice that this is a status-line command. The command /bay is echoed on the status line, and the cursor is moved to the first occurrence it finds in the forward direction of the string "bay." Interested in finding another instance of "bay"? Enter a / character. This command continues the search for "bay" in the forward direction and places the cursor at the next instance of "bay." Each time you enter the / key, vi tries to find an instance of the previous string pattern. When it reaches the end of the file, vi loops back and continues its search at the start of the file.

You can also search backward for strings in vi by using the ? command. It works in exactly the same manner as the / command, but in the opposite direction. Try it out by typing

?I

in asong, instructing vi to search back for instances of "I." You can repeat this search by pressing ?, as you might have suspected. You can continue a search by pressing n, which always continues a search in the same direction as the preceding search. N, however, uses the same search string but in the opposite direction.

As I mentioned earlier, searches can be made very powerful through the use of regular expressions. The search command is supplied in the same fashion as described before (/ or ?), but square brackets are added to instruct vi to perform a regular expression expansion of the enclosed characters. For example, search forward through asong from the first line for all strings containing the substring "er." Type this:

/er

vi's first matching string arrives at "Where." If you press n, vi moves the cursor to "where", and so on. You can also specify collections of characters or ranges of characters to match. Try typing the following command:

/[a-z]y

This command used in asong finds the strings "by" and "my," as well as any word with these strings inside them (such as "bay"). This works because the range of characters given is treated as an enumerated range of ASCII values. Thus, you could also include a range of numbers (for example, 0-9). Now try the following command:

/[Mm]y

This locates the strings "My" and "my."

In vi, searches without regular expressions find only exact matches of the supplied pattern (including the case of the letters in the pattern). Clearly, regular expressions can be used to enhance many types of searches in which you might not know exactly how a pattern appears in a file.

One of the more common applications of a search is to replace instances of one word (or pattern) with another. This is done with an ex command that starts with a colon. To search the entire asong file for the string "Down" and replace it with the string "Up," type this:

:%s/Down/Up/g

The s indicates that this is a search operation, the % means that the entire file is to be searched, Down is the pattern to be found, Up is the new pattern, and the g tells vi that the search should continue until no more pattern matches are found. Without the g, vi would perform the replacement on only the first match it finds. This command also works with regular expressions appearing in the search pattern and the replacement pattern.

Setting Preferences

vi is configurable, which means that you can set options to control your editing environment. These options are initialized with default values that you can modify in vi at any time. vi is configured using the set command. You must precede the set command with a colon and enter it by pressing Enter. For example, to display line numbers in the editor, you would issue this command:

:set number

The following list describes a few of the more common set commands:
all Displays a list of all available set options and their current

statuses
errorbells Sounds the terminal bell when an error occurs
ignorecase Makes searches case-insensitive
number Displays line numbers in the leftmost column of the screen

(these are not written to the file)
showmode
Puts a display in the lower-right portion of the screen thatindicates whether you are in input mode, change mode, replace mode, and so on



   
   

set commands that do not take a value can be switched off via insertion of no as a prefix to the set parameter. For example, the command

:set nonumber

switches line numbering off. The command

:set

shows only the options you have changed.

The settings you use in a vi session are (unfortunately) lost each time you exit vi. If you do not like the idea of resetting these options each time you use vi, you can perform this initialization in another way. Use the vi initialization file called .exrc. vi searches for this file in your home directory each time it is invoked. If it can't find this file, it uses the defaults set within the vi program. As you will see in the following example, the .exrc file can also be used to define vi macros.

An example .exrc file would look something like this:

set number

set errorbells

set showmode

Note that the colon is not required before a set command in .exrc files.

A Summary of Commands

Following is a summary of the more essential commands described in this chapter. You should consult the vi man page for more details on the many other vi commands.
i Starts inserting text at the cursor
h Moves the cursor one character to the left
j Moves the cursor down one line
k Moves the cursor up one line
l Moves the cursor one character to the right
C-f Scrolls forward one screen
C-b Scrolls backward one screen
ndd Deletes the next n lines
nyy Yanks the next n lines into the unnamed buffer
p Puts the contents of the unnamed buffer to the right of the cursor
u Undoes the preceding change
:wq Writes changes and exits vi
:q! Exits vi without saving changes
:set all Shows all set parameters and their values
/string
Searches forward for string

The emacs Editor

emacs has become the editor of choice for many users because of its online help facility and its extensive collection of editing commands. For programmers, emacs is especially attractive because it can be configured to format source code for various languages, such as C, C++, and Lisp. emacs is somewhat easier to learn than vi, but it also features a much larger set of commands.

Starting emacs

emacs is invoked from the command line by the following command:

emacs

To start emacs with a file to be edited, enter this:

emacs filename

If you start emacs with a file, the screen displays the contents starting from the first line. Note the two lines at the bottom of the screen. The first of these lines, known as the mode line, displays the name of the file being edited and which part of the file you are looking at (for example, TOP, 20%, BOT). The last line on the screen is the echo line, which emacs uses to display system messages and to prompt for more input.

Control and Meta Keys

You are quite free at this point to start entering text into the edit buffer at the cursor location. However, you're probably wondering, "How do I move the cursor around?" Before I fill you in on this little detail, you should know something about two keys: the Control key (which I will refer to as C) and the Meta key (denoted by M). The Control key is used in most of the commands for emacs, but some use the Meta key instead. Commands in emacs consist of combinations of the Control or Meta key followed by some other character. It is necessary to hold down the Control key when pressing the next character, whereas the Meta key can be pressed and released before you enter the next character. For the PC, the Meta key is usually the Alt key.

NOTE

You'll see the Control key abbreviated as C and the Alt key denoted by M.

Moving the Cursor

Now that you know about the Control key, we can talk about the cursor-movement commands. Following are the basic ones you need to remember:
C f Moves the cursor forward one character
C b Moves the cursor back one character
C p Moves the cursor to the preceding line
C n Moves the cursor to the next line
C a Moves the cursor to the beginning of the line
C
e Moves the cursor to the end of the line


NOTE: When I refer to a command such as C-b, I mean that you press and hold down the Control key while you press the letter b. The same is true for Meta commands such as M-v.

Most implementations of emacs conveniently map the first four movement commands to the arrow keys on the keyboard. Let's edit a new file called asong2. (If you are in the middle of a previous file, exit the editor by pressing Ctrl-X, Ctrl-C.) Start a new copy of emacs by entering the following command from the shell:

emacs asong2

Now enter the following text into the buffer:

This is a file for edit

And you have to give emacs some credit

It's really quite swell

And all you have to do is spell

emacs works, if only you let it!

Now use the C-b command to move back through this horrendous piece of poetry. Notice how the cursor jumps up to the end of the preceding line after reaching the beginning of the lower line. This works the same way in the opposite direction using the C-f command.

Another useful way of moving around is by scrolling through a file one screen at a time. The command C-v moves the cursor forward one screen at a time. The command M-v moves the cursor in the opposite direction.

Like vi, emacs treats a sequence of non-whitespace characters as a word. You can move the cursor forward one word at a time with the M-f command. The M-b command moves the cursor back one word.

Quitting emacs

At this time, you can stop editing to save the contents of the buffer to your file asong2. To do this, issue the command sequence C-x, C-s. As you enter this command, notice how the command is displayed on the echo line as you type it. To quit emacs and return to the shell, enter the command C-x, C-c. If you have made changes that haven't been saved using C-x, C-s, emacs asks for confirmation before quitting.

Deleting Text

You can delete text in several ways. The Backspace (or Delete) key is used to erase the character immediately preceding the cursor. The command C-d deletes the character underneath the cursor, and C-k deletes or "kills" all characters from the cursor to the end of the line. Words can be deleted also: M-d deletes the word the cursor is currently located over, and M-Delete (the Delete key) deletes the word preceding the current word.

If you ever find that you have committed an edit that you didn't really want, just type C-x, u to undo the preceding editing changes. You can repeat the undo command as many times as you want, rolling over all the changes you made. This is an advantage over vi, which can undo only the last change.


TIP: Change your mind about a command? Type C-g to abort the current command operation.

Working with Multiple Files

emacs enables you to edit several files in one session, each contained within its own buffer. To copy an external file into a new buffer, use the C-x, C-f command. After entering this command, you see the following prompt on the echo line:

Find file: ~/

emacs is smart when it looks for files. It supports filename completion, which means that you can simply type a few characters of a filename, and emacs attempts to match a file (or files) to what you have typed so far. To do this, type the letters .log and press the Tab key. emacs expands this to ~/.login (or any other filename that matches). If two or more files match the pattern supplied, a press of the Tab key cycles through them.

After you have loaded a new file into emacs, you can switch between buffers by using the C-x, b command followed by the name of the buffer you want. The buffer's name is that of the file that was loaded into it. The C-x, b command also uses filename completion, so you can use the Tab key to cycle through your edit buffers after supplying a few relevant characters.

When you have finished editing a buffer, instead of saving the contents using the C-x, C-s command, you might decide you don't really want to keep the edits you have made. You can "kill" the current buffer by entering the command C-x, k. emacs prompts you for the name of the buffer to kill, but you can kill the current buffer by simply pressing Enter. emacs asks for confirmation, to which you can respond by typing yes (if you're sure) and pressing Enter.


TIP: Whenever you are working with just two buffers, you can simply press Enter after entering the C-x, b command to switch to the other buffer.

Copying and Moving Text

To copy and move blocks of text in emacs, you must define the region of text by marking the beginning and end points of the text block. You carry out this task by moving the cursor to where you want the block to begin and marking it using the C-Space command (in this case, Space means literally the spacebar). The end of the block is defined by wherever you place the cursor after that. To make a copy of the block, enter the command M-w. The text within the block is copied to emacs's internal clipboard, from which you can paste it at another location with the C-y command. Alternatively, you can cut the block into the clipboard using C-w rather than M-w. Cutting, of course, deletes the text from its current location.

Let's try out some of these techniques on your buffer asong2. Use the M-< command to jump to the beginning of the buffer. Use C-Space to mark the start of the block, and then use C-n to move down a line. Cut the block to the clipboard using C-w, move the cursor to the end of the buffer using M->, and paste it using C-y. The result should look like this:

It's really quite swell

And all you have to do is spell

emacs works, if only you let it!

This is a file for edit

And you have to give emacs some credit

Searching and Replacing Text

You can search forward through text by using the C-s command and backward through text by using C-r. These commands, like many in emacs, use command completion. This is the same concept as filename completion: you supply a few characters, and emacs tries to fill in the rest. In this case, however, emacs moves the cursor to each instance it finds of the string supplied.

As you enter more characters, emacs narrows its search further. When you have found a correct match, press Enter or use any of the cursor-movement commands to halt the search.

As with vi, searching in either direction wraps around the beginning or end of the file, depending on which direction you are searching in. When emacs reaches the top or bottom of the file, however, it tells you that the search failed. You can keep searching by pressing C-s or C-r accordingly, and emacs continues using the current string.

To illustrate how searching in emacs works, let's search backward through your file asong2. Type C-r and press s. emacs moves the cursor to the "s" in "works." Now press w. emacs now tries to find a pattern that matches the string sw. The cursor ends up on the "w" in "swell." You can edit the search string using the Backspace or Delete key. Delete the w and press p. What happens?

To perform search-and-replaces, you enter the query-replace command. This is qualified by the M-x command, which tells emacs that the text to follow is a full command and not a key combination. After you have entered the query-replace command, you are prompted for the string to be found. Enter the string and press Enter. emacs then prompts you for the replacement string. After you have entered the replacement string, emacs searches for every instance of the first string and, if it finds one, asks you whether the first string should be replaced with the second string.


NOTE: emacs is actually composed of a set of explicit command names that are bound to key combinations. The query-replace command is bound to M-% in some implementations of emacs.

Using Modes with Buffers

emacs is versatile enough to handle many types of editing chores. It enables you to associate modes to buffers so that you can have text formatting specific to your editing application. If you type the command C-x, m, emacs enters mail mode, which formats a buffer with To: and Subject: fields as well as a space for the body of the mail message. emacs can even send the mail message for you (if you use C-c, C-c) after you have finished editing it.

emacs also supports modes for many programming languages, such as C. When a file with the extension .c (C source code) or .h (C header file) is loaded into emacs, the buffer is automatically set to C mode. This mode has knowledge of how C programs are formatted, and pressing the Tab key indents a line correctly based on its place in the program (a for loop within another for loop, for example).

Online Help in emacs

One of the best features of the emacs editor is that if you ever get stuck, or are just plain overwhelmed by it all, help is just a few keystrokes away--and lots of it! If you need a short emacs tutorial, just type C-h, t. If you would like to find out what function a particular key supports, type C-h, k and then press the key. The help option has many different topics. Use C-h, i to load the information documentation reader and read about all the types of help available.

A Summary of Commands for emacs

emacs, like the vi editor, has such a rich command set that we can cover only a portion of it in this chapter. The following list summarizes the essential commands you need for basic editing in emacs. The emacs man page should be consulted for a more comprehensive description of the full emacs command set.
C b Moves back one character
C d Deletes the current character
C f Moves forward one character
C g Cancels the current command
C h Enters emacs online help
C n Moves forward to the next line
C p Moves back to the preceding line
C s Searches forward for a string
C v Scrolls forward one screen
M v Scrolls backward one screen
C x u Undoes the last edit
CxCc Exits emacs
CxCs

Saves the buffer to a file

The joe Editor

The joe editor, written by Joseph H. Allen, is very easy to use for folks who are coming to Linux from a DOS environment. The editor's look and feel is very similar to the old Wordstar editors, and it might be comfortable for users of the DOS edit program. The joe editor is handy for quick edits and is powerful enough to be a decent programmer's editor.

The joe editor is a shareware program that is distributed under the GNU license. You can get the full package from ftp sites on the Internet free. The latest version at the time of writing was version 2.2. The joe editor comes with the Slackware CD, so you don't have to go to the Internet to get it if you can live with the next-to-latest version. When installing Linux, you have a choice to install joe if you chose the verbose option. If you did not choose to install joe at installation time, you can always run the setup program again and install it later.

Also, don't look for a commercial version of joe. Joseph Allen clearly states in the man pages that he is not interested in commercializing this editor. The man pages come with more than adequate information on how to use the editor and its command-line options.

The primary advantage of the joe editor is its simplicity of use. An on-screen help menu for all the basic commands is available at any time. Type the command joe on the command line to invoke the editor. You can type the name of one or more files to edit by specifying them on the command line:

$ joe filename



$ joe file1 file2 file3

Don't let joe's easy-to-use interface fool you into believing that it's not a powerful editor. Many features in joe make it a good, useful editor.

A Summary of Commands for joe

After you are in the editor, you can type directly into the window that's presented. Use the arrow keys to move your cursor.

Help is not far away if you get stuck. Type Ctrl-K, H and you are presented with a help menu as shown in Listing 16.1. The documentation in the man pages for joe use the notation ^K to represent pressing the Control key and the K key simultaneously. This is the convention to follow in this section. (In the emacs editor, we would have specified it as C-k.) It's best to stick with the same documentation style that comes with the documents for each editor.

Listing 16.1. Commands for the joe editor.



CURSOR            GO TO             BLOCK      DELETE   MISC         EXIT

^B left  ^F right ^U prev. screen   ^KB begin  ^D char  ^KJ reformat ^Ksave

^P up    ^N down  ^V next screen    ^KK end    ^Y line  ^T options   ^Cabort

^Z previous word  ^A beg. of line   ^KM move   ^W >word ^R refresh   ^KZ sh

^X next word      ^E end of line    ^KC copy   ^O word< ^@ insert    FILE

SEARCH            ^KU top of file   ^KW file   ^J >line SPELL        ^KE edit

^KF find text     ^KV end of file   ^KY delete ^_ undo  ^[N word     ^KR insert

^L find next      ^KL to line No.   ^K/ filter ^^redo   ^[L file     ^KD save

The commands are fairly straightforward and are not case-sensitive. For example, copying and moving text requires the use of the block feature. Mark the start of the block by pressing ^KB after moving the cursor to the start of the text. Then move the cursor to the end of the text to be copied, and press ^KK. To copy the block, press ^KC, or to delete the block press ^KY. A limited redo/undo feature can be invoked with the ^^ and ^_ keys, respectively.

The editor can be customized with the use of command-line options. The listed options include setting the baud rate for screen refresh, tabs, word wrap margins, and which line number to start at. For example, the command

$ joe +23 ch16.txt

starts the joe editor on the file ch16.txt and places the cursor on line 23 of the file.

Movement in the editing window is done with the arrow keys or via the commands shown in Listing 16.1. The ^K key followed by a space character lists the current line number.

The current file is saved with the ^KB command. New files can be edited with the ^KE command. You can read in the contents of another file with the ^KR command. All commands prompt you for a filename. To abort the current edits, type ^C.

One of the nice features of joe includes filename completion when you press the Tab key as the response to a command. When prompted for a filename, press the Tab key and joe attempts to fill in the name of the file with closest name. If more than one match exists, you hear a beep. Just press the Tab key repeatedly to have joe list all the available choices.

You can type over any of the choices shown on the prompt line if you want to manually complete the filename. To set up the joe editor as the default editor on your account, you set your environment variables EDITOR and VISUAL to joe.

When Should I Use joe Rather Than vi or emacs?

Before you take this step and begin using joe, you should be aware of some drawbacks of using the joe editor.

First of all, joe's simplicity might turn off the programmer in you. If you are an emacs or vi hack, the joe editor might seem a little too simple to use. Choosing a text editor is still a very personal decision.

Second, the use of the arrow and control keys to move around in a text file might confuse some of the dumb dialup programs. Actually, vi is best suited for dialup situations in which control keys cause havoc. On many occasions, I have been logged on to computers aboard seafaring vessels using archaic means of communication and yet have been able to use vi and not emacs! Finally, you cannot extend joe the way you can extend emacs. No doubt, of the three editors discussed here, emacs is the most powerful in terms of extensibility.

Despite these "drawbacks," the joe editor has some remarkably good features. For one thing, there is support for the use of regular expressions in joe. Also, you can copy vertical blocks of text with the ^TX option.

Macro Recording and Playback

joe also has the capability to record and play back macros. Up to 10 macros can be recorded per session. Each macro is numbered from 0 to 9. Use the ^K[ key and then a number from 0 to 9 to number the macro. The editor then starts recording your keystrokes. Use ^K] to stop recording. All keystrokes typed in-between are applied to the text in the window. To initiate playback, use ^K and then the number of the macro you just recorded. For example, the following keystrokes record a macro to put /* and */ around a line:

^K[ ^A /* ^E */ ^K]

You can use multiple windows to edit more than one file! The ^KO command opens another window. You can have many windows open at one time. The ^KN and ^KP commands let you traverse the next and previous windows, respectively. The ^KI command toggles the zooming in and out of the contents of a window. Try this with vi!

All in all, the joe editor is a nice, simple, yet powerful editing tool for Linux.

Summary

Many text editors are available for the Linux system. This chapter introduced three of the most popular editors: vi (which is actually an alias to the elvis editor), joe (an editor based on the old Wordstar and DOS edit editors), and emacs (the editor for "power programmers"). Each text editor provides basic editing functions, such as inserting and deleting text, reading and writing external files, text searching, and copying and moving text. vi is a full-screen editor that has two modes: command mode and text mode. An X Window version of vi, xvile, is available from sunsite.unc.edu in the /pub/Linux/apps/editors/vi/vile-5.5.tar.gz file. emacs is an extendible and powerful editor that is highly configurable to suit various editing tasks (such as programming, document writing, and changing user or system files). An X Window version of emacs, Xemacs, is also available from http://www.xemacs.org. The joe editor is a full-screen editor suitable for teaching folks how to use editors, as well as for use by programmers. To find more editors for Linux, you can look in the /pub/Linux/apps/editors directory on sunsite.unc.edu.