   This version is newer than the second printed edition of the GNU
Emacs Lisp Reference Manual.  It corresponds to Emacs Version 19.19.

   Published by the Free Software Foundation 675 Massachusetts Avenue
Cambridge, MA 02139 USA

   Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the Foundation.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the section entitled "GNU General Public License" is included
exactly as in the original, and provided that the entire resulting
derived work is distributed under the terms of a permission notice
identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the section entitled "GNU General Public License"
may be included in a translation approved by the Free Software
Foundation instead of in the original English.

Commands for Binding Keys
=========================

   This section describes some convenient interactive interfaces for
changing key bindings.  They work by calling `define-key'.

 - Command: global-set-key KEY DEFINITION
     This function sets the binding of KEY in the current global map to
     DEFINITION.

          (global-set-key KEY DEFINITION)
          ==
          (define-key (current-global-map) KEY DEFINITION)

 - Command: global-unset-key KEY
     This function removes the binding of KEY from the current global
     map.

     One use of this function is in preparation for defining a longer
     key which uses it implicitly as a prefix--which would not be
     allowed if KEY has a non-prefix binding.  For example:

          (global-unset-key "\C-l")
              => nil

          (global-set-key "\C-l\C-l" 'redraw-display)
              => nil

     This function is implemented simply using `define-key':

          (global-unset-key KEY)
          ==
          (define-key (current-global-map) KEY nil)

 - Command: local-set-key KEY DEFINITION
     This function sets the binding of KEY in the current local keymap
     to DEFINITION.

          (local-set-key KEY DEFINITION)
          ==
          (define-key (current-local-map) KEY DEFINITION)

 - Command: local-unset-key KEY
     This function removes the binding of KEY from the current local
     map.

          (local-unset-key KEY)
          ==
          (define-key (current-local-map) KEY nil)

Scanning Keymaps
================

   This section describes functions used to scan all the current keymaps
for the sake of printing help information.

 - Function: accessible-keymaps KEYMAP &optional PREFIX
     This function returns a list of all the keymaps that can be
     accessed (via prefix keys) from KEYMAP.  The value is an
     association list with elements of the form `(KEY . MAP)', where
     KEY is a prefix key whose definition in KEYMAP is MAP.

     The elements of the alist are ordered so that the KEY increases in
     length.  The first element is always `("" . KEYMAP)', because the
     specified keymap is accessible from itself with a prefix of no
     events.

     If PREFIX is given, it should be a prefix key sequence; then
     `accessible-keymaps' includes only the submaps whose prefixes start
     with PREFIX.  These elements look just as they do in the value of
     `(accessible-keymaps)'; the only difference is that some elements
     are omitted.

     In the example below, the returned alist indicates that the key
     ESC, which is displayed as `^[', is a prefix key whose definition
     is the sparse keymap `(keymap (83 . center-paragraph) (115 .
     foo))'.

          (accessible-keymaps (current-local-map))
          =>(("" keymap
                (27 keymap   ; Note this keymap for ESC is repeated below.
                    (83 . center-paragraph)
                    (115 . center-line))
                (9 . tab-to-tab-stop))

          ("^[" keymap
              (83 . center-paragraph)
              (115 . foo)))

     In the following example, `C-h' is a prefix key that uses a sparse
     keymap starting with `(keymap (118 . describe-variable)...)'.
     Another prefix, `C-x 4', uses a keymap which happens to be
     `ctl-x-4-map'.  The event `mode-line' is one of several dummy
     events used as prefixes for mouse actions in special parts of a
     window.

          (accessible-keymaps (current-global-map))
          => (("" keymap [set-mark-command beginning-of-line ...
                             delete-backward-char])

          ("^H" keymap (118 . describe-variable) ...
               (8 . help-for-help))

          ("^X" keymap [x-flush-mouse-queue ...
               backward-kill-sentence])

          ("^[" keymap [mark-sexp backward-sexp ...
               backward-kill-word])
              ("^X4" keymap (15 . display-buffer) ...)
          ([mode-line] keymap
               (S-mouse-2 . mouse-split-window-horizontally) ...))

     These are not all the keymaps you would see in an actual case.

 - Function: where-is-internal COMMAND &optional KEYMAP FIRSTONLY
     This function returns a list of key sequences (of any length) that
     are bound to COMMAND in KEYMAP and the global keymap.  The
     argument COMMAND can be any object; it is compared with all keymap
     entries using `eq'.  If KEYMAP is not supplied, then the global
     map alone is used.

     If FIRSTONLY is non-`nil', then the value is a single string
     representing the first key sequence found, rather than a list of
     all possible key sequences.

     This function is used by `where-is' (see Help (emacs)).

          (where-is-internal 'describe-function)
              => ("\^hf" "\^hd")

 - Command: describe-bindings PREFIX
     This function creates a listing of all defined keys, and their
     definitions.  The listing is put in a buffer named `*Help*', which
     is then displayed in a window.

     A meta character is shown as ESC followed by the corresponding
     non-meta character.  Control characters are indicated with `C-'.

     When several characters with consecutive ASCII codes have the same
     definition, they are shown together, as `FIRSTCHAR..LASTCHAR'.  In
     this instance, you need to know the ASCII codes to understand
     which characters this means.  For example, in the default global
     map, the characters `SPC .. ~' are described by a single line.
     SPC is ASCII 32, `~' is ASCII 126, and the characters between them
     include all the normal printing characters, (e.g., letters,
     digits, punctuation, etc.); all these characters are bound to
     `self-insert-command'.

     If PREFIX is non-`nil', it should be a prefix key; then only keys
     that start with PREFIX are described.

Menus
*****

Format of Menus
===============

   A menu is described using a "menu description", which is a list of
menu items, strings, and submenus.  The menu description specifies which
items are present in the menu, what function each item invokes, and
whether the item is selectable or not.  Pop-up menus are directly
described with a menu description, while menubars are described slightly
differently (see below).

   The first element of a menu must be a string, which is the name of
the menu.  This is the string that will be displayed in the parent menu
or menubar, if any.  This string is not displayed in the menu itself,
except in the case of the top level pop-up menu, where there is no
parent.  In this case, the string will be displayed at the top of the
menu if `popup-menu-titles' is non-`nil'.

   The rest of the menu consists of elements as follows:

   * A "menu item", which is a vector of three or four elements as
     follows:

        - the name of the menu item (a string);

        - the "callback" of that item;

        - whether this item is active (selectable);

        - and an optional string to append to the name.

     If the callback of a menu item is a symbol, then it must name a
     command.  It will be invoked with `call-interactively'.  If it is
     a list, then it is evaluated with `eval'.

     The third element of a menu item should either be `t', `nil', or a
     form to evaluate (with no arguments) to decide whether this item
     should be selectable.

     The fourth element of a menu item is a convenient way of adding
     the name of a command's "argument" to the menu, like `Kill Buffer
     NAME'.

   * If an element of a menu is a string, then that string will be
     presented in the menu as unselectable text.

   * If an element of a menu is a string consisting solely of hyphens,
     then that item will be presented as a solid horizontal line.

   * If an element of a menu is a list, it is treated as a submenu.
     The name of that submenu (the first element in the list) will be
     used as the name of the item representing this menu on the parent.

   The syntax, more precisely:

        form		:=  <something to pass to `eval'>
        command	:=  <a symbol or string, to pass to `call-interactively'>
        callback 	:=  command | form
        active-p	:=  <t, nil, or a form to evaluate to decide whether this
     		    item should be selectable>
        text		:=  <string, non selectable>
        name		:=  <string>
        argument	:=  <string>
        menu-item	:=  '['  name callback active-p [ argument ]  ']'
        menu		:=  '(' name [ menu-item | menu | text ]+ ')'

Format of the Menubar
=====================

   A menubar is a list of menus, menu items, and strings.  The format is
similar to that of a menu, except:

   * The first item need not be a string, and is not treated specially.

   * A string consisting solely of hyphens is not treated specially.

   * If an element of a menubar is `nil', then it is used to represent
     the division between the set of menubar items which are flush-left
     and those which are flush-right.  (Note: this isn't completely
     implemented yet.)

Menubar
=======

 - Variable: current-menubar
     This variable holds the description of the current menubar.  This
     may be buffer-local.  When the menubar is changed, the function
     `set-menubar-dirty-flag' has to be called in order for the menubar
     to be updated on the screen.

 - Function: set-menubar-dirty-flag
     This function tells Emacs that the menubar widget has to be
     updated.  Changes to the menubar will generally not be visible
     until this function is called.

   The following convenience functions are provided for setting the
menubar.  They are equivalent to doing the appropriate action to change
`current-menubar', and then calling `set-menubar-dirty-flag'.  Note
that these functions copy their argument using `copy-sequence'.

 - Function: set-menubar MENUBAR
     This function sets the default menubar to be MENUBAR (see Menu Format.).
     This is the menubar that will be visible in buffers
     that have not defined their own, buffer-local menubar.

 - Function: set-buffer-menubar MENUBAR
     This function sets the buffer-local menubar to be MENUBAR.  This
     does not change the menubar in any buffers other than the current
     one.

   Miscellaneous:

 - Variable: menubar-show-keybindings
     If true, the menubar will display keyboard equivalents.  If false,
     only the command names will be displayed.

Modifying Menus
===============

   The following functions are provided to modify the menubar of one of
its submenus.  Note that these functions modify the menu in-place,
rather than copying it and making a new menu.

   Some of these functions take a "menu path", which is a list of
strings identifying the menu to be modified.  For example, `("File")'
names the top-level "File" menu.  `("File" "Foo")' names a hypothetical
submenu of "File".

   Others take a "menu item path", which is similar to a menu path but
also specifies a particular item to be modified.  For example, `("File"
"Save")' means the menu item called "Save" under the top-level "File"
menu.  `("Menu" "Foo" "Item")' means the menu item called "Item" under
the "Foo" submenu of "Menu".

 - Function: add-menu MENU-PATH MENU-NAME MENU-ITEMS &optional BEFORE
     This function adds a menu to the menubar or one of its submenus.
     If the named menu exists already, it is changed.

     MENU-PATH identifies the menu under which the new menu should be
     inserted.  If MENU-PATH is `nil', then the menu will be added to
     the menubar itself.

     MENU-NAME is the string naming the menu to be added; MENU-ITEMS is
     a list of menu items, strings, and submenus.  These two arguments
     are the same as the first and following elements of a menu
     description (see Menu Format.).

     BEFORE, if provided, is the name of a menu before which this menu
     should be added, if this menu is not on its parent already.  If the
     menu is already present, it will not be moved.

 - Function: add-menu-item MENU-PATH ITEM-NAME FUNCTION ENABLED-P
          &optional BEFORE
     This function adds a menu item to some menu, creating the menu
     first if necessary.  If the named item exists already, it is
     changed.

     MENU-PATH identifies the menu under which the new menu item should
     be inserted. ITEM-NAME, FUNCTION, and ENABLED-P are the first,
     second, and third elements of a menu item vector (see Menu Format.).

     BEFORE, if provided, is the name of a menu item before which this
     item should be added, if this item is not on the menu already.  If
     the item is already present, it will not be moved.

 - Function: delete-menu-item MENU-ITEM-PATH
     This function removes the menu item specified by MENU-ITEM-PATH
     from the menu hierarchy.

 - Function: enable-menu-item MENU-ITEM-PATH
     This function makes the menu item specified by MENU-ITEM-PATH be
     selectable.

 - Function: disable-menu-item MENU-ITEM-PATH
     This function makes the menu item specified by MENU-ITEM-PATH be
     unselectable.

 - Function: relabel-menu-item MENU-ITEM-PATH NEW-NAME
     This function changes the string of the menu item specified by
     MENU-ITEM-PATH.  NEW-NAME is the string that the menu item will be
     printed as from now on.

   The following function can be used to search for a particular item in
a menubar specification, given a path to the item.

 - Function: find-menu-item MENUBAR MENU-ITEM-PATH &optional PARENT
     This function searches MENUBAR for the item given by
     MENU-ITEM-PATH starting from PARENT (`nil' means start at the top
     of MENUBAR).  This function returns `(ITEM . PARENT)', where
     PARENT is the immediate parent of the item found (a menu
     description), and ITEM is either a vector, list, or string,
     depending on the nature of the menu item.

     This function signals an error if the item is not found.

Menu Hooks
==========

 - Variable: menu-no-selection-hook
     This is a normal hook that will be called when a menu or dialog
     box is dismissed without a selection having been made.

 - Variable: activate-menubar-hook
     This is a function or list of functions that is called before a
     menubar menu is pulled down.  The functions in the hook should
     interrogate and modify the value of `current-menubar' as desired.

     The functions on this hook are invoked after the mouse goes down,
     but before the menu is mapped, and may be used to activate,
     deactivate, add, or delete items from the menus.

     These functions may return the symbol `t' to assert that they have
     made no changes to the menubar.  If any other value is returned,
     the menubar is recomputed.  If `t' is returned but the menubar has
     been changed, then the changes may not show up right away.
     Returning `nil' when the menubar has not changed is not so bad;
     more computation will be done, but redisplay of the menubar will
     still be performed optimally.

   The following two functions are provided for use in
`activate-menubar-hook' and are automatically added to the hook at
startup time.

 - Function: sensitize-file-and-edit-menus-hook
     This function changes the sensitivity of these `File' and `Edit'
     menu items:

    `Cut'
          Sensitive only when Emacs owns the primary X Selection (if
          `zmacs-regions' is `t', this is equivalent to saying that
          there is a region selected).

    `Copy'
          Sensitive only when Emacs owns the primary X Selection.

    `Clear'
          Sensitive only when Emacs owns the primary X Selection.

    `Paste'
          Sensitive only when there is an owner for the X Clipboard
          Selection.

    `Undo'
          Sensitive only when there is undo information.  While in the
          midst of an undo, this is changed to `Undo More'.

    `Kill Buffer'
          Has the name of the current buffer appended to it.

    `Print Buffer'
          Has the name of the current buffer appended to it.

    `Save Buffer'
          Has the name of the current buffer appended to it, and is
          sensitive only when the current buffer is modified.

    `Revert Buffer'
          Has the name of the current buffer appended to it, and is
          sensitive only when the current buffer has a file.

    `Delete Screen'
          Sensitive only when there is more than one visible screen.

 - Function: build-buffers-menu-hook
     This function changes the contents of the `Buffers' menu to
     correspond to the current set of buffers.  Only the
     most-recently-used few buffers will be listed on the menu, for
     efficiency reasons.  See Buffers Menu, for options controlling
     how the `Buffers' menu will be displayed.

Buffers Menu
============

   The following options control how the `Buffers' menu is displayed.
This is a list of all (or a subset of) the buffers currently in
existence, and is updated dynamically.

 - User Option: buffers-menu-max-size
     This user option holds the maximum number of entries which may
     appear on the `Buffers' menu.  If this is 10, then only the ten
     most-recently-selected buffers will be shown.  If this is `nil',
     then all buffers will be shown.  Setting this to a large number or
     `nil' will slow down menu responsiveness.

 - Function: format-buffers-menu-line BUFFER
     This function returns a string to represent BUFFER in the
     `Buffers' menu.  `nil' means the buffer shouldn't be listed.  You
     can redefine this.

 - User Option: complex-buffers-menu-p
     If true, the `Buffers' menu will contain several commands, as
     submenus of each buffer line.  If this is false, then there will
     be only one command: select that buffer.

 - User Option: buffers-menu-switch-to-buffer-function
     This user option holds the function to call to select a buffer
     from the `Buffers' menu.  `switch-to-buffer' is a good choice, as
     is `pop-to-buffer'.

Pop-Up Menus
============

 - Function: popup-menu MENU-DESC
     This function pops up a menu specified by MENU-DESC, which is a
     menu description (see Menu Format.).  The menu is displayed at
     the current mouse position.

 - Function: popup-menu-up-p
     This function returns `t' if a pop-up menu is up, `nil' otherwise.

 - Variable: popup-menu-titles
     If true (the default), pop-up menus will have title bars at the
     top.

Dialog Boxes
************

Dialog Box Format
=================

   A dialog box description is a list.

   * The first element of the list is a string to display in the dialog
     box.

   * The rest of the elements are descriptions of the dialog box's
     buttons.  Each one is a vector of three elements:
        - The first element is the text of the button.

        - The second element is the "callback".

        - The third element is `t' or `nil', whether this button is
          selectable.

   If the callback of a button is a symbol, then it must name a command.
It will be invoked with `call-interactively'.  If it is a list, then it
is evaluated with `eval'.

   One (and only one) of the buttons may be `nil'.  This marker means
that all following buttons should be flushright instead of flushleft.

   The syntax, more precisely:

        form		:=  <something to pass to `eval'>
        command	:=  <a symbol or string, to pass to `call-interactively'>
        callback 	:=  command | form
        active-p	:=  <t, nil, or a form to evaluate to decide whether this
     		    button should be selectable>
        name		:=  <string>
        partition	:=  'nil'
        button	:=  '['  name callback active-p ']'
        dialog	:=  '(' name [ button ]+ [ partition [ button ]+ ] ')'

Dialog Box Functions
====================

 - Function: popup-dialog-box DBOX-DESC
     This function pops up a dialog box.  DBOX-DESC describes how the
     dialog box will appear (see Dialog Box Format.).

   See Yes-or-No Queries, for functions to ask a yes/no question
using a dialog box.

Major and Minor Modes
*********************

   A "mode" is a set of definitions that customize Emacs and can be
turned on and off while you edit.  There are two varieties of modes:
"major modes", which are mutually exclusive and used for editing
particular kinds of text, and "minor modes", which provide features that
may be enabled individually.

   This chapter covers both major and minor modes, the way they are
indicated in the mode line, and how they run hooks supplied by the user.
Related topics such as keymaps and syntax tables are covered in separate
chapters.  (see Keymaps, and Syntax Tables.)

Major Modes
===========

   Major modes specialize Emacs for editing particular kinds of text.
Each buffer has only one major mode at a time.

   The least specialized major mode is called "Fundamental mode".  This
mode has no mode-specific definitions or variable settings, so each
Emacs command behaves in its default manner, and each option is in its
default state.  All other major modes redefine various keys and options.
For example, Lisp Interaction mode provides special key bindings for
LFD (`eval-print-last-sexp'), TAB (`lisp-indent-line'), and other keys.

   When you need to write several editing commands to help you perform a
specialized editing task, creating a new major mode is usually a good
idea.  In practice, writing a major mode is easy (in contrast to
writing a minor mode, which is often difficult).

   If the new mode is similar to an old one, it is often unwise to
modify the old one to serve two purposes, since it may become harder to
use and maintain.  Instead, copy and rename an existing major mode
definition and alter it for its new function.  For example, Rmail Edit
mode, which is in `emacs/lisp/rmailedit.el', is a major mode that is
very similar to Text mode except that it provides three additional
commands.  Its definition is distinct from that of Text mode, but was
derived from it.

   Rmail Edit mode is an example of a case where one piece of text is
put temporarily into a different major mode so it can be edited in a
different way (with ordinary Emacs commands rather than Rmail).  In such
cases, the temporary major mode usually has a command to switch back to
the buffer's usual mode (Rmail mode, in this case).  You might be
tempted to present the temporary redefinitions inside a recursive edit
and restore the usual ones when the user exits; but this is a bad idea
because it constrains the user's options when it is done in more than
one buffer: recursive edits must be exited most-recently-entered first.
Using alternative major modes avoids this limitation.  See Recursive Editing.

   The standard GNU Emacs Lisp library directory contains the code for
several major modes, in files including `text-mode.el', `texinfo.el',
`lisp-mode.el', `c-mode.el', and `rmail.el'.  You can look at these
libraries to see how modes are written.  Text mode is perhaps the
simplest major mode aside from Fundamental mode.  Rmail mode is a
rather complicated, full-featured mode.

Major Mode Conventions
----------------------

   The code for existing major modes follows various coding conventions,
including conventions for local keymap and syntax table initialization,
global names, and hooks.  Please keep these conventions in mind when you
create a new major mode:

   * Define a command whose name ends in `-mode', with no arguments,
     that switches to the new mode in the current buffer.  This command
     should set up the keymap, syntax table, and local variables in an
     existing buffer without changing the buffer's text.

   * Write a documentation string for this command which describes the
     special commands available in this mode.  `C-h m'
     (`describe-mode') will print this.

     The documentation string may include the special documentation
     substrings, `\[COMMAND]', `\{KEYMAP}', and `\<KEYMAP>', that
     enable the documentation to adapt automatically to the user's own
     key bindings.  See Keys in Documentation.  The `describe-mode'
     function replaces these special documentation substrings with
     their current meanings.  See Accessing Documentation.

   * The major mode command should set the variable `major-mode' to the
     major mode command symbol.  This is how `describe-mode' discovers
     which documentation to print.

   * The major mode command should set the variable `mode-name' to the
     "pretty" name of the mode, as a string.  This appears in the mode
     line.

   * Since all global names are in the same name space, all the global
     variables, constants, and functions that are part of the mode
     should have names that start with the major mode name (or with an
     abbreviation of it if the name is long).  See Style Tips.

   * The major mode should usually have its own keymap, which is used
     as the local keymap in all buffers in that mode.  The major mode
     function should call `use-local-map' to install this local map.
     See Active Keymaps, for more information.

     This keymap should be kept in a global variable named
     `MODENAME-mode-map'.  Normally the library that defines the mode
     sets this variable.  Use `defvar' to set the variable, so that it
     is not reinitialized if it already has a value.  (Such
     reinitialization could discard customizations made by the user.)

   * The mode may have its own syntax table or may share one with other
     related modes.  If it has its own syntax table, it should store
     this in a variable named `MODENAME-mode-syntax-table'.  The reasons
     for this are the same as for using a keymap variable.  See
     Syntax Tables.

   * The mode may have its own abbrev table or may share one with other
     related modes.  If it has its own abbrev table, it should store
     this in a variable named `MODENAME-mode-abbrev-table'.  See
     Abbrev Tables.

   * To give a variable a buffer-local binding, use
     `make-local-variable' in the major mode command, not
     `make-variable-buffer-local'.  The latter function would make the
     variable local to every buffer in which it is subsequently set,
     which would affect buffers that do not use this mode.  It is
     undesirable for a mode to have such global effects.  See
     Buffer-Local Variables.

   * If hooks are appropriate for the mode, the major mode command
     should run the hooks after completing all other initialization so
     the user may further customize any of the settings.  See Hooks.

   * If this mode is appropriate only for specially-prepared text, then
     the major mode command symbol should have a property named
     `mode-class' with value `special', put on as follows:

          (put 'funny-mode 'mode-class 'special)

     This tells Emacs that new buffers created while the current buffer
     has Funny mode should not inherit Funny mode.  Modes such as
     Dired, Rmail, and Buffer List use this feature.

   * If it is desirable that Emacs use the new mode by default after
     visiting files with certain recognizable names, add an element to
     `auto-mode-alist' to select the mode for those file names.  If you
     define the mode command to autoload, you should add this element
     in the same file that calls `autoload'.  Otherwise, it is
     sufficient to add the element in the file that contains the mode
     definition.  See Auto Major Mode.

   * In the documentation, you should provide a sample `autoload' form
     and an example of how to add to `auto-mode-alist', that users can
     include in their `.emacs' files.

   * The top level forms in the file defining the mode should be
     written so that they may be evaluated more than once without
     adverse consequences.  Even if you never load the file more than
     once, someone else will.

Major Mode Examples
-------------------

   Text mode is perhaps the simplest mode besides Fundamental mode.
Here are excerpts from  `text-mode.el' that illustrate many of the
conventions listed above:

     ;; Create mode-specific tables.
     (defvar text-mode-syntax-table nil
       "Syntax table used while in text mode.")

     (if text-mode-syntax-table
         ()              ; Do not change the table if it is already set up.
       (setq text-mode-syntax-table (make-syntax-table))
       (modify-syntax-entry ?\" ".   " text-mode-syntax-table)
       (modify-syntax-entry ?\\ ".   " text-mode-syntax-table)
       (modify-syntax-entry ?' "w   " text-mode-syntax-table))

     (defvar text-mode-abbrev-table nil
       "Abbrev table used while in text mode.")
     (define-abbrev-table 'text-mode-abbrev-table ())

     (defvar text-mode-map nil)   ; Create a mode-specific keymap.

     (if text-mode-map
         ()              ; Do not change the keymap if it is already set up.
       (setq text-mode-map (make-sparse-keymap))
       (define-key text-mode-map "\t" 'tab-to-tab-stop)
       (define-key text-mode-map "\es" 'center-line)
       (define-key text-mode-map "\eS" 'center-paragraph))

   Here is the complete major mode function definition for Text mode:

     (defun text-mode ()
       "Major mode for editing text intended for humans to read.
      Special commands: \\{text-mode-map}

     Turning on text-mode runs the hook `text-mode-hook'."
       (interactive)
       (kill-all-local-variables)

     (use-local-map text-mode-map)     ; This provides the local keymap.
       (setq mode-name "Text")           ; This name goes into the mode line.
       (setq major-mode 'text-mode)      ; This is how `describe-mode'
                                         ;   finds the doc string to print.
       (setq local-abbrev-table text-mode-abbrev-table)
       (set-syntax-table text-mode-syntax-table)
       (run-hooks 'text-mode-hook))      ; Finally, this permits the user to
                                         ;   customize the mode with a hook.

   The three Lisp modes (Lisp mode, Emacs Lisp mode, and Lisp
Interaction mode) have more features than Text mode and the code is
correspondingly more complicated.  Here are excerpts from
`lisp-mode.el' that illustrate how these modes are written.

     ;; Create mode-specific table variables.
     (defvar lisp-mode-syntax-table nil "")
     (defvar emacs-lisp-mode-syntax-table nil "")
     (defvar lisp-mode-abbrev-table nil "")

     (if (not emacs-lisp-mode-syntax-table) ; Do not change the table
                                            ;   if it is already set.
         (let ((i 0))
           (setq emacs-lisp-mode-syntax-table (make-syntax-table))

     ;; Set syntax of chars up to 0 to class of chars that are
           ;;   part of symbol names but not words.
           ;;   (The number 0 is `48' in the ASCII character set.)
           (while (< i ?0)
             (modify-syntax-entry i "_   " emacs-lisp-mode-syntax-table)
             (setq i (1+ i)))
           ...

     ;; Set the syntax for other characters.
           (modify-syntax-entry ?  "    " emacs-lisp-mode-syntax-table)
           (modify-syntax-entry ?\t "    " emacs-lisp-mode-syntax-table)
           ...

     (modify-syntax-entry ?\( "()  " emacs-lisp-mode-syntax-table)
           (modify-syntax-entry ?\) ")(  " emacs-lisp-mode-syntax-table)
           ...))
     ;; Create an abbrev table for lisp-mode.
     (define-abbrev-table 'lisp-mode-abbrev-table ())

   Much code is shared among the three Lisp modes.  The following
function sets various variables; it is called by each of the major Lisp
mode functions:

     (defun lisp-mode-variables (lisp-syntax)
       ;; The `lisp-syntax' argument is `nil' in Emacs Lisp mode,
       ;;   and `t' in the other two Lisp modes.
       (cond (lisp-syntax
              (if (not lisp-mode-syntax-table)
                  ;; The Emacs Lisp mode syntax table always exists, but
                  ;;   the Lisp Mode syntax table is created the first time a
                  ;;   mode that needs it is called.  This is to save space.

     (progn (setq lisp-mode-syntax-table
                            (copy-syntax-table emacs-lisp-mode-syntax-table))
                         ;; Change some entries for Lisp mode.
                         (modify-syntax-entry ?\| "\"   "
                                              lisp-mode-syntax-table)
                         (modify-syntax-entry ?\[ "_   "
                                              lisp-mode-syntax-table)
                         (modify-syntax-entry ?\] "_   "
                                              lisp-mode-syntax-table)))

     (set-syntax-table lisp-mode-syntax-table)))
       (setq local-abbrev-table lisp-mode-abbrev-table)
       ...)

   Functions such as `forward-paragraph' use the value of the
`paragraph-start' variable.  Since Lisp code is different from ordinary
text, the `paragraph-start' variable needs to be set specially to
handle Lisp.  Also, comments are indented in a special fashion in Lisp
and the Lisp modes need their own mode-specific
`comment-indent-function'.  The code to set these variables is the rest
of `lisp-mode-variables'.

     (make-local-variable 'paragraph-start)
       (setq paragraph-start (concat "^$\\|" page-delimiter))
       ...

     (make-local-variable 'comment-indent-function)
       (setq comment-indent-function 'lisp-comment-indent))

   Each of the different Lisp modes has a slightly different keymap.
For example, Lisp mode binds `C-c C-l' to `run-lisp', but the other
Lisp modes do not.  However, all Lisp modes have some commands in
common.  The following function adds these common commands to a given
keymap.

     (defun lisp-mode-commands (map)
       (define-key map "\e\C-q" 'indent-sexp)
       (define-key map "\177" 'backward-delete-char-untabify)
       (define-key map "\t" 'lisp-indent-line))

   Here is an example of using `lisp-mode-commands' to initialize a
keymap, as part of the code for Emacs Lisp mode.  First we declare a
variable with `defvar' to hold the mode-specific keymap.  When this
`defvar' executes, it sets the variable to `nil' if it was void.  Then
we set up the keymap if the variable is `nil'.

   This code avoids changing the keymap or the variable if it is already
set up.  This lets the user customize the keymap if he or she so wishes.

     (defvar emacs-lisp-mode-map () "")

     (if emacs-lisp-mode-map
         ()
       (setq emacs-lisp-mode-map (make-sparse-keymap))
       (define-key emacs-lisp-mode-map "\e\C-x" 'eval-defun)
       (lisp-mode-commands emacs-lisp-mode-map))

   Finally, here is the complete major mode function definition for
Emacs Lisp mode.

     (defun emacs-lisp-mode ()
       "Major mode for editing Lisp code to run in Emacs.
     Commands:
     Delete converts tabs to spaces as it moves back.
     Blank lines separate paragraphs.  Semicolons start comments.
     \\{emacs-lisp-mode-map}

     Entry to this mode runs the hook `emacs-lisp-mode-hook'."
       (interactive)
       (kill-all-local-variables)
       (use-local-map emacs-lisp-mode-map)    ; This provides the local keymap.
       (set-syntax-table emacs-lisp-mode-syntax-table)

     (setq major-mode 'emacs-lisp-mode)     ; This is how `describe-mode'
                                              ;   finds out what to describe.
       (setq mode-name "Emacs-Lisp")          ; This goes into the mode line.
       (lisp-mode-variables nil)              ; This define various variables.
       (run-hooks 'emacs-lisp-mode-hook))     ; This permits the user to use a
                                              ;   hook to customize the mode.

How Emacs Chooses a Major Mode
------------------------------

   Based on information in the file name or in the file itself, Emacs
automatically selects a major mode for the new buffer when a file is
visited.

 - Command: fundamental-mode
     Fundamental mode is a major mode that is not specialized for
     anything in particular.  Other major modes are defined in effect
     by comparison with this one--their definitions say what to change,
     starting from Fundamental mode.  The `fundamental-mode' function
     does *not* run any hooks, so it is not readily customizable.

 - Command: normal-mode &optional FIND-FILE
     This function establishes the proper major mode and local variable
     bindings for the current buffer.  First it calls `set-auto-mode',
     then it runs `hack-local-variables' to parse, and bind or evaluate
     as appropriate, any local variables.

     If the FIND-FILE argument to `normal-mode' is non-`nil',
     `normal-mode' assumes that the `find-file' function is calling it.
     In this case, it may process a local variables list at the end of
     the file.  The variable `enable-local-variables' controls whether
     to do so.

     If you run `normal-mode' yourself, the argument FIND-FILE is
     normally `nil'.  In this case, `normal-mode' unconditionally
     processes any local variables list.  See Local Variables in Files (emacs),
     for the syntax of the local
     variables section of a file.

     `normal-mode' uses `condition-case' around the call to the major
     mode function, so errors are caught and reported as a `File mode
     specification error',  followed by the original error message.

 - User Option: enable-local-variables
     This variable controls processing of local variables lists in files
     being visited.  A value of `t' means process the local variables
     lists unconditionally; `nil' means ignore them; anything else means
     ask the user what to do for each file.  The default value is `t'.

 - User Option: enable-local-eval
     This variable controls processing of `Eval:' in local variables
     lists in files being visited.  A value of `t' means process them
     unconditionally; `nil' means ignore them; anything else means ask
     the user what to do for each file.  The default value is `maybe'.

 - Function: set-auto-mode
     This function selects the major mode that is appropriate for the
     current buffer.  It may base its decision on the value of the `-*-'
     line, on the visited file name (using `auto-mode-alist'), or on the
     value of a local variable).  However, this function does not look
     for the `mode:' local variable near the end of a file; the
     `hack-local-variables' function does that.  See How Major Modes are Chosen (emacs).

 - User Option: default-major-mode
     This variable holds the default major mode for new buffers.  The
     standard value is `fundamental-mode'.

     If the value of `default-major-mode' is `nil', Emacs uses the
     (previously) current buffer's major mode for the major mode of a
     new buffer.  However, if the major mode symbol has a `mode-class'
     property with value `special', then it is not used for new buffers;
     Fundamental mode is used instead.  The modes that have this
     property are those such as Dired and Rmail that are useful only
     with text that has been specially prepared.

 - Variable: initial-major-mode
     The value of this variable determines the major mode of the initial
     `*scratch*' buffer.  The value should be a symbol that is a major
     mode command name.  The default value is `lisp-interaction-mode'.

 - Variable: auto-mode-alist
     This variable contains an association list of file name patterns
     (regular expressions; see Regular Expressions.) and
     corresponding major mode functions.  Usually, the file name
     patterns test for suffixes, such as `.el' and `.c', but this need
     not be the case.  Each element of the alist looks like `(REGEXP .
     mODE-FUNCTION)'.

     For example,

          (("^/tmp/fol/" . text-mode)
           ("\\.texinfo$" . texinfo-mode)
           ("\\.texi$" . texinfo-mode)

          ("\\.el$" . emacs-lisp-mode)
           ("\\.c$" . c-mode)
           ("\\.h$" . c-mode)
           ...)

     When you visit a file whose *expanded* file name (see File Name Expansion.)
     matches a REGEXP, `set-auto-mode' calls the
     corresponding MODE-FUNCTION.  This feature enables Emacs to select
     the proper major mode for most files.

     Here is an example of how to prepend several pattern pairs to
     `auto-mode-alist'.  (You might use this sort of expression in your
     `.emacs' file.)

          (setq auto-mode-alist
            (append
             ;; Filename starts with a dot.
             '(("/\\.[^/]*$" . fundamental-mode)
               ;; Filename has no dot.
               ("[^\\./]*$" . fundamental-mode)
               ("\\.C$" . c++-mode))
             auto-mode-alist))

 - Function: hack-local-variables &optional FORCE
     This function parses, and binds or evaluates as appropriate, any
     local variables for the current buffer.

     The handling of `enable-local-variables' documented for
     `normal-mode' actually takes place here.  The argument FORCE
     reflects the argument FIND-FILE given to `normal-mode'.

Getting Help about a Major Mode
-------------------------------

   The `describe-mode' function is used to provide information about
major modes.  It is normally called with `C-h m'.  The `describe-mode'
function uses the value of `major-mode', which is why every major mode
function needs to set the `major-mode' variable.

 - Command: describe-mode
     This function displays the documentation of the current major mode.

     The `describe-mode' function calls the `documentation' function
     using the value of `major-mode' as an argument.  Thus, it displays
     the documentation string of the major mode function.  (see
     Accessing Documentation.)

 - Variable: major-mode
     This variable holds the symbol for the current buffer's major
     mode.  This symbol should be the name of the function that is
     called to initialize the mode.  The `describe-mode' function uses
     the documentation string of this symbol as the documentation of
     the major mode.

Minor Modes
===========

   A "minor mode" provides features that users may enable or disable
independently of the choice of major mode.  Minor modes can be enabled
individually or in combination.  Minor modes would be better named
"Generally available, optional feature modes" except that such a name is
unwieldy.

   A minor mode is not usually a modification of single major mode.  For
example, Auto Fill mode may be used in any major mode that permits text
insertion.  To be general, a minor mode must be effectively independent
of the things major modes do.

   A minor mode is often much more difficult to implement than a major
mode.  One reason is that you should be able to deactivate a minor mode
and restore the environment of the major mode to the state it was in
before the minor mode was activated.

   Often the biggest problem in implementing a minor mode is finding a
way to insert the necessary hook into the rest of Emacs.  Minor mode
keymaps make this easier.

Conventions for Writing Minor Modes
-----------------------------------

   There are conventions for writing minor modes just as there are for
major modes.  Several of the major mode conventions apply to minor
modes as well: those regarding the name of the mode initialization
function, the names of global symbols, and the use of keymaps and other
tables.

   In addition, there are several conventions that are specific to
minor modes.

   * Make a variable whose name ends in `-mode' to represent the minor
     mode.  Its value should enable or disable the mode (`nil' to
     disable; anything else to enable.)  We call this the "mode
     variable".

     This variable is used in conjunction with the `minor-mode-alist' to
     display the minor mode name in the mode line.  It can also enable
     or disable a minor mode keymap.  Individual commands or hooks can
     also check the variable's value.

     If you want the minor mode to be enabled separately in each buffer,
     make the variable buffer-local.

   * Define a command whose name is the same as the mode variable.  Its
     job is to enable and disable the mode by setting the variable.

     The command should accept one optional argument.  If the argument
     is `nil', it should toggle the mode (turn it on if it is off, and
     off if it is on).  Otherwise, it should turn the mode on if the
     argument is a positive integer, a symbol other than `nil' or `-',
     or a list whose CAR is such an integer or symbol; it should turn
     the mode off otherwise.

     Here is an example taken from the definition of `overwrite-mode'.
     It shows the use of `overwrite-mode' as a variable which enables or
     disables the mode's behavior.

          (setq overwrite-mode
                (if (null arg) (not overwrite-mode)
                  (> (prefix-numeric-value arg) 0)))

   * Add an element to `minor-mode-alist' for each minor mode (see
     Mode Line Variables.).  This element should be a list of the
     following form:

          (MODE-VARIABLE STRING)

     Here MODE-VARIABLE is the variable that controls enablement of the
     minor mode, and STRING is a short string, starting with a space,
     to represent the mode in the mode line.  These strings must be
     short so that there is room for several of them at once.

     When you add an element to `minor-mode-alist', use `assq' to check
     for an existing element, to avoid duplication.  For example:

          (or (assq 'leif-mode minor-mode-alist)
              (setq minor-mode-alist
                    (cons '(leif-mode " Leif") minor-mode-alist)))