Writing GNU Emacs Extensions
Cambridge • Koln • Paris • Sebastopol • Tokyo
Writing GNU Emacs Extensions
by Bob Glickstein
Copyright © 1997 O'Reilly & Associates, Inc. All rights reserved.
Printed in the United States of America.
Editor: Andy Oram
Production Editors: Kismet McDonough-Chan and Ellie Fountain Maden
April 1997: First Edition.
Nutshell Handbook and the Nutshell Handbook logo are registered trademarks and The Java
Series is a trademark of O'Reilly & Associates, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and O'Reilly &
Associates, Inc. was aware of a trademark claim, the designations have been printed in caps or
While every precaution has been taken in the preparation of this book, the publisher assumes no
responsibility for errors or omissions, or for damages resulting from the use of the information
This book is printed on acid-free paper with 85% recycled content, 15% post-consumer waste.
O'Reilly & Associates is committed to using paper with the highest recycled content available
consistent with high quality.
ISBN: 1-56592-261-1 [8/97]
For Mom and Dad, without whom. . .
well, I'd just rather not think about it.
Table of Contents
1. Customizing Emacs 1
Backspace and Delete 1
Keys and Strings 4
To What Is C-h Bound? 7
To What Should C-h Be Bound? 8
Evaluating Lisp Expressions 8
2. Simple New Commands 13
Traversing Windows 13
Line-at-a-Time Scrolling 21
Other Cursor and Text Motion Commands 23
Clobbering Symbolic Links 24
Advised Buffer Switching 30
Addendum: Raw Prefix Argument 33
3. Cooperating Commands 34
The Symptom 34
A Cure 35
Generalizing the Solution 40
4. Searching and Modifying Buffers 47
Inserting the Current Time 47
5. Lisp Files 71
Creating a Lisp File 71
Loading the File 72
Compiling the File 76
Local Variables Lists 78
Addendum: Security Consideration 80
6. Lists 81
The Simple View of Lists 81
List Details 83
Recursive List Functions 85
Iterative List Functions 87
Other Useful List Functions 87
Destructive List Operations 89
Circular Lists?! 93
7. Minor Mode 95
Paragraph Filling 95
Defining a Minor Mode 97
Mode Meat 99
8. Evaluation and Error Recovery 110
Macro Functions 112
Backquote and Unquote 113
Return Value 116
Failing Gracefully 119
Point Marker 120
9. A Major Mode 122
My Quips File 122
Major Mode Skeleton 123
Changing the Definition of a Paragraph 125
Quip Commands 126
Derived Modes 131
10. A Comprehensive Example 133
New York Times Rules 133
Data Representation 134
User Interface 141
Setting Up the Mode 148
Tracking Unauthorized Changes 157
Parsing the Buffer 162
Word Finder 163
Last Word 181
A. Lisp Quick Reference 185
Data Types 186
Control Structure 190
Code Objects 193
B. Debugging and Profiling 195
The Debugger 195
The Profiler 198
C. Sharing Your Code 200
Preparing Source Files 200
D. Obtaining and Building Emacs 203
Availability of Packages 203
Unpacking, Building, and Installing Emacs 205
Before you even begin to extend Emacs, it's already the highest-function text editor there is. Not
only can it do everything you'd normally expect (formatting paragraphs, centering lines,
searching for patterns, putting a block in upper case), not only does it have advanced features
(matching braces in source code, employing color to highlight syntactic elements in your files,
giving online help on every keystroke and other commands), but it also performs a host of
functions you'd never dream of finding in a text editor. You can use Emacs to read and compose
email and to browse the World Wide Web; you can have it run FTP for you, transparently
making remote files editable as if they were local; you can ask it to remind you about upcoming
meetings, appointments, and anniversaries. As if that weren't enough, Emacs can also play you
in a game of Go-Moku (and win, more than likely); it can tell you today's date in the ancient
Mayan calendar; and it can decompose a number into its prime factors.
With all that functionality, it may seem crazy that Emacs users often spend a significant portion
of their time extending Emacs. After all, most programmers view their editors as tools for
creating other software; why spend so much energy modifying the tool itself? A carpenter
doesn't tinker with his hammer; a plumber doesn't tinker with his wrench; they use their tools to
accomplish the job at hand. So why are Emacs users different?
The answer is that the carpenter and the plumber would tinker with their tools to make them
better, if they knew how. Who knows exactly what they need better than they do? But they're not
toolsmiths. On the other hand, Emacs is a special kind of tool: it's software, which means the
tool is the same stuff as what Emacs users use it on. The user of Emacs is often a programmer,
and programming Emacs is, after all, just programming. Emacs users are in the happy position
of being their own toolsmiths.
This book teaches Emacs Lisp programming using a series of real-life examples progressing
from trivial to sophisticated. We'll start with simple configuration tweaks that you can put in
your Emacs startup file, and by the end we'll be writing "major modes" and modifying Emacs's
own "command loop." Along the way we'll learn about variables, keymaps, interactive
commands, buffers, windows, process I/O, and more. When I refer to Emacs in this book, I
specifically mean GNU Emacs. There are many editors that call themselves Emacs. Here's a bit
of the history of the name according to the authoritative On-line Hacker Jargon File, version
[Emacs] was originally written by Richard Stallman in TECO under ITS at the MIT Al lab; AI Memo
554 described it as "an advanced, self-documenting, customizable, extensible real-time display
editor." It has since been re-implemented any number of times, by various hackers, and versions exist
that run under most major operating systems. Perhaps the most widely used version, also written by
Stallman and now called "GNU EMACS" or GNUMACS, runs principally under UNIX. It includes
facilities to run compilation subprocesses and send and receive mail; many hackers spend up to 80%
of their tube time inside it. Other variants include GOSMACS, CCA EMACS, UniPress EMACS,
Montgomery EMACS, jove, epsilon, and MicroEMACS.
The examples in this book were all developed and tested in GNU Emacs version 19.34 and a
pre-release version of Emacs 20.1 under various flavors of UNIX. See Appendix D, Obtaining
and Building Emacs, for information on where to find the Emacs distribution.
I've let my own progression as an Emacs user be my guide in selecting instructive examples.
The sequence of examples in this book essentially retells the story of how my own Emacs
usage matured. For instance, from the very first moment I started using Emacs I knew I had to
do something about getting that damn BACKSPACE key not to invoke the online help! Maybe
you have that problem, too. Solving that problem is the first example we'll cover in the next
After I'd been using Emacs for a short while, I found myself wanting a number of cursor-motion
shortcuts. As I learned, they were easily written in terms of Emacs's existing motion primitives.
We'll see several examples of those in Chapter 2, Simple New Commands. Later I needed to
have some way of undoing one of my most common and maddening typing errors: pressing
CONTROL-v several times, when I meant to press CONTROL-b. Instead of moving the
cursor a few spaces to the left, I'd scroll the whole window a few times and lose my place.
Fixing this was easily done, too, as you'll see in Chapter 3, Cooperating Commands. When I
began to manage files full of clever quotations, I needed special tools to handle the specially
formatted files. We'll see some of those in Chapter 9, A Major Mode. Except for the first
handful of examples, which are simple one- and two-liners, each example has its own chapter.
Each chapter illustrates some problem needing
an Emacs Lisp solution, then presents a function or set of functions that solves the problem.
Then, just as real-life customizations tend to evolve to become more useful and more general,
we'll revise the solution once or twice before going on to the next subject.
Each example builds on the concepts of prior examples and introduces a few new ones of its
own. By the en