The battle of the Linux text editors has been going on for years. In this Daily Drill Down, Michael Jennings gives you his reasons for choosing Emacs.
Everyone should learn vi.
Okay, so I'm beginning an Emacs Daily Drill Down by saying that everyone should learn vi. Am I insane? Well, quite possibly, but that's not really the point right now. I am a die-hard Emacs user, but I know how vi works and how to get around in it. I truly believe that anyone who wants to work in UNIX, especially as a system administrator, should know vi. Why? Because vi is omnipresent. If you have a UNIX system, you are basically guaranteed to have vi in some form on that system. Furthermore, if you are forced to boot your system into single-user mode or from a rescue disk/CD, chances are you will have a statically linked vi sitting around with which you can do any needed editing.
That, however, is where my affinity for vi ends. Although vi makes a great crutch in times of crisis, it is not at all ideally suited for daily editing tasks. As a programmer, I have always used Emacs for writing and editing code. It provides a complete, robust environment for software development, which vi has never had and never will.
Before I continue, however, I must point out that the statements in this Daily Drill Down will pertain solely to GNU Emacs version 20.x versus standard UNIX vi. I will not discuss vi spin-offs (like vim, gvim, nvi, elvis, etc.), nor will I discuss Emacs spin-offs (jed, xjed, XEmacs). Many of the arguments against vi are resolved by vim, and many of the arguments against Emacs are resolved by jed. Once you have chosen which camp you'll inhabit, you can then choose the tent in which you will sleep.
I would also like to dispel a myth brought up by my colleague in her vi Daily Drill Down, “Why I love vi.” Emacs does not stand for [Esc][Meta][Alt][Ctrl][Shift], as many people seem to believe. The name Emacs stands for Editor MACroS. The very first Emacs was a set of macros written for an editor called TECO, used on ITS in the mid-’70s.
Now that we've gotten that out of the way, let's move on, shall we? In this Daily Drill Down, I’ll simplify the vast greatness of Emacs down to a few points:
- Emacs is complete.
- Emacs is flexible.
- Emacs is extensible.
- Emacs is standard.
Emacs, unlike vi, is a complete editing environment. It's not just a simple editor. It provides an interactive shell, built-in terminal emulation, syntax highlighting (for just about any language), automatic language-based indentation, automatic line wrapping, and so much more. And every bit is entirely optional; it pops up only when you want it to, and it can be turned off at any time.
On the other hand, vi does not provide any of these features. In fact, vi is really very little more than an adaptation of the ed editor, a line-based editor for UNIX that closely resembles DOS's EDLIN in usability. (Incidentally, the popular sed command on UNIX stands for Stream EDitor and is basically a non-interactive version of ed that works with files and pipes.) Thus, the usability of vi itself is only slightly higher than that of ed, as any newcomer to vi will quickly learn the moment he or she opens vi and tries to start typing something.
The number of options with which Emacs comes is enormous. You can alter and tweak just about every behavior Emacs has. In fact, Emacs comes with a module called Viper that allows it to emulate the common vi key sequences. I could never hope to detail every single feature you can customize in Emacs. I've already given you a few examples; you'll just have to take my word on the rest or keep reading this Daily Drill Down.
Unfortunately, my colleague is mistaken in her statement that you can do anything, absolutely anything, with vi. For example, vi cannot emulate Emacs' key sequences; display color syntax highlighting; run in a native X11 application window as well as in a text terminal; display a customizable status bar with line/column numbers, the date, and even the system load; or provide pop-up menus for easier use. These are just a few examples. Emacs does all these things, and they are not simply useless features that bloat; they are very handy tools to have in an editor.
Emacs is infinitely extensible. This may sound like a bold statement, but there are people who use Emacs to read USENET news, send e-mail, or browse the Web. Some people even use Emacs for their shell!
How can an editor do all these things? Emacs isn't just an editor. Emacs is actually a LISP interpreter that comes with an enormous number of pre-written LISP modules that provide all its functionality. Even the user-level configuration file for Emacs ($HOME/.emacs) is an Emacs LISP file. Here are a few lines from mine:
(global-set-key "\M-g" 'goto-line)
(global-set-key "\M-rs" 'replace-string)
(global-set-key "\M-re" 'replace-regexp)
(global-set-key "\C-xrk" 'kill-rectangle)
These lines set up some key bindings that make it faster to execute some commands I use a lot. The first one, for example, binds [Meta]g ([Alt]g for keyboards with no [Meta] key, or [Esc]g also works) to a LISP function called goto-line. This LISP function prompts me for a line number, then jumps right to that line—very useful for hunting down compiler warnings or errors, for example. The other lines bind similarly handy keystrokes to oft-used commands that do string search-and-replace, regular expression search-and-replace, and rectangular kills. (Ever needed to delete a column of data in the middle of a bunch of columns of data? That's exactly what kill-rectangle does—it deletes a rectangular area.)
I can't begin to show you everything you can do with Emacs LISP. But it provides a level of control and power vi simply cannot compare with.
Emacs key sequences are everywhere. The default shell on Linux, bash, uses Emacs key bindings by default. (On other UNIX flavors, you can get to Emacs editing mode from ksh using the command set -o emacs.) You'll also find them in Netscape on UNIX. (Try pressing [Ctrl]E in the Location entry box sometime. That will get you to the end of the line, just like [Ctrl]A will get you to the beginning of the line and [Ctrl]K will delete everything after the cursor. Cool, eh?) A popular UNIX IRC client, ircII, uses Emacs keystrokes also, as do its derivatives (EPIC, BitchX, etc.).
Furthermore, any interactive program that uses the GNU readline library (like MySQL, Samba, Python, and PostgreSQL) uses Emacs-like key sequences by default for line editing. So once you learn the basic Emacs keystrokes, you'll be able to use them in many different programs on UNIX. (Out of fairness, I should mention that many programs use vi sequences, like ksh and the less pager. However, many programs cannot use them, due to the conflict between navigation keys and normal letters. But as I said at first, it's always wise to know the vi sequences.)
Getting started with Emacs
Thankfully, learning Emacs does not involve the painful realization that you cannot simply open an editor and start typing, nor does it entail pressing lots of keys and wondering why nothing is happening. With Emacs, you can simply run the command emacs and start typing in the editor.
One of the worst features of vi is the fact that the keys used for navigation (j, k, l, h, etc.) are normal letters. This means that vi must have different modes to distinguish j the "I want to move the cursor down a line" key from j the “I want a j to appear” key. That's why nothing happens when you start typing in vi until you press a key that enters edit mode, like a or i.
Thankfully, Emacs doesn't have this problem. Emacs wisely chose to avoid such conflicts by using modifier keys, which your terminal (or terminal emulator) has. These keys are [Ctrl], [Meta], and [Shift]. For those with 104-key keyboards on Linux, the [Meta] key will most likely be the key with the Microsoft Windows logo on it, or possibly the [Alt] key. If you have a Sun keyboard, the key with a diamond on it is [Meta]. If all else fails, pressing the [Esc] key works just like holding down [Meta].
Emacs uses abbreviations to represent the various keystrokes. Here is a list of the most important ones:
|C-||Hold [Ctrl] and type the following letter.|
|M-||The same, but with the [Meta] key. Or press [Esc] and then press the following letter.|
|S-||Hold [Shift] and type the letter.|
|f1-, f2-, etc.||Press the appropriate function key and then the following letter.|
|RET||Press [Return] or [Enter].|
|SPC||Press the Spacebar.|
|mouse-1, mouse-2, etc.||Click the appropriate mouse button.|
These abbreviations are often combined to form key sequences, or series of keystrokes that accomplish an end result. For example, C-x C-c means, "Hold down the [Ctrl] key and press the x key, and then hit the c key while still holding down the [Ctrl] key." Likewise, my previous kill-rectangle example, C-x r k (or simply C-xrk), means, “Hold down [Ctrl] and press x, release the [Ctrl] key and press r, and then k.” The abbreviation M-x goto-line RET is a little more complicated. It means “Hold [Meta] and press x, and then type goto-line and press the [Enter] key.” (As I mentioned earlier, if you don't have a [Meta] key, and holding [Alt] doesn't work, just press [Esc] instead.)
To start up Emacs, simply type emacs at the command line and press [Enter]. If you are running under X11, a graphical Emacs window will pop up, complete with scroll bar, menu bar, status line, and so forth. To open a file, simply select Files | Open File. The Files menu also contains Save, Save As, and Exit options, in addition to items for opening directories, recovering sessions (in case the system crashes while you're editing), inserting a file into the current buffer, splitting the display into multiple panes, and more.
The pop-up menus make it easy to get acquainted with Emacs, so I recommend getting started while running under X11. The menus are easy to navigate, and they list the keystroke commands for all the menu items that have them, greatly simplifying the learning process. However, if you are stuck in text mode, don't worry. I'll discuss the key bindings anyway, since they make common operations very quick.
If you have a file you'd like to try editing, go to a command prompt and type emacs <filename>, where <filename> is the name (with or without a path) of the file you wish to edit. If you don't know which file you want to work on, you can instead run emacs <directory>, where <directory> is the name of the directory you want to view. Emacs will pop up a window containing the contents of that directory; simply middle-click your choice (or, if you’re using a two-button mouse, click both buttons simultaneously) to edit that file. (Unlike vi, Emacs doesn't try to edit the directory as if it were a file. Emacs is more intelligent than that.)
Emacs can also open several files at a time, something else vi doesn't handle very well. Simply list all the filenames on the command line, separated by spaces. Emacs will open all the files you specify, each into its own little workspace, or buffer, in Emacs-speak. All of the various buffers you have are listed in the Buffers menu, which you can access from the menu bar by pressing C-x C-b (remember, that's [Ctrl]x followed by [Ctrl]b, or just hold down the [Ctrl] key and press x, and then b), via M-x buffer-menu RET or via C-x b [Tab][Tab]. The menu bar is easiest, of course, but if you make an effort to use the keystrokes as much as possible, you'll find that they quickly become second nature and that you can hold down [Ctrl] while pressing x s x c much faster than you can flail your fingers around the keyboard pressing [Esc] :wq [Enter].
Earlier, I promised that I'd go over the basic keystrokes in Emacs for various tasks. I'll give you the keystrokes as we go along. Here are the keystrokes for manipulating files and buffers:
|Open file||C-x C-f|
|Close file (close buffer)||C-x k RET|
|Save file||C-x C-s|
|Save file as||C-x C-w|
|Exit Emacs||C-x C-c|
|Insert file into current buffer||C-x i|
|Change to a different buffer||C-x b|
|Split window into two||C-x 2|
|One window (reverse of the above)||C-x 1|
So let's do an example. Start out by typing emacs by itself on the command line, and then press [Enter]. Emacs will pop up and display a brief copyright/version screen. Now, let's start a new file. Press C-x C-f and type a name for a file that doesn't already exist. Press [Enter] when you've finished. If you watch the minibuffer (the thin one-line area at the bottom of the Emacs window, just below the status line), you'll see that it says (New file). Now, just start typing. Notice that there is no command mode or text mode in Emacs the way there is in vi. You just start typing, exactly as you'd expect.
So type some stuff—it really doesn't matter what. Now press C-x C-s. The easiest way to do this is to simply hold down [Ctrl] while you press the x key followed by the s key (it's also the fastest way). When you do this, Emacs will save the file under the name you specified earlier. If you watch the minibuffer, it will say Wrote <file>, where <file> is the complete path and filename of the file you saved. If you wish to save under a different name, simply press C-x C-w and type the new filename, followed by [Enter]. You'll see that the filename in the status line is changed to the new name as well; in the future, if you press C-x C-s to save, the new name will be used, not the old one.
Okay, now type some more stuff. When you've finished, it's time to save and exit. So press and hold [Ctrl] with your left pinky finger, then using your index and middle fingers, press the following keys in succession: x s x c.
That's all there is to it. As you get more comfortable with Emacs, you'll find that the save-and-exit key sequence gets quite fast. As a side note, if you simply press C-x C-c to exit and haven’t saved everything, Emacs will ask you if it should save the unsaved buffers before exiting.
Of course, being able to create a file just isn't enough. You need to be able to edit that file, which means learning how to navigate in Emacs. The standard arrow keys work as you'd expect, as do the [Page Up] and [Page Down] keys. The [Home] and [End] keys go to the beginning and end of the file, respectively. In addition to those keystrokes, the following navigation keys work in Emacs:
|Forward one character||C-f|
|Backward one character||C-b|
|Up one line||C-p|
|Down one line||C-n|
|Forward one word||M-f|
|Backward one word||M-b|
|Beginning of line (BOL)||C-a|
|End of line (EOL)||C-e|
|Up one page||M-v|
|Down one page||C-v|
|Beginning of file||M-<|
|End of file||M->|
You can't really edit files without knowing a few basic editing keystrokes, so here are the big ones:
|Search for a string||C-s|
|* Search and replace||M-r s|
|* Search and replace by regexp||M-r e|
|Interactive search and replace||M-%|
|Interactive regexp search and replace||C-M-%|
|Begin selecting text||C-SPACE|
|Kill line (delete to end of line)||C-k|
|* Kill a rectangular area||C-x r k|
|Refresh screen and re-center||C-l|
Pay special attention to that last one, [Ctrl]Underscore (or [Ctrl][Shift][Minus]). Undo is a quite handy thing to have. Emacs has basically infinite undo capability. Unlike other editors, however, undoing an action is an action in and of itself. So if you undo a bunch of operations, then use the arrow keys to move around and subsequently try to continue undoing, you'll find that the first thing that gets undone is all the undoing you just did! So it's basically like a redo there. However, if you continue to undo, you'll find that those actions will eventually get undone again, followed by what came before that. (I realize that my explanation may have made no sense whatsoever. That's okay. After playing around with Emacs' undo facility for a while, you'll become accustomed to how it operates, and the above paragraph will subsequently make perfect sense. It's just hard to explain without being able to demonstrate.)
You'll notice that some of the above key sequences have asterisks beside them. This is because they may not be enabled by default in your version of Emacs. However, earlier in this Daily Drill Down I showed you a few lines from my own .emacs file; these lines enable the behaviors I mention in the table above. So let's create an .emacs file containing those lines now.
At the command line, type emacs $HOME/.emacs and press [Enter]. If you already have an .emacs file, it will be opened; if not, Emacs will be ready to create it. Now, select the lines that I included earlier in the Daily Drill Down using your mouse. Go to the Emacs window and press C-y, or click the middle mouse button. This will paste those lines into the .emacs file.
If you're lucky, those four lines got pasted properly so that the first parenthesis of each line is aligned in the first column. However, chances are that the second through fourth lines have a bunch of spaces in front of them. Fortunately, this is easy to fix with Emacs. Go to the very beginning of the second line and press C-SPACE (that's [Ctrl]Spacebar). Now move the cursor to the first parenthesis on the last line and press C-x r k. This runs the kill-rectangle command, which deletes all those annoying leading spaces. (If that key sequence doesn't work for you, try M-x kill-rectangle RET instead.) Now save and exit (C-x C-s C-x C-c).
Two final tidbits
If you edit a file for a long time without saving, you'll notice that Emacs says Auto saving.... Emacs periodically saves your work in progress to disk so that it can be recovered in case of a system crash. If this happens to you, simply run Emacs on the file again. It will warn you that a newer backup copy exists and that you should consider running M-x recover-file. To recover your work, simply select Recover Session from the Files menu, or type M-x recover-file RET followed by the name of the file you wish to recover.
So what is with all this M-x stuff? The secret to Emacs' power is that every task it performs is a LISP function. For example, when you press [Ctrl]f to move forward one character, what Emacs actually does is execute the built-in LISP function called forward-char. When you hit C-x C-s to save a file, Emacs runs the save-buffer LISP function. Selecting Save Buffer from the Files menu runs the exact same function.
Pressing M-x allows you to ask Emacs to run a specific LISP function without knowing the key sequence for that function. So instead of C-x C-s, you could type M-x save-buffer RET and accomplish the same thing. In fact, M-x itself is bound to a LISP function called execute-extended-command.
So why should you care? Well, other than the fact that M-x is used all over the place within Emacs, it's important to know that these functions exist. If you look at the .emacs file I just created for you, you'll see that I've shown you how to bind your own key sequences to various LISP functions. So if you know what function performs a particular task, just add a global-set-key line in your .emacs file to bind it to whatever you wish.
How do you find these function names, you ask? Try typing M-x and then pressing [Tab]. You'll see a complete list of all the LISP functions you need. However, this list can get a little daunting, so Emacs has some built-in describe commands that help document what various keystrokes and functions do. Look at the Describe menu under the Help menu for more information.
In this Daily Drill Down, I've only begun to scratch the surface of everything you can do with Emacs. I highly recommend taking the time to go through Emacs' built-in tutorial (accessed from the Help menu) at least once to learn more about what it has to offer. Also try out the Customize tool (M-x customize), which simplifies creation and management of your .emacs file without having to know E-LISP.
Emacs is to editors what Perl is to scripting languages. If it exists within the realm of possibility, chances are Emacs can do it. I'll leave you with a quote from the author of vi—who, by the way, does not use vi anymore. If the author himself won't use vi, why would you?
“People don't know that vi was written for a world that doesn't exist anymore.”—Bill Joy, author of vi
Michael Jennings is the creator of Eterm, a terminal emulator for the X Window System. He is a software engineer at VA Linux Systems.The authors and editors have taken care in preparation of the content contained herein, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for any damages. Always have a verified backup before making any changes.