BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Learning GNU Emacs
Learning GNU Emacs, Second Edition

By Debra Cameron, Bill Rosenblatt, Eric S. Raymond

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Preface
Emacs is the most powerful text editor available today. Unlike most other editors (in particular, unlike the standard UNIX editor, vi), Emacs is a complete working environment. No matter what you do, you can start Emacs in the morning, work all day and all night, and never leave it: you can use it to edit, rename, delete, and copy files; to compile programs; to do interactive work with the UNIX shell; to read and organize electronic mail; to access the Internet, and so on. Before window systems like X became popular, Emacs often served as a complete windowing system of its own. All you needed was a terminal, and you could live within Emacs forever. Emacs is also infinitely flexible; you can write your own commands, change the keys that are associated with commands, and (if you are willing to take the time) do just about anything you want.
Because it does so much, Emacs has a reputation for being extremely complicated. To date, most of the Emacs manuals that have been published have been comprehensive reference manuals rather than how-to books designed for people who are new to Emacs. That's the reason for this book: to teach you how to learn Emacs from the ground up, covering first the basics and then some of the more advanced features.
In this book, we have tried to reach as broad an audience as possible: from the administrative assistant who needs to use Emacs only to write mail messages and office memos, to the professional writer who needs to write complex documents full of formatting codes, to the advanced programmer who would like to use Emacs to format source code. No matter what you do with Emacs, you will find it's easy to learn; after one or two sessions, you'll know the basics of editing any file. After you learn the basics, you can go on to learn about more advanced topics that provide the real benefits of using Emacs. These include
  • Using multiple windows and buffers so you can work on several files at once
  • Customizing your keyboard commands
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why Read This Book?
Because it does so much, Emacs has a reputation for being extremely complicated. To date, most of the Emacs manuals that have been published have been comprehensive reference manuals rather than how-to books designed for people who are new to Emacs. That's the reason for this book: to teach you how to learn Emacs from the ground up, covering first the basics and then some of the more advanced features.
In this book, we have tried to reach as broad an audience as possible: from the administrative assistant who needs to use Emacs only to write mail messages and office memos, to the professional writer who needs to write complex documents full of formatting codes, to the advanced programmer who would like to use Emacs to format source code. No matter what you do with Emacs, you will find it's easy to learn; after one or two sessions, you'll know the basics of editing any file. After you learn the basics, you can go on to learn about more advanced topics that provide the real benefits of using Emacs. These include
  • Using multiple windows and buffers so you can work on several files at once
  • Customizing your keyboard commands
  • Tailoring Emacs to fit your work style using variables
  • Making Emacs your work environment where you can do all your everyday tasks, such as reading mail, compiling programs, and issuing shell commands
  • Creating macros to streamline repetitive tasks
  • Using Emacs to support programming in many languages (including C, C++, LISP, and FORTRAN)
  • Formatting files with various markup languages
  • Using word abbreviations to avoid spelling out long phrases or to correct common misspellings
  • Accessing Internet resources through Emacs
Of course, many of the topics may not apply to you; some topics may be appropriate for a second reading but not for the first. Toward the end of the preface, we'll sketch several different ways to approach the book, depending on your interests and experience.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Which Emacs Is Which?
Many versions of Emacs are available, offering a wide range of features. For UNIX, the most important versions of Emacs are GNU Emacs (which we cover in this book), Unipress, JOVE, MicroEmacs, Freemacs, MG, Epsilon, and CCA. Some versions, including GNU Emacs, run on personal computers under MS-DOS. Some other versions offer a limited set of features but, in return, are relatively sparing of memory and CPU cycles; the "mainline" Emacs implementations tend to be hard on computers, particularly if many users share a central computer. Some Emacs-like editors (Epoch and xemacs) are very closely integrated with the X Window System. Some versions are "free" (which may mean any of several different things), and some are rather expensive commercial products. Some other programs (like FrameMaker) are not Emacs implementations in any way but have a similar set of keyboard commands.
As you've probably gathered, Emacs isn't so much an editor as a family of editors. There are a lot of similarities; all of these editors allow you to mix text and editor commands freely; most support work in multiple windows; they all provide some kind of support for working with special file types (like C programs, TEX files, etc.); and most of them are heavily customizable, usually by programming in some dialect of LISP.
Given all this confusing diversity, which version of Emacs have we described? This book covers GNU Emacs. Since its appearance, GNU Emacs has become by far the most popular Emacs implementation in the UNIX world, and there's no reason to believe that this situation will change. It is also the most powerful and the most flexible of these extremely powerful and flexible editors. If you know GNU Emacs, you will be able to adapt to any other Emacs implementation with no trouble; it's not so easy to go in the other direction. Given these facts, our only logical choice was to focus the book on GNU Emacs.
This book, however, isn't limited to GNU Emacs users. Because of the family relations between different Emacs implementations, this book should help you get started with any Emacs editor. The basic keyboard commands change little from one editor to another—you'll find that
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
GNU Emacs and the Free Software Foundation
You don't need to know its history to use GNU Emacs, but its sources are an interesting part of recent computer history. The Free Software Foundation (FSF), which maintains and distributes GNU Emacs, has become an important part of computer culture.
A long time ago (1975), Richard Stallman at MIT wrote the first Emacs editor. According to the folklore, the original Emacs editor was a set of macros for TECO, an almost incomprehensible and now obsolete line editor. The name Emacs stands for "Editing Macros." Tradition also has it that Emacs is a play on the name of a favorite ice cream store. Much has happened since 1975. TECO has slipped into deserved obscurity, and Emacs has been rewritten as an independent program. Several commercial versions of Emacs have appeared, of which Unipress Emacs and CCA Emacs were the most important. For several years, these commercial implementations were the Emacs editors you were most likely to run across outside of the academic world.
Stallman's Emacs became prominent with the birth of the FSF and the GNU Project. GNU stands for "GNU's Not UNIX" and refers to a complete UNIX-like operating system that Stallman and his associates are building. Stallman founded the FSF to guarantee that some software would always remain free. Free does not necessarily mean cheap (you may have to pay a fee to cover the cost of distribution); it most definitely means liberated from restrictions about how it can be used.
To understand what free means, we have to look at how software is typically distributed. Most commercial software comes with a highly restrictive license. You have to pay to use the program; you probably have to pay separately for each computer that runs the program; you may have to pay more money every year to continue using the program; in some cases, you even have to pay by the minute. You are most definitely not allowed to give the program to your friends, and you will probably never (unless you are very wealthy) see the program's source code. If a commercial program is broken or doesn't have some feature you need, you are completely at the mercy of the company you bought it from, and they may well decide to ignore you.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
An Approach to Learning Emacs
Just as there are many versions of Emacs, there are many types of Emacs users. This book is designed to get you started with Emacs as quickly as possible, whether you are an experienced computer user or a novice. The first two chapters give you the basics you need to know, and the rest of the book builds on these basics. After the first two chapters, you don't have to read the rest consecutively; you can skip to the topics that interest you. Additionally, the book is designed to give you just the level of hand-holding you want; you can either read the book in detail or skim it, looking for tables of commands and examples.
Here are some reading paths you could take:
If
Read
You are an administrative user
Preface Chapter 1-Chapter 3, Chapter 16
You are a casual user
Preface, Chapter 1-Chapter 3, Chapter 16
You are a programmer
Preface, Chapter 1-Chapter 5, Chapter 10-Chapter 12,
You are a writer or production person
Preface, Chapter 1-Chapter 4, Chapter 8, Chapter 9, Chapter 16
You want to customize Emacs
Chapter 11 and possibly Chapter 13
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What We Haven't Included
GNU Emacs is a large and powerful editor; in this book, we've been able to give you only a sample of what it does. Many features have been left out, and more features are added all the time. Some topics, however, are missing:
  • Compatibility modes: GNU Emacs provides compatibility modes for the UNIX vi editor and the VAX/VMS EDT editor. We've left a discussion of these modes out. In our experience, compatibility modes tend to be poor emulations of the real thing. If you really want to use vi or EDT, do so. You're better off getting to know Emacs on its own terms, rather than pretending it is something else.
  • Many programming language modes: In this book, we discuss the editing modes for C++, LISP, and FORTRAN. There are many modes for other languages; some work better than others, and new modes are added frequently. There's no way we could discuss everything.
  • Advanced LISP programming: GNU Emacs incorporates a complete LISP interpreter. We give a very basic and brief introduction to Emacs LISP; Chapter 13 should be enough to get you started, but it really only scratches the surface. The FSF publishes a complete Emacs LISP Reference Manual, and O'Reilly & Associates has a forthcoming title on the subject, written by Bob Glickstein, one of the technical reviewers for this book.
  • Porting, debugging, and installation: This book doesn't describe the problems that can arise when porting GNU Emacs to other systems. We believe a book on this topic is needed, but it's beyond the scope of the present volume. Let us know if you'd find such a book useful, and we'll consider writing it.
  • Games and amusements: GNU Emacs includes an eclectic bunch of games and amusements, including the ability to pipe random quotations from Zippy the Pinhead into the famous "Eliza" pseudo-psychoanalyst. (Type
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conventions Used in This Book
This section covers the conventions used in this book.
Emacs commands consist of a modifier, such as CTRL (CONTROL) or ESC (ESCAPE), followed by one or two characters. Commands shown in this book abbreviate CTRL to C:
C-g
Hold down the CTRL key and press g.
To complete a command you may need to press a carriage return:
RETURN
Press the RETURN key. (This key may be labeled ENTER on your keyboard.)
Most Emacs manuals refer to the META key in addition to the CTRL key. Since most keyboards don't have a META key, this book refers to ESC instead of META:
ESC x
Press ESC, release it, then press x.
It is entirely possible that your keyboard has a META key. On Sun workstations, the keys to the immediate right and left of the space bar are META keys. On many other keyboards, the ALT keys function as a META key. If your keyboard does have a META key, it works like the CTRL key described here—that is, you hold down the META key and press the desired key, such as g. Since you can continue to hold down the META key for repeated keystroke sequences, META keys do have an advantage. ESC tends to be less convenient for repeated keystroke sequences. In general, if you have a META key on your keyboard, you will probably prefer to use it instead of ESC.
A few mouse commands (used only with the X Window System, discussed in Chapter 14 use the SHIFT key as a modifier, often in combination with the CTRL key. This is abbreviated as:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How to Contact Us
We have tested and verified the information in this book to the best of our ability, but you may find that features have changed (or even that we have made mistakes!). Please let us know about any errors you find, as well as your suggestions for future editions, by writing to:
O'Reilly & Associates, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international/local)
(707) 829-0104 (fax)
You can also send us messages electronically. To be put on the mailing list or request a catalog, send email to:
To ask technical questions or comment on the book, send email to:
We have a web site for the book, where we'll list examples, errata, and any plans for future editions. You can access this page at:
http://www.oreilly.com/catalog/gnu2/
For more information about this book and others, see the O'Reilly website:
http://www.oreilly.com
You can also send questions about Emacs and suggestions about this book to deb@ora.com. If you have access to Usenet news, you may also want to check out the gnu.emacs.help newsgroup.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Acknowledgments
Debra Cameron: There are many people who helped shape this second edition of the book. Readers sent in comments. Emacs changed, from Version 18 to Version 19. Still, no book can really encompass all that Emacs offers. Emacs is much more than an editor; it is a universe for ongoing exploration. It's also somewhat like a house that you move into and then turn into the home you want, building on additions and changing things to reflect the way you work and live.
I'd like to thank Bill Rosenblatt, who helped me get two versions of Emacs up and running, guiding me step by step through the build process. By the time I installed the third version of Emacs 19, thanks to input from Lar Kaufman and Matt Welsh, I'd discovered Linux and the FSF had streamlined the installation process to the point that it only took a few hours to FTP and compile Emacs. I would also like to thank Lenny Muellner who patiently helped me in producing review versions of the book.
I'd especially like to thank my husband Jim for his support and encouragement and our children, Meg and David, who gave up my time and attention so that "the Emacs book" could be finished.
Bill Rosenblatt: I would like to thank the following people: Professor Richard Martin (Princeton Classics Department), for planting the seed in me that eventually turned writing from a chore to a pleasure; Intermetrics, Inc., for giving me little enough to do that I could fritter away my workdays delving into GNU Emacs; Hal Stern, for getting me this gig; Sandy Wise, for his help with the X Window System chapter; Jessica Lustig, for her love and support; and most importantly, my grad-school housemates for putting up with a tied-up phone line at all hours of the day and night.
Eric Raymond: My thanks go first to the hacker community at large, all the people who created the rich tradition of Emacs LISP programming that brings Emacs customization from elegant theoretical possibility to practical tool. I learned what I know partly from reading code written by the likes of Olin Shivers, Jamie Zawinski, Kyle Jones, Barry Warsaw, Roland McGrath, Richard Stallman himself (of course), and many others. Secondly, my thanks and warmest love go as always to Catherine C. Olanich, who supported me on many levels while I worked on my bits of this book. Finally, my thanks and respect to the hip, professional and clueful people at O'Reilly. They know how to produce a good book and how to treat an author right. They care, and it shows.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 1: Emacs Basics
Some of you out there are probably dying to get your hands on the keyboard and start typing. We won't try to stop you; turn to Section 1.4and you can go ahead. But do read the beginning of this chapter later when you're ready for a break. Emacs is much easier to learn if you understand some of the basic concepts involved, and these are discussed in the following introduction.
GNU Emacs is one of the most commonly used text editors in the UNIX world today. Many users prefer GNU Emacs to vi (UNIX's standard editor) or to the editor that's built into most modern window systems. Why is it so popular? It isn't the newest tool on the market, and it's certainly not the prettiest. But it may well be the most useful tool you'll ever learn. We want to present what you need to know about Emacs in order to do useful work, in a way that lets you use it effectively. This book is a guide for Emacs users; it tries to satisfy the needs of many readers, ranging from administrators and managers who write memos and reports, to advanced programmers who edit source code in several different languages.
Our approach therefore isn't to tell you absolutely everything that Emacs does. There are many features and commands that this book doesn't describe. We don't think that's a problem; Emacs has a comprehensive online help facility that will help you figure out what these are. We have focused our attention on describing how to use Emacs to get useful work done. After covering basic editing in the first three chapters, we describe how to use Emacs as a comprehensive working environment: how to send and receive mail, how to give UNIX commands without leaving the editor, how to take advantage of special editing modes, how to use Emacs for editing special types of files (source files for troff, TEX, and various programming languages), and so on. We cover the most important commands and the most important editing modes. However, you should always keep one principle in mind: Emacs does many things well, but it isn't important for that reason. Emacs is important because of the integration between different things you like to do.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introducing Emacs!
GNU Emacs is one of the most commonly used text editors in the UNIX world today. Many users prefer GNU Emacs to vi (UNIX's standard editor) or to the editor that's built into most modern window systems. Why is it so popular? It isn't the newest tool on the market, and it's certainly not the prettiest. But it may well be the most useful tool you'll ever learn. We want to present what you need to know about Emacs in order to do useful work, in a way that lets you use it effectively. This book is a guide for Emacs users; it tries to satisfy the needs of many readers, ranging from administrators and managers who write memos and reports, to advanced programmers who edit source code in several different languages.
Our approach therefore isn't to tell you absolutely everything that Emacs does. There are many features and commands that this book doesn't describe. We don't think that's a problem; Emacs has a comprehensive online help facility that will help you figure out what these are. We have focused our attention on describing how to use Emacs to get useful work done. After covering basic editing in the first three chapters, we describe how to use Emacs as a comprehensive working environment: how to send and receive mail, how to give UNIX commands without leaving the editor, how to take advantage of special editing modes, how to use Emacs for editing special types of files (source files for troff, TEX, and various programming languages), and so on. We cover the most important commands and the most important editing modes. However, you should always keep one principle in mind: Emacs does many things well, but it isn't important for that reason. Emacs is important because of the integration between different things you like to do.
What does integration mean? A simple example will help. Assume that someone sends you a mail message describing a special command for accessing a new printer. You can use Emacs to read the mail message. Then you can try the command by starting a UNIX shell within Emacs, copying the command, and executing it directly. If it works, you can edit your
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding Files and Buffers
Editors don't edit an actual file. Rather, they put the contents of the file into a temporary buffer and edit that. The actual file on the disk doesn't change until you tell the editor to save your buffer. Remember: a buffer seems a lot like a file, but it's really only a temporary workspace that may contain a copy of a file.
Like files, Emacs buffers have names. The name of a buffer is usually the same as the name of the file that you're editing. There are a few exceptions. Some buffers don't have files associated with them—for example, *scratch* is just a temporary practice buffer, like a scratch-pad; the help facility displays help messages in a buffer named *Help*, which also isn't connected to a file. But you don't have to worry about these now. For the moment, just remember that when you start editing a file, Emacs copies the file into the buffer. As you edit the file, you are modifying the buffer, not the file itself. When you're satisfied with your changes, you can save them. Your file is only modified when you deliberately choose to save your changes. If you decide you don't like your changes, you can quit Emacs without saving the file, and no harm will be done.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Word About Modes
Emacs achieves some of its famed versatility by having various editing modes in which it behaves slightly differently. The word mode may sound technical or complicated, but what it really means is that Emacs becomes sensitive to the task at hand. When you're writing, you often want features like word wrap so that you don't have to press RETURN at the end of every line. When you're programming, the code must be formatted correctly depending on the language. For writing, there's text mode; for programming, there are modes for different languages, including C mode. Modes, then, allow Emacs to be the kind of editor you want for different tasks.
Text mode and C mode are major modes. A buffer can be in only one major mode at a time; to exit a major mode, you have to enter another one. Table 1-1 lists some of the major modes, what they do, and where they're covered in this book.
Table 1-1: Major Modes
Mode
Function
Fundamental mode
The default mode; no special behavior
Text mode
For writing text (Chapter 2)
Mail mode
For writing mail messages (Chapter 6)
RMAIL mode
For reading and organizing mail (Chapter 6)
View mode
For viewing files but not editing (Chapter 5)
Shell mode
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Starting Emacs
To start Emacs, simply type emacs followed by the name of the file you want to edit. If you use a filename that doesn't exist, Emacs creates a new file. You'll most likely see something like this:
% emacs myfile
Type emacs with a filename at the UNIX prompt to start an Emacs session.
Of course, if the file you request already exists, Emacs reads the file and displays it on the screen:
% emacs dickens
You can omit the filename, if you want. If you just type emacs, you'll see a short message describing the version of Emacs that you're running, how to start the help system, and a few other trivia. This message disappears as soon as you type the first character. Emacs then puts you in an empty buffer called *scratch*, which is an ideal place for you to experiment.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
About the Emacs Screen
When you enter Emacs, you see a large workspace at the top of the screen (usually 20 or more lines) where you do your editing. (See Figure 1-1.)
Figure 1-1: Understanding the Emacs screen
A cursor marks your position in the file. The cursor is also called point, particularly among people who are more familiar with Emacs and in the online help system; therefore, it's useful to remember this term.
You don't have to do anything special before you start; just start typing at your keyboard and, as long as you type alphanumeric characters and punctuation, Emacs inserts them into your text. The cursor indicates where Emacs inserts the new characters; it moves as you type. Unlike many editors (particularly vi), Emacs does not have separate modes for inserting text and giving commands. Try typing something right now, and you'll begin to see how easy Emacs is to use. (If you get stuck for any reason, just press C-g.)
The top line of the screen has a menu bar that lists the options Buffers, Files, Tools, Edit, Search, and Help; these options lead to other menus. We'll discuss how to use these menus later.
Just above the bottom of your screen (on the second-to-last line), Emacs prints a lot of information about what it's doing. This line is called the mode line. Near the left edge of the mode line, you may see two asterisks (**). These asterisks indicate that whatever you're editing has been modified since the last time you saved it. If you haven't made any changes, the asterisks won't be there. Next, Emacs prints Emacs: followed by the name of the buffer you are editing (myfile). In parentheses following this is the editing mode or modes you are in. (Modes are discussed earlier in this chapter.) Following this, Emacs shows where you are in the file: what line you are on (line 1 in this case) and your position relative to the rest of the file. If you're at the beginning of the file, Emacs prints the word
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Emacs Commands
You're about to start learning some Emacs commands, so let's discuss them a bit first. How do you give commands? Each command has a formal name, which (if you're fastidious) is the name of a LISP routine inside of Emacs. These names are very long; you usually wouldn't want to type the whole thing. So we need some way to abbreviate commands.
Emacs ties a command name to a short sequence of keystrokes starting with CTRL or ESC. This tying of commands to keystrokes is known as binding. In the case of the X Window System, Emacs binds some commands to mouse clicks (alone or modified by SHIFT or CTRL) and to options on menus.
The authors of Emacs tried to bind the most frequently used commands to the key sequences that are the easiest to reach. Here are the varieties of key sequences you'll encounter:
  • The most commonly used commands (such as cursor movement commands) are bound to C- n (where n is any character). To press C- n, press and hold the CTRL key and type n, then release both keys.
  • Slightly less commonly used commands are bound to ESC n, where n is any character. To press ESC n, press the ESC key, release it, then type n.
  • Other commonly used commands are bound to C-x something (C-x followed by something else—one or more characters or another control sequence). Among other types of commands, file manipulation commands, like the ones you are about to learn, are generally bound to C-x something.
  • Some specialized commands are bound to C-c something. These commands often relate to one of the more specialized modes, such as picture mode or mail mode. You won't encounter them until much later in this book.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Opening a File
You can open a file by specifying the filename when you start Emacs (as we did earlier) or by typing C-x C-f (the long command name for this is find-file). C-x C-f creates a new buffer that has the same name as the file.
Type: C-x C-f
Emacs prompts you for a filename; respond by typing the filename, followed by RETURN.
Type: newfile RETURN
Emacs starts another buffer with the new file in it.
To type C-x C-f, hold down CTRL, press x and then press f. Now release CTRL. This procedure may sound complicated, but after you try it a few times it's easy.
After you type C-x C-f, Emacs uses the minibuffer to ask you for the filename. Remember that whenever Emacs wants information from you, it automatically puts the cursor in the minibuffer. When you're done typing in the minibuffer, you need to press RETURN to enter the command. You don't need a RETURN after normal editing commands (i.e., commands that use the CTRL or ESC keys).
What if you try to read the same file twice? Instead of creating a new buffer, Emacs just moves you to the buffer the file is in.
Now is a good time to try typing if you haven't already done so. You may find yourself wanting to learn more about cursor movement and editing; that's fine. Feel free to skim the rest of this chapter and go on to Chapter 2. We recommend that you read the sections on saving files and exiting Emacs. There's also a table of commands at the end of this chapter for future reference. If you'd like to learn more about working with files as well as some shortcuts that will help you, stay with us through the rest of the chapter.
If you happen to read the wrong file (perhaps because you were in the wrong directory or because of a typo), an easy way to get the right file is by typing
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Saving Files
To save the file you are editing, type C-x C-s or select Save Buffer from the Files menu. Emacs writes the file. To let you know that the file was saved correctly, it puts the message Wrote filename in the minibuffer. If you haven't made any changes to the file, Emacs puts the message (No changes need to be saved) in the minibuffer.
If you decide to save something you've typed in the *scratch* buffer by typing C-x C-s, Emacs asks you for a filename. After you give it a filename, Emacs changes the mode line to reflect the filename, replacing *scratch* with the new name.
If you type C-x C-s and your session freezes (nothing you type is accepted), probably C-s and C-q are being used as flow control characters. In this case, C-s means "stop receiving input." Type C-q to restart the session. A command called enable-flow-control (added in Emacs 19) can quickly solve this problem. Type ESC x enable-flow-control RETURN. You can then type C-\ in place of C-s, and C-^ in place of C-q. This command solves the problem for the current session only. See "Making Emacs Work the Way You Want" at the end of Chapter 2 for a permanent solution. To understand more about flow control problems, see Chapter 11.
If you have problems with C-s (or even if you don't), you may want to use the write-file command (C-x C-w) to save your files. The write-file command is slightly different from save-buffer. The save-buffer command assumes you don't want to change the file's name. The write-file command assumes you do; it asks you to type a new filename in the minibuffer. However, if you just press RETURN instead of a new filename, write-file saves the file with its old name—just as C-x C-s would have done.
The write-file command is useful for editing files that you do not have permission to change. Use the find-file command to get the file you want into a buffer, and then use
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Leaving Emacs
To end a session in Emacs, type C-x C-c or select Exit Emacs from the Files menu. If you have made changes to files that you have not saved, Emacs asks you if you want to save the changes. If you type y, Emacs writes the file, then exits. If you type n, Emacs asks you to confirm that you really want to leave and abandon the changes you made by typing yes or no in full. If you type no, your normal Emacs session continues just as if you never typed C-x C-c. If you type yes, you exit Emacs and the changes you made during this session do not become permanent. Leaving without saving changes is often useful if you make changes you didn't intend to make.
By the way, Emacs is picky about whether you type y or yes. Sometimes it wants one, sometimes the other. If it asks for a y, you can sometimes get away with typing yes but not vice versa. If it beeps and displays, Please answer yes or no, you didn't enter the whole word and it wants you to. In versions prior to 19.29, it can also be picky about case; enter lowercase y or n or lowercase yes or no, depending on what it asks for.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Help
GNU Emacs has extensive online help, which is discussed further in Chapter 16. To enter help, type C-h or select an option from the Help menu. Pressing C-h gives you a list of options. Pressing C-h t starts a tutorial that is an excellent introduction to Emacs.
To get information about the meaning of a keystroke combination, press C-h k for describe-key. For example, if you type C-h k C-x i, Emacs displays a description of the insert-file command, which is bound to C-x i. Pressing C-h f (for describe-function) asks Emacs to describe a function (really just a command's full name, such as find-file). Essentially, C-h k and C-h f give you the same information; the difference is that with C-h k, you press a key and ask what it does, whereas with C-h f, you type a command name and ask what it does.
Assume you want to find out about what C-x i does. First, type C-h k (as shown in Figure 1-3).
Figure 1-3: Asking for help about a keyboard command
Type C-x i to get help information about insert-file (as shown in Figure 1-4).
Figure 1-4: Emacs help screen
A few things to notice: the screen is now split into two parts because you're looking at two separate buffers. Each buffer has its own mode line. The lower buffer is the *Help* buffer; it contains the information about the insert-file command that you wanted to look up. Emacs keeps the cursor in the dickens buffer because it knows there's no good reason for you to edit the *Help* buffer. To make the *Help* buffer disappear from the screen, type the command C-x 1 (to remember this, think "return to 1 buffer") or select One Window
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
Now you know the basic commands for starting and stopping Emacs and for working with files. Chapter 2 builds on these commands to give you the skills you need for editing with Emacs. Table 1-3 summarizes the commands we covered in this chapter, including options from the Files and Help menus.
Table 1-3: File-Handling Commands
Keystrokes
Command Name
Action
C-x C-f
find-file
Find file and read it in a new buffer.
FilesOpen File
C-x C-v
find-alternate-file
Read an alternate file, replacing the one read with C-x C-f.
C-x i
insert-file
Insert file at cursor position.
FilesInsert File
C-x C-s
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Editing Files
Now that you know how to enter and exit Emacs as well as the basics of working with files, it's time to learn how to move around in and edit files. Emacs offers lots of ways to move around in files. At first, you might find it confusing that there are so many ways to do the same thing. Be patient—as you learn, the confusion will lessen, and you'll begin to appreciate the variety of Emacs commands. The more ways you learn, the fewer keystrokes you'll need to get to the part of the file you want to edit.
If you want to practice commands while you're reading--which will help you learn faster—start by typing a page or two from anything you happen to have handy; the newspaper is fine. That will give you some text to work with as you learn the editing skills described in this chapter. Don't worry if you make mistakes; just keep on typing. You can correct any mistakes once you learn the basic editing skills outlined here. Learning any editor is primarily a matter of forming certain finger habits, rather than memorizing what the book says. You will learn the right finger habits only if you start typing.
When you are typing and you get to the right side of the display, you have two options. You can press RETURN to go to the next line, or you can keep typing. If you type a long line and don't press RETURN, Emacs waits until you reach the end of the display. Then it puts a backslash (\) at the end of the line and moves to the next line. For example, the following represents one long line:
Emacs uses a backslash to show you when a line is longer than the width of your display.
The backslashes aren't part of the line; they are just markers to remind you that the next line on your display really belongs to the same line.
Easier than typing RETURN after every line and better than backslashes is auto-fill mode, a minor mode that lets Emacs decide where to break lines. In auto-fill mode, Emacs waits until you get close to the end of the line, then waits until you type a space, and finally it moves the previous word (in some cases, several words) to the next line. When you are typing paragraphs of text, this behavior, sometimes referred to as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Moving the Cursor
The easiest way to move the cursor is to click the left button on your mouse (if you have one) or to press the arrow keys. To use Emacs commands to move the cursor forward one space, type C-f (f for "forward"). As you might guess, C-b moves the cursor backward. To move up, type C-p (for previous-line), and to move down, type C-n (for next-line). It's easier to memorize commands if you remember what the letters stand for. Figure 2-1 illustrates how to move up, down, left, and right using Emacs commands.
Figure 2-1: Basic cursor motion
If you're at the end of a line, C-f moves to the first character on the next line. Likewise, if you're at the beginning of a line, C-b moves to the last character of the previous line. If there's no place to go, Emacs beeps and displays the message Beginning of buffer or End of buffer. There's one important exception to this rule. If you are on the last line of a buffer, typing C-n will move to the next line, adding a new line to the buffer. In this situation (and only in this situation) C-n not only moves down a line, it creates a new line. Don't ask us why.
Now we'll learn some more advanced ways to move the cursor. One common way is moving forward and backward by word: ESC f moves forward a word; ESC b moves backward a word. You can also move to the beginning or end of the line. C-a moves you to the beginning of the line (just like a is the beginning of the alphabet). C-e moves you to the end of the line. To move backward one sentence type ESC a; to move forward one sentence, type ESC e. To move forward a whole paragraph at a time, type ESC }; to move backward a paragraph, type
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deleting Text
Before you start practicing deletion commands, you might want to know the undo command, which is discussed fully later in this chapter. Typing C-x u will undo your last edit; typing it again will undo the edit before that one, and so on.
Emacs provides many ways to delete text. The simplest way to delete text is to press the DEL key, which deletes the character immediately to the left of the cursor. See Figure 2-3 for possible locations of the DEL key on your keyboard. DEL is easiest to define by what it does: it deletes the previous character. If you're typing and you decide to erase the last character you typed, what key on your keyboard do you reach for? In Emacs, it's the DEL key.
Emacs provides a number of other deletion commands—perhaps too many for your taste, although you'll eventually find a reason to use most of them. For example, C-d (for delete-character) deletes the character under the cursor. The command for deleting the next word is ESC d (for kill-word). Once again, note how the ESC key augments the command: C-d operates on a character, and ESC d operates on a word.
Emacs has commands to delete the next or previous word, sentence, and paragraph. By their names, you can guess what they do when you're between words, sentences, or paragraphs. If you're in the middle of an entity, however, they do something a little surprising: they delete a portion of the current word, sentence or paragraph, backward or forward depending on whether the command deletes previous or next. For example, here's how ESC d acts differently depending on where the cursor is.
If the cursor is here:
ESC d makes this edit:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Marking Text to Delete, Move, or Copy
What if the text you want to delete is just a phrase? Or half a paragraph? Or several paragraphs? You could use the various delete commands in combination to delete just the part you want to, but Emacs offers an easier way: defining the area you want to delete by marking text. The marked area is called a region.
To define a region, you use a secondary pointer called a mark. Some versions of Emacs display the mark on the screen; unfortunately, in GNU Emacs, the mark is invisible.
You set the mark at one end of the region by pressing C-@ or C-SPACE, then move the cursor to the other end of the region. (The cursor is sometimes also referred to as point. There is one minor but important difference between the cursor and the point, however. The cursor is on top of a character; in Emacs, the point is actually in between the character the cursor is on and the previous character. As we said, this difference is minor, but it helps you to visualize where the cursor should be when you mark a region.) Figure 2-4 illustrates point, mark, and region.
Figure 2-4: Point, mark, and region
Let's mark a sample region. In this example, we remove the phrase "it was the worst of times." First, we find the beginning of the phrase. Then we set the mark, move forward to the end of the phrase, and delete. We use shading to indicate the region that is selected (you won't see shading on your screen unless you use X).
Move to the beginning of "it" and type C-@
Set the mark; Mark set appears in the minibuffer.
Move to the "i" in "it was the age of wisdom." Since the point is really just before the "i", this placement will be just right.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Reformatting Paragraphs
If you're in auto-fill mode, Emacs tries to make your lines as neat as possible by inserting line breaks so that each line is roughly the same length. Of course, this helps only when you're writing the first draft. As you edit, you'll make some lines longer and some shorter. Soon, you'll no longer have a neatly formatted file. Depending on the editing you've done, some lines may be short and some may be so long that they no longer fit on your display.
Emacs won't reformat your text of its own accord. If you want to restore your file to its original beauty, you need to give a fill command. The simplest way to reformat your text is to give the fill-paragraph command by typing ESC q. Emacs reformats the paragraph, then positions the cursor at the end of the paragraph.
There's one important pitfall here. In text mode, a paragraph is any text that is indented or has a blank line before and after it. If you have a file with no blank lines, Emacs thinks it is all one long paragraph. Typing ESC q by mistake takes all the text, ignoring line breaks, and makes it one long paragraph. This outcome is a particular problem if you use the