Programming a Major Mode

Once you get comfortable with Emacs LISP programming, you may find that that “little extra something” you want Emacs to do takes the form of a major mode. In previous chapters, we covered major modes for text entry, word processor input, and programming languages. Many of these modes are quite complicated to program, so we’ll provide a simple example of a major mode, from which you can learn the concepts needed to program your own. Then, in the following section, you will learn how you can customize existing major modes without changing any of the LISP code that implements them.

We’ll develop calc-mode, a major mode for a calculator whose functionality will be familiar to you if you have used the UNIX dc (desk calculator) command. It is a Reverse Polish (stack-based) calculator of the type made popular by Hewlett-Packard. After explaining some of the principal components of major modes and some interesting features of the calculator mode, we will give the mode’s complete LISP code.

Components of a Major Mode

A major mode has various components that integrate it into Emacs. Some are:

  • The symbol that is the name of the function that implements the mode

  • The name of the mode that appears in the mode line in parentheses

  • The local keymap that defines key bindings for commands in the mode

  • Variables and constants known only within the LISP code for the mode

  • The special buffer the mode may use

Let’s deal with these in order. The mode symbol is set by assigning the name ...

Get Learning GNU Emacs, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.