Living in Emacs
Living in Emacs
Living in Emacs
Table of Contents
If you're viewing this document online, you can click any of the topics below to link directly to that section.
Getting started with Emacs requires navigating a steep learning curve. Our goal is to help
you past the initially unfamiliar interface so that the power and utility of Emacs become
apparent. Then you'll be ready to explore further on your own, following up on the resources
and tips at the end of the tutorial.
If you're running Linux, then you might already have it loaded. Check by typing emacs at a
command-line prompt. If nothing happens (or you get a message like "command not found"),
then use the package tools that come with your distribution to install one package or the
other.
Running another operating system? Check the sites linked above for a version of Emacs that
will work for you.
For technical questions about this tutorial, please contact Brian at bilbrey@orbdesigns.com.
Section 2. Origins
Overview
In this tutorial, we'll cover a lot of ground very quickly. First we'll have a look at what Emacs is
and where it comes from. Then we'll jump right into using the editor, starting with keystrokes,
commands, the Emacs environment, and some of the elemental commands you need to get
started. I'll show you how to add and delete, kill and yank text in a variety of ways.
The next leg of our journey is an introduction to Emacs' cursor navigation scheme. That's
followed by an examination of the search and replace features. After that, I'll show you what
Emacs does with files and buffers. I'll wrap the trip up with a few glimpses at the higher
functions and extra features that you can only find in Emacs, from modes to coding to
connectivity to games.
At the end of this tutorial, you will be comfortable moving around in the Emacs environment
and have a sense of the power that's available to you through it. Let's get started.
What is Emacs?
According to a description at GNU.org, Emacs is the extensible, customizable,
self-documenting real-time display editor. It offers true LISP -- smoothly integrated into the
editor -- for writing extensions and provides an interface to the X Window System.
It has also been said (perhaps not entirely in jest) that Emacs can do so very many different
things so well that it would make a fine operating system indeed -- if only it had a decent text
editor.
But seriously: Emacs is a robust and extensible text-editing environment that has many,
many additions designed into it, from compiling and debugging interfaces to e-mail, games,
and Eliza. Especially for those who write or code (or both) for a living, it's easy to start up
several Emacs sessions in the morning, start working, and never execute another application
all day, thus the name of this tutorial: Living in Emacs.
There is one major "competitor" to GNU Emacs -- XEmacs -- which is the result of a fork in
the Emacs codebase. This fork took place far enough back that, while major portions of the
user interface are identical or highly similar, the underlying extensions and LISP code are not
compatible. Porting between the two is possible however.
Many Linux distributions are accompanied by both versions of Emacs, although preferentially
one is installed over the other, depending upon the choices made by the publisher. Debian,
for instance, installs GNU Emacs if you choose to install Emacs, as does Red Hat 7.2. The
last time I installed Caldera OpenLinux, it defaulted to XEmacs.
For the purposes of this tutorial, our descriptions, examples, and screenshots are based
upon GNU Emacs. Point your Web browser to
http://www.gnu.org/software/emacs/emacs.html for more details.
But what's Meta? Meta can be a dedicated key (sometimes so labeled), it might be the Alt
key, or perhaps it doesn't even exist in the keymap that your system uses. That's okay; there
is a fallback to Meta, which is to first press the Esc key and then the following character in
turn (instead of together). This yields the same result as M-<chr>.
Now start up your copy of Emacs (or XEmacs), and let's make some quick progress. Type
emacs practice1.text in a terminal or console to get started.
That's why many of the commands are bound to key combinations, prefaced with the Control
and Meta keys. To invoke a named command, start by typing M-x followed by the command
name. To get a list of the key bindings, the long form command is M-x
describe-bindings. Fortunately, there's a keybinding for that: C-h b
Type C-x o to swap to the listing window, C-s to do an incremental search, C-x o to switch
back to your working window, and C-x 1 to close all windows except for the current buffer.
Give that a try, and have a look at some of those commands -- there are about 600 or so that
have key-bindings. Also, don't worry about the commands we used in this quick side trip, as
we'll revisit all of them in turn later in the tutorial.
First instructions
Quitting: When I first started using Emacs, I found that I would get lost someplace in the
documentation, or in a welter of buffers that I was sure I hadn't opened myself, and so on. At
that point, all I wanted to do was exit the system so that I could start over again and figure
out where I went wrong. Here's the sequence you type to exit Emacs: C-x C-c .
From the keystroke convention that you saw in the previous panel, that means to press Ctrl
+ x, followed by Ctrl + c . If you made any changes in any open files, then Emacs will
prompt you, for example:
I'll reply y to any such prompts if I've made changes I care about, or press the ! to simply
proceed with quitting, nothing saved.
To open an existing file after Emacs is started, type C-x C-f to find a file and load it into a
buffer.
On the other hand, I most often want to save the work I've done and then continue typing. So
to save my work and continue, the keystroke combination is C-x C-s .
The main editing window can be split into two or more windows, which can be views of the
same buffer (file), or of different buffers. See the Windows in Emacs on page 18 panel for more
details.
In the initial configuration, the editing window has a demarcation at the bottom by a status
bar (also known as the mode bar). With multiple visible windows, each will have its own
status bar. The status bar has indicators for whether the text in the buffer has changed, the
file name associated with the name, the mode (shown as SGML in the screenshot), the
current line number, and the position of the cursor as a percentage of the entire text. The
mode indicates what type of text Emacs thinks it is working with and modifies the menus and
functions accordingly.
The bottom line, which contains a [Wrote...] message in the screenshot, is called the
mini-buffer. It's used to display partially-typed commands, the results of commands run, and
occasionally to show minimal help.
Did you enjoy that? This is the shortest, easiest panel in this tutorial. Now take a deep
breath, and let's dive in to deleting text.
Delete, at least, has an Emacs equivalent: C-d deletes the character under the cursor. To
undo character deletion, use the C-x u command or the real shorthand, C-_. The latter is
easier for multiple undos. Practice these operations just a bit now to start training your
fingers in Emacs.
Note: Some of the documentation I have read indicates that the Delete key should delete
backwards (the backspace or ^H equivalent) and C-d takes the place of Delete. This
depends on your operating setup and terminal configuration.
Deleted characters are only saved in a buffer for undo, and you can only reach those
modifications by undoing all that's changed since the deletion. The more "advanced" form of
deletion, for multi-character regions, is saved to a different structure as well, and we'll look at
that next.
C-k has a bit of a trick to it. Used once, it kills the text on the line but not the newline
character. That takes a second C-k. There are also commands to kill paragraphs,
kill-paragraph and backward-kill-paragraph, although key bindings don't exist for
those.
So where does your deleted stuff go? Into the kill ring, of course. Multiple sequential deletes
(for instance, repeating C-k several times) goes into the kill ring as a block, which is very
handy. In the next panel, we'll look at accessing that data.
Type C-y to yank the most recent block. Repeating C-y merely yanks that block again.
To get at the older "killed" items, type C-y first, and you'll see the most recent block. Then,
type M-y to step back through the kill ring. Each step replaces the prior yank. Give it a try
now -- it's really quite handy.
For example, typing C-u 6 C-k kills three lines. Yes, that's three lines, not six. Remember
that with kill-line, the text on the line and the newline are done separately. Not hard to
get your head around, once you've used it a few times.
C-k kill-line
C-y yank is the paste equivalent
M-y Traverse the kill ring, must follow C-y
C-u, C-u N universal-argument, adds count
prefix to commands
The native key navigation has the additional advantage of keeping your hands on the
keyboard, where they belong, both for productivity and ergonomic reasons. I find that the
context switch between keyboard and mouse costs me about 10% productivity when I'm
using a tool in GUI mode.
Fire up Emacs as before (type emacs practice1.txt), and type a few lines (or copy this
panel) into the initial window that you're presented with.
Little steps
Emacs occasionally uses character mnemonics to
assist you, as your fingers learn the commands
without conscious effort. Just remember Previous,
Next, Forward, and Back. The first letter of each is
your motion key.
Practice these in the test document and keep using them. I found that I had to force myself
not to use the cursor keys or the mouse for a while. By keeping my fingers on the home row
and consciously using these commands, I was soon navigating through each file's buffer with
ease.
A standard forward incremental search is initiated with the C-s command. Searching
backwards from the cursor position is accomplished with the C-r (isearch-backward)
command. There are a variety of in-search commands available; you can get a complete
description by typing:
C-h d isearch-forward
Highlights include incrementing through the matches by typing C-s for forward or C-r for
backward steps. Also, press Enter or C-g to terminate the search when you've reached your
goal.
Regexp searches
Regexp searches are also incremental but make use of regular expressions to permit more
powerful search capabilities. I won't cover regular expressions in this tutorial, but you can find
many good resources in print and online (see Resources on page 24 ).
To start a forward regexp search, type ESC C-s (that is, Escape then Control plus the 's'
key). To search backwards similarly, use ESC C-r.
For example, let's say that I have the words bartok and footok someplace in my text for a
weird reason. I want to find the closest instance of either one, and I can use a single regexp
search for the purpose, instead of searching for both and taking note of line numbers, etc.
which first matches the bartok above. Then as I add the "or foo" part of the expression, the
command re-checks from the point of search and finds that footok is indeed the closest.
From here, I can use C-r or C-s to increment through the assorted foo's and bar's in the
buffer, backward or forward respectively.
Replacing text
There are two basic types of replace commands in Emacs. The first is an unconditional
replace, based either on string or regular expression specification. There is no key-binding by
default (I must therefore conclude that it's not regarded as significant), but it can be accessed
by typing M-X replace-string (or M-x replace-regexp). This is followed by the target
string/expression and the replacement string. Replacement is unconditional and forward from
the cursor location only.
The second command, query-replace, is bound to M-% (another shifted keystroke). After
typing in the target and replacement strings at the prompts in the mini-buffer, each match in
turn is highlighted, and you're prompted for the action to take. Pressing ? displays the
complete list of possibilities here. The most common are 'y' to replace and continue, 'n' to
skip and continue, 'q' to quit, and ! to replace all the remaining matches unconditionally.
<find> search-forward
Esc C-s isearch-forward-regexp
Esc C-r isearch-backward-regexp
n/a replace-string
M-% query-replace
I introduced the save-buffer command at the beginning of this tutorial: C-x C-s. To save
the contents of a buffer as a different file name, the corresponding key-binding is C-x C-w.
A path/filename prompt appears in the mini-buffer that can be expanded to a directory listing
with a pair of Tab strokes, as with finding files.
Note that after using the write-file command to do a Save As, the buffer is associated
with the new file name. If you're accustomed to an editor retaining the original file name, this
may take a bit of getting used to.
Buffers at start-up
Working in multiple buffers is a snap. However, Emacs is natively a text application, so
there's a group of commands for switching buffers and viewing them. When Emacs starts
without a file argument, there are two initial buffers called scratch and messages. Other
buffers that you open are named after the files whose contents they contain for editing
purposes.
The scratch buffer is aptly named. Use it for temporary storage and for quickie Emacs LISP
macro development and testing. It is not saved when Emacs exits, so don't leave anything
there that you care about. Messages is a buffer that contains the "system-level" output of
commands and background activities, as shown in the excerpt below.
Loading sgml-mode...done
Auto-saving...done
Wrote /home/bilbrey/Documents/IBM/LIE/Living_In_Emacs.xml
Auto-saving...done
Windows in Emacs
Next, there are windows to consider with Emacs. To start with, you can get two views of the
current buffer by typing C-x 2, to split them horizontally (C-x 3 splits them vertically
instead). This doesn't open a new buffer, since that would be an independent copy of the
data. Instead, it's a window into the same buffer.
To switch between visible windows, the key-binding is C-x o, which is bound to the
command other-window. It cycles through the visible windows. When learning Emacs, I
most frequently used this command to swap in and out of the help window. It's also very
helpful in coding when I need to frequently swing back and forth between module and header
files.
To reduce your window count to just one, type C-x 1, which maximizes the window that
currently contains the cursor, closing other windows.
Buffers in action
To experiment a bit with buffers, first open a couple of test files. Then list all the buffers using
the command C-x C-b. Your listing should resemble this:
The MR column reflects the "Modified" and "Read-Only" status of each buffer. Buffer (name),
Size and File are self-explanatory, and we'll address modes towards the end of the tutorial.
Switch to the buffer listing window (using C-x o), then position the cursor on the line of the
new buffer you wish to open, and press Enter to select it. The buffer listing is replaced in the
window with the selected buffer. Then you can maximize that window, if you wish.
To kill the current buffer, type C-x k. The first prompt that appears in the mini-buffer
confirms the name of the buffer being killed. If the contents of the buffer are unchanged,
pressing Enter closes the buffer. Otherwise, there's a second confirm that requires a "yes" or
"no" response to discard a modified buffer.
The following table summarizes the commands found in the preceding panels.
C-x b switch-to-buffer
C-x k kill-buffer
There are two different types of modes: major and minor. Major modes are only active one at
a time, but they modify how the minor modes are interpreted. For example, in most coding,
indents only happen in the context of the previous line. Press Tab in a .txt document
(which has automatically invoked the text-mode), and a tab character is inserted and shown
as 8 columns.
On the other hand, in this XML document, Emacs invokes SGML mode by default. Here
pressing Tab only has an effect if there is leading whitespace on the previous line, in which
case the cursor is placed in the first column that matches non-whitespace above, and the
distance is filled with space characters, not a tab character.
Indent behavior is part of a minor mode, whose activity is modified by the major mode
currently invoked. Other immediate evidence of modes is the differences in syntax
highlighting and the way that text is autofilled.
For example, if I open a file named bob.txt, the buffer will open in text-mode. To start working
in c-mode, I can type this: M-x c-mode. This actually invokes cc-mode for me, according to
the messages buffer, and is shown on the status bar as C Abbrev).
To list all the major modes that Emacs recognizes automatically, type M-x
describe-variable, press Enter, and then type auto-mode-alist at the prompt in the
mini-buffer. Some of the common modes I've worked in include text, c, SGML and
occasionally LISP.
Compiling code
From a look at the list of modes, there are clearly many things you can do with Emacs. First
and foremost, though, Emacs is a programmer's editor. Among other things, you can code,
compile, debug and test software, all within the Emacs environment. I won't touch on all of
these subjects here, but let's presume that I have written a typical C-language Hello World
type of program.
Once I've typed in the program and saved the buffer to disk, I type M-x compile and the
prompt in the mini-buffer reads, Compile command: with perhaps a default after. I type in
gcc -o hello hello.c and press Enter. A compilation window opens containing the
following text:
cd /home/bilbrey/
gcc -o hello hello.c
To see if my program works, I'll run it from inside Emacs: M-! ~/hello. There in the
mini-buffer is my output: "Hello, World!"
Emacs variables can be set (once you know their names and the appropriate values) from
the command line by typing M-x set-variable and then entering the variable name
followed by the new value at the prompts. Or you can set variables by evaluating them
directly. I'd suggest using the scratch buffer for this purpose. To borrow an example from the
"LinuxDoc Emacs Beginner HOWTO" (see Resources on page 24 ), let's modify the width for
the auto-fill mode (or word wrapping):
Once that's typed in, leave the cursor at the end of the line and type C-x C-e to evaluate
the expression. The result is a 20 down in the mini-buffer. Test it by reformatting a paragraph
of text using the M-q (fill-paragraph) command.
You can also code new functions as you learn more. Experiment and find settings that you
like. You can then place these into your ~/.emacs customization file for future use.
Connectivity in Emacs
There are e-mail and Web browsing tools build right into Emacs. To start a new e-mail
message, just type C-x m. When you're done, C-x C-s saves and sends your message.
Reading mail is a little more involved. Web browsing is accomplished either by sending a
URL to an external browser or by running a textmode browser like Lynx directly inside
Emacs. Type M-x browse-url-lynx-emacs to invoke Lynx, enter the URL, and you're
off. The example running below shows e-mail composition and browsing in a single terminal
mode Emacs session.
There's even the famous Rogerian psych program, Eliza, to get you through the rough spots
at 0300 when nothing you do seems to compile. Type M-x doctor. It's far cheaper than any
of the 900 numbers, right?
Use Emacs. Live in it for a while, learn to love it a little bit. Like any complex program, it will
take time for you to fully grok it, but the effort's worthwhile: you'll have become fluent in one
of the most common UNIX programming utilities and picked up a fundamentally marketable
skill to boot!
Resources
Here are a few references to speed you on your way to Emacs mastery:
• The Emacs Beginner HOWTO at the Linux Documentation Project is a good jumping off
point.
• The GNU Emacs Manual is your ultimate reference for the editor, linked to from the GNU
Emacs homepage.
• If XEmacs is your preference, you need to go to the XEmacs home page.
• Here at IBM's developerWorks site, you can find extended resources useful in extending
your powers with Emacs, for instance with Using Regular Expressions.
• And no discussion of Emacs is complete without a reference to its arch-rival in the Linux
text-editor space. Check out vi intro - the cheat sheet method , and see what it's like for
yourself.
• The dead-tree resources of choice for Emacs are the ever-popular Learning GNU Emacs
and GNU Emacs Pocket Reference, both from O'Reilly. Pick them up at your favorite
online or corporeal bookseller.
• Emacs is licensed under the GNU GPL by the Free Software Foundation.
• For more on the history of Emacs (and many, many other UNIXish topics), consult the
Jargon File.
Your feedback
We look forward to getting your feedback on this tutorial and on future directions in providing
up-to-the minute information about the fast-moving Linux arena. You may also contact the
author directly at bilbrey@orbdesigns.com.
Colophon
This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial
generator. The open source Toot-O-Matic tool is an XSLT stylesheet and several XSLT
extension functions that convert an XML file into a number of HTML pages, a zip file, JPEG
heading graphics, and two PDF files. Our ability to generate multiple text and binary formats
from a single source file illustrates the power and flexibility of XML. (It also saves our
production team a great deal of time and effort.)