Making Your Own Emacs Mode

The task of writing a major mode can be separated, broadly speaking, into two components: Indentation and Fontification. In these articles, we will explore how fontification works by considering a few toy major modes that gradually increase in sophistication. First, the basics:

Let's get a very basic major mode working. Enter the following into a buffer

(define-derived-mode toy-mode fundamental-mode "== TOY MODE ==" "This is the toy mode")
(provide 'toy-mode)

and save the buffer as ~/emacs/toy/toy-mode.el. Now add the following code to your ~/.emacs file:

(add-to-list 'load-path "~/emacs/toy/")
(autoload 'toy-mode "toy-mode" "A Toy Major Mode." t)

As we modify toy-mode.el, we will be constantly reloading it. Here is a function that can be added to ~/.emacs that does this:

(defun toy-reload ()
  (interactive)
  (if (featurep 'toy-mode)
      (unload-feature 'toy-mode))
  (toy-mode))

Now enter C-x C-f toy (the C-x means type <CTRL> then x) to open a buffer called toy. On the status bar at the bottom, you should see Fundamental, which means we're in fundamental-mode, which is the default buffer mode. Now type M-x toy-mode (the M-x means type <ALT> then x), and see that Fundamental changes to "== TOY MODE ==". To see the help on toy-mode, type C-h f toy-mode and you should see the brief description that we gave above. So far, this mode is exactly the same as Fundamental mode, except for its name and description. In the next section, we shall embellish the mode with a little fontification.