Using Common Command-Line Editors





Using Common Command-Line Editors

In the preceding chapter, you created a few text files using the touch command, but they were all empty text filesunlikely to be of much use for any common purpose. Most of the time if you're creating a text file, you need it to contain specific text that you enter yourself.

At the Linux command line, two major editors are commonly used to create text filesand they are polar opposites. The first is a small, classic Unix tool called vi; the second is a large, extensible data processor called emacs. You can use either editor to create the kinds of documents you want to create at the Linux command line. The vi editor is generally preferred by users who want a minimal, fast, no-frills editing experience, and the emacs editor is generally preferred by power users. The editor you choose to use on a daily basis is ultimately a matter of personal preference and little more; some Linux administration tools integrate the vi editor as part of their functionality, however, so you should at least become moderately familiar with vi.

Text Editor Versus Word Processor

Although most computer users are familiar with the term word processor, the term text editor is less widely known.

A word processor includes features designed for desktop publishing, such as typeface selection, layout controls, and formatting options for the printed page. A text editor is designed to edit letters and numbers only; a text editor does not offer features for controlling the appearance or layout of text in printed output.


Using vi to Create or Edit Text Files

The vi editor is popular because, unlike emacs, it's nearly always present, even on the most minimal system. It's also popular because, unlike emacs, vi is small and fast.

Begin work on an empty document now by typing the vi command followed by the name of the file you want to create as an argument. Call this file myvifile.txt:

[[email protected] ~]$ vi myvifile.txt

If the File Exists, It Will Be Loaded

Starting vi does not always create a file. If you supply the name of an already existing file as the argument to vi, that file is loaded into vi so that you can edit it.


You always know you're working in vi when you see the line of tilde (~) characters stretching down the left side of your console. These characters indicate that there is no text yet on any of these lines. Don't actually try to type anything yet; you won't be able to. The vi editor is line-oriented and has two modes. When you first start vi, you are in a mode not designed to allow text entry.

You are looking at the command mode right now. Anything you type, including normal alphabetic text, will not appear in the document; rather, it will be interpreted by vi as an attempt to demand action. In command mode, you can save your file, move your cursor around, delete phrases or lines of text, and so on.

The insert mode is the only mode in which you can directly enter text, and while vi is in the insert mode, text entry is nearly the only thing you can do. This two-mode system inevitably confuses new vi users at first, but after a little practice, most people become comfortable with it.

Let's insert some text.

Inserting Text in vi

To begin inserting text in the vi file you're working on, myvifile.txt, press the i key. Notice that the word INSERT appears at the bottom of the display, as shown in Figure.

Figure. The vi editor in insert mode, waiting for you to enter text. All keyboard entry from now on is considered text input until you press the Esc key.


Enter a few lines of text now. Follow along with the examples here or enter your own text. Note that there is no word wrap in vi; when you come to the end of a line, you must press Enter to start a new line of text:

The vi editor is ubiquitous in Unix. Because of this, it is important
that all aspiring Unix users understand how to interact with vi.

There Is No Word Wrap in vi

If you choose not to press Enter before you reach the right side of your display, the text on your screen wraps around to the left side of the display in mid-word. Understand, however, that the text in vi's memory buffer does not. If you manage to fill the entire screen full of text without ever pressing Enter, the file you save is stored as one long line of text.

Having just one long line of text can have unexpected consequences when you're printing, emailing, or even editing text files.


When you finish entering text, press the Esc key to exit the insert mode and return to command mode. When you do so, notice that the word INSERT disappears from the status line at the bottom of the screen.

Now you've inserted some text. But what if you want to change what you've typed so far? In vi, the methods for making changes aren't always obvious.

Editing Text in vi

You use keystroke commands to navigate and edit text in vi. Figure shows some of the most common keystrokes.

Figure Common Keystroke Commands for Editing and Navigating in vi

Keystroke

Action

l

Move cursor one character to the right.

h

Move cursor one character to the left.

j

Move cursor down one text line (not one display line).

k

Move cursor up one text line (not one display line).

x

Delete the character immediately under the cursor.

d#<Space>

Delete # characters immediately under and to the right of the cursor.

dd

Delete the current line.

i

Insert: Return to insert mode, inserting immediately under the cursor at its current position.

a

Append: Return to insert mode, inserting immediately to the right of the cursor at its current position.

A

Append: Return to insert mode, inserting at the end of the current text line (not display line).

Esc

Return to command mode.


Try using the movement and editing keys in command mode to alter the text you just entered, to delete a line or a few characters of text, or to insert or append some text to the file. If you get confused, the keyboard stops responding, or keys don't work as you expect them to while you are editing, you have likely keyed incorrectly; press Esc several times to ensure that you return to the command mode.

You Can Use the Arrow Keys in vi

If you've been following along and experimenting with vi, you've likely discovered that it's actually easier than we've made it out to be. Fedora Core 4 uses an enhanced version of vi called vim. In this enhanced vi editor, you can use your arrow keys to navigate through the text, even in insert mode, as long as your terminal is properly configured (as is the case at the Linux console).

This enhanced version of vi isn't present on most Unix systems, however, or even on all Linux systemsand vim might not be included in future versions of Fedora Core 4. Furthermore, some administration situations can limit you to traditional vi keys even while using Fedora Core 4. You should become familiar with the traditional vi keys and behaviors, in case you find yourself working in a traditional vi editor in the future.


Experiment with vi for a while and try to become familiar with it; you'll encounter it often enough in Linux to make it worth your time.

Saving and Quitting

Let's save the file you just created by entering what may seem like a very cryptic command. Type a colon (:) now. Notice that a colon appears at the lower left of the display and that the cursor has moved there; vi is now waiting for you to enter a more complex command. Type a lowercase w and press Enter. The vi editor responds with a status update at the lower left of the display:

"myvifile.txt" [New] 2L, 135C written

First, vi indicates the name of the file that has just been saved; you called this file myvifile.txt. Next, vi gives the number of lines in the file (2), followed by the number of individual characters in the file (135). You have now saved your first vi file.

A Save As function is also available in vi. To save your text again, this time as a new file, type a colon, and then enter w followed by a space and the name mynewvifile.txt. The vi editor responds with

"mynewvifile.txt" i[New] 2L, 135C written

You now have two copies of the file in your home directory: myvifile.txt and mynewvifile.txt. That's enough of vi for this book. To exit vi, type a colon and then type q. This command quits vi and returns you to the command prompt.

If You Haven't Saved, vi Will Let You Know

If you try to exit vi without first saving the file you've been working on, vi interrupts you with an error message indicating that your file has not been saved; it then returns to command mode.

If you really want to exit anyway, use :q! (with the exclamation mark added) instead of simply :q to exit; vi then complies.


vi is powerful and worthy of some study, both because of the number of efficiency-oriented editing features it provides and because you will so often encounter it while using Linux or Unix computers at the command line. If you're feeling adventurous, you can explore the bulky online help system in Fedora Core 4's version of the vi editor by restarting vi and entering :help while in command mode. The resulting title page appears in Figure.

Figure. The title screen for the vi (vim) online help system. The help is reasonably extensive, and you can become quite a vi expert simply by reading these documents.


More Detailed vi Information Is Available

You can find a more complete vi tutorial in Sams Teach Yourself Unix in 24 Hours, by Dave Taylor.


Using emacs to Create Text Files

If you found vi to be too minimal for your taste, you'll likely feel better about emacs, although emacs also has its quirks. Whereas vi's focus is on minimalism, basic functionality, and speed, emacs is extensible and programmable and has over the years grown into a monster of a system. Very few people on Earth know everything that can be known about emacs; there are hundreds of modes and commands and an entire programming language (Emacs LISP) to master.

For our purposes, however, emacs is going to seem friendly and simple compared to vi. You can start emacs the same way you started vi: Type the emacs command followed by the name of the file you want to open or create as an argument. Use the filename myemacsfile.txt:

[[email protected] ~]$ emacs myemacsfile.txt

Depending on your system configuration, loading emacs might take somewhat longer than loading vi. emacs is a much larger and more complex editor than vi. After emacs loads, you find yourself looking at the screen shown in Figure if you started emacs in a virtual console, or at the new application window shown in Figure if you started emacs from a desktop Terminal.

Figure. The emacs editor clearly has a more accessible look than vi and is designed to function in some ways that Windows users are more accustomed to.


Figure. If you start emacs from the Terminal application on your desktop, it looks like and responds to mouse clicks just like any other application.


Starting emacs from a desktop Terminal opens a new window, complete with point-and-click menus. You should still learn the keystrokes in this chapter, though! Inserting text into the emacs editor is easy: Just type. The arrow keys, Backspace and Delete keys, Page Up and Page Down keys, and Home and End keys all behave as you expect them to.

When you reach the end of the first line, you'll soon find out that, like vi, emacs does not normally automatically word wrap. Remember to press Enter at the end of each line because emacs is a line-oriented editor. If you don't press Enter at the end of each line, only one very long line of text is written when you save your file.

Using the emacs Menu System

If you are using emacs on the desktop, a familiar and relatively user-friendly menu bar appears across the top of the application window; you can navigate through it just as you normally would using your mouse.

Although the top of the emacs display in a virtual console might appear to have a menu bar as well, this isn't really the case. There is no way to visually activate drop-down menus at the console.

You can, however, access the fairly intuitive emacs menu in a virtual console by pressing the F10 key at almost any time. When you press F10, your display is split in two, and the lower half of your display fills with options that you can activate with a single keypress (see Figure).

Figure. When you bring up the emacs menu system at the console, you can activate each item by pressing its respective key.


To save the file you have been working on, press f to open the File menu and then s to save it after the File menu appears. emacs displays a message in the small area at the bottom of the screen, known as the minibuffer, to let you know that the file has been saved:

wrote /home/you/myemacsfile.txt

You can use the F10 menu system in emacs to perform most basic editing, saving, and loading functions at the command line. For most users, the F10 menu and simpler editing style make emacs the editor of choice over vi.

Using Essential emacs Keystrokes

If you aren't too ham-handed, you might be able to use emacs and the F10 menu for months or even years without getting into trouble. However, an accidental keystroke that leaves emacs expecting additional commands may leave you sitting in front of a beeping emacs editor printing cryptic error messages or demands in the minibuffer.

The essential keystroke to know at such times is written in the emacs documentation as C-g (hold down Ctrl and press g). This combination is the emacs abort keystroke. The emacs editor is large enough and complex enough that there will be many opportunities, after mis-keying, to find yourself in an unknown state with respect to emacs' expectations; most of the time, repeatedly pressing C-g until things return to normal is the solution to this type of confusion.

Figure lists a few other interesting emacs keystrokessome accessible from the menu system, some not. To understand this table, you must first become familiar with the format of emacs keystrokes:

  • C-x, where x is a letter, means hold down the Ctrl key and press the letter.

  • C-xy, where both x and y are letters, means hold down the Ctrl key, press the first letter, release both the Ctrl key and the first letter, and then press the second letter alone.

  • M-x, where x is a letter, means hold down the Alt key and press the letter.

  • C-x C-y, where both x and y are letters, means hold down the Ctrl key, press the first letter, and then, without releasing the Ctrl key, press the second letter.

Figure Useful emacs Keystrokes

Keystroke

Explanation

C-ht

Launch the emacs tutorial, in which many more keystrokes are documented.

C-x C-f

Find (open or create) a file in the current editing pane; you are prompted in the minibuffer for a filename or path.

C-x C-s

Save the file you are currently working on.

C-x2

Split the current editing pane vertically.

C-x3

Split the current editing pane horizontally.

C-x1

Cause the current editing pane to fill the entire screen (hide/remove other panes).

C-xo

Select the next editing pane.

C-xk

Close (without saving) the file or buffer you are currently working in. For example, use this keystroke after you've opened the emacs tutorial to exit it again.

C-xb

Switch to another buffer; you are prompted in the minibuffer for a buffer name. If you are unsure about the names of open buffers, press Tab for a complete list.

C-xi file

Insert a file at the current cursor position. You are prompted 1for the name of the file in the minibuffer.

C-x C-c

Exit emacs completely.

C-g

Abort the current emacs process.


Note that the letters in these Control key combinations are case sensitive, so be careful to press the keys indicated, rather than their uppercase or lowercase counterparts.

One final keystroke before we finish our discussion of emacs takes you well on your way to becoming an emacs guru. To see a list of available commands in emacs, press M-x and then the Tab key. A buffer containing a list of emacs commands appears. Press C-xo until your cursor appears in that pane; you can then use Page Up and Page Down to browse through the available commands. If you see one you would like to try, type it into the minibuffer and press Enter.

The various emacs commands include the following:

  • M-x dunnet starts a text-based adventure game.

  • M-x auto-fill turns on word wrap.

  • M-x calendar opens a new pane containing a three-month calendar.

  • M-x shell opens a shell in the current pane. Be sure to use C-x2 or C-x3 before running this one so that you can edit a file and work with the shell at the same time, switching between panes with C-xo, as shown in Figure.

    Figure. An emacs editor that has been split horizontally with C-x2. A shell is started in the lower pane with C-xo followed by M-x shell. You switch between the panes with C-xo.


emacs Makes Backups of Your Files

If you become an emacs user, you will soon find that, from time to time, files appear in your working directory with names similar to those you've been working on, but with slight additions. For example, if you've been working on a file called myfile.txt, you might also find #myfile.txt# or myfile.txt~ in the same directory.

emacs creates these "safety" files in the interest of preserving your data.

When you exit without saving a file, emacs saves the file anyway, under the same name but with hash marks (#) at the front and back, in case you want to recover the changes you made later.

When you make changes to an existing file and save them, emacs preserves the original (unmodified) file under the same name, but with a tilde character (~) at the end, in case you want to return to the original file later.

If you don't want to preserve the autosave or backup files, remove them with rm, although you might want to load them into emacs first to make sure that they don't contain data that you want to save.



     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows