Go to the first, previous, next, last section, table of contents.


Writing Major Modes

Each major mode must define a command whose name ends in `-mode' (i.e. c-mode, lisp-mode, etc...). This command is called when the major mode is to be installed in the current buffer. It's first action must be to check for an already installed mode and remove it. The following code fragment does this,

(when major-mode-kill
  (funcall major-mode-kill))

All major modes must do this!

Now the major mode is free to install itself; generally this will entail setting the buffer-local values of the mode-name, major-mode, major-mode-kill and keymap-path variables. For example the lisp-mode sets these variables as follows,

(setq mode-name "Lisp"
      major-mode 'lisp-mode
      major-mode-kill 'lisp-mode-kill
      keymap-path (cons 'lisp-mode-keymap keymap-path))

Note how the major mode's own keymap (with all the mode's local key bindings installed in it) is consed onto the front of the keymap-path; this ensures that mode-local bindings take precedence over bindings in the global keymaps.

After installing itself a major mode should call a hook (generally called x-mode-hook where x is the name of the mode) to allow customisation of the mode itself.

The major-mode-kill variable holds a function to be called when the major mode is to be removed from the current buffer; basically it should remove its keymap and set all the mode-local variables to nil. For example the lisp-mode-kill function does the following to negate the effects of the code fragment above,

(setq keymap-path (delq 'lisp-mode-keymap keymap-path)
      major-mode nil
      major-mode-kill nil
      mode-name nil)

Variable: major-mode
This buffer-local variable contains the symbol whose function definition was used to install the buffer's major mode (i.e. c-mode, etc...).

When it is nil the buffer uses the `generic' mode; this is simply the bog standard editor.

Variable: major-mode-kill
This buffer-local variable contains the function which should be called to remove the buffer's currently installed major-mode.

Note that the kill-buffer function calls this (if it's non-nil) just before destroying a buffer; so if necessary, an error signalled within this function will prevent a buffer being killed.

Variable: mode-name
A buffer-local variable containing the `pretty' name of the buffer's major mode, a string which will be printed in the status line.

Many modes bind commands to keys with the prefix Ctrl-c, to save each mode creating a new root keymap the buffer-local variable ctrl-c-keymap exists.

Variable: ctrl-c-keymap
This buffer-local variable can be used by major modes to hang their keymap for the Ctrl-c prefix from. Simply set this variable to the keymap your mode wants to be installed after a Ctrl-c prefix.

The definitions for many different types of modes can be found in Jade's lisp directory.


Go to the first, previous, next, last section, table of contents.