"Fossies" - the Fresh Open Source Software Archive

Member "emacs-26.1/doc/lispref/modes.texi" (25 May 2018, 172525 Bytes) of package /linux/misc/emacs-26.1.tar.xz:


Caution: As a special service "Fossies" has tried to format the requested Texinfo source page into HTML format but that may be not always succeeeded perfectly. Alternatively you can here view or download the uninterpreted Texinfo source code. A member file download can also be achieved by clicking within a package contents listing on the according byte size field. See also the latest Fossies "Diffs" side-by-side code changes report for "modes.texi": 25.3_vs_26.1.

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1 Major and Minor Modes

A mode is a set of definitions that customize Emacs behavior in useful ways. There are two varieties of modes: minor modes, which provide features that users can turn on and off while editing; and major modes, which are used for editing or interacting with a particular kind of text. Each buffer has exactly one major mode at a time.

This chapter describes how to write both major and minor modes, how to indicate them in the mode line, and how they run hooks supplied by the user. For related topics such as keymaps and syntax tables, see @ref{Keymaps}, and @ref{Syntax Tables}.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.1 Hooks

A hook is a variable where you can store a function or functions to be called on a particular occasion by an existing program. Emacs provides hooks for the sake of customization. Most often, hooks are set up in the init file (@pxref{Init File}), but Lisp programs can set them also. @xref{Standard Hooks}, for a list of some standard hook variables.

Most of the hooks in Emacs are normal hooks. These variables contain lists of functions to be called with no arguments. By convention, whenever the hook name ends in ‘-hook’, that tells you it is normal. We try to make all hooks normal, as much as possible, so that you can use them in a uniform way.

Every major mode command is supposed to run a normal hook called the mode hook as one of the last steps of initialization. This makes it easy for a user to customize the behavior of the mode, by overriding the buffer-local variable assignments already made by the mode. Most minor mode functions also run a mode hook at the end. But hooks are used in other contexts too. For example, the hook suspend-hook runs just before Emacs suspends itself (@pxref{Suspending Emacs}).

The recommended way to add a hook function to a hook is by calling add-hook (see section Setting Hooks). The hook functions may be any of the valid kinds of functions that funcall accepts (@pxref{What Is a Function}). Most normal hook variables are initially void; add-hook knows how to deal with this. You can add hooks either globally or buffer-locally with add-hook.

If the hook variable’s name does not end with ‘-hook’, that indicates it is probably an abnormal hook. That means the hook functions are called with arguments, or their return values are used in some way. The hook’s documentation says how the functions are called. You can use add-hook to add a function to an abnormal hook, but you must write the function to follow the hook’s calling convention. By convention, abnormal hook names end in ‘-functions’.

If the variable’s name ends in ‘-function’, then its value is just a single function, not a list of functions. add-hook cannot be used to modify such a single function hook, and you have to use add-function instead (@pxref{Advising Functions}).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.1.1 Running Hooks

In this section, we document the run-hooks function, which is used to run a normal hook. We also document the functions for running various kinds of abnormal hooks.

Function: run-hooks &rest hookvars

This function takes one or more normal hook variable names as arguments, and runs each hook in turn. Each argument should be a symbol that is a normal hook variable. These arguments are processed in the order specified.

If a hook variable has a non-nil value, that value should be a list of functions. run-hooks calls all the functions, one by one, with no arguments.

The hook variable’s value can also be a single function—either a lambda expression or a symbol with a function definition—which run-hooks calls. But this usage is obsolete.

If the hook variable is buffer-local, the buffer-local variable will be used instead of the global variable. However, if the buffer-local variable contains the element t, the global hook variable will be run as well.

Function: run-hook-with-args hook &rest args

This function runs an abnormal hook by calling all the hook functions in hook, passing each one the arguments args.

Function: run-hook-with-args-until-failure hook &rest args

This function runs an abnormal hook by calling each hook function in turn, stopping if one of them fails by returning nil. Each hook function is passed the arguments args. If this function stops because one of the hook functions fails, it returns nil; otherwise it returns a non-nil value.

Function: run-hook-with-args-until-success hook &rest args

This function runs an abnormal hook by calling each hook function, stopping if one of them succeeds by returning a non-nil value. Each hook function is passed the arguments args. If this function stops because one of the hook functions returns a non-nil value, it returns that value; otherwise it returns nil.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.1.2 Setting Hooks

Here’s an example that uses a mode hook to turn on Auto Fill mode when in Lisp Interaction mode:

(add-hook 'lisp-interaction-mode-hook 'auto-fill-mode)
Function: add-hook hook function &optional append local

This function is the handy way to add function function to hook variable hook. You can use it for abnormal hooks as well as for normal hooks. function can be any Lisp function that can accept the proper number of arguments for hook. For example,

(add-hook 'text-mode-hook 'my-text-hook-function)

adds my-text-hook-function to the hook called text-mode-hook.

If function is already present in hook (comparing using equal), then add-hook does not add it a second time.

If function has a non-nil property permanent-local-hook, then kill-all-local-variables (or changing major modes) won’t delete it from the hook variable’s local value.

For a normal hook, hook functions should be designed so that the order in which they are executed does not matter. Any dependence on the order is asking for trouble. However, the order is predictable: normally, function goes at the front of the hook list, so it is executed first (barring another add-hook call). If the optional argument append is non-nil, the new hook function goes at the end of the hook list and is executed last.

add-hook can handle the cases where hook is void or its value is a single function; it sets or changes the value to a list of functions.

If local is non-nil, that says to add function to the buffer-local hook list instead of to the global hook list. This makes the hook buffer-local and adds t to the buffer-local value. The latter acts as a flag to run the hook functions in the default value as well as in the local value.

Function: remove-hook hook function &optional local

This function removes function from the hook variable hook. It compares function with elements of hook using equal, so it works for both symbols and lambda expressions.

If local is non-nil, that says to remove function from the buffer-local hook list instead of from the global hook list.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2 Major Modes

Major modes specialize Emacs for editing or interacting with particular kinds of text. Each buffer has exactly one major mode at a time. Every major mode is associated with a major mode command, whose name should end in ‘-mode’. This command takes care of switching to that mode in the current buffer, by setting various buffer-local variables such as a local keymap. See section Major Mode Conventions. Note that unlike minor modes there is no way to “turn off” a major mode, instead the buffer must be switched to a different one.

The least specialized major mode is called Fundamental mode, which has no mode-specific definitions or variable settings.

Command: fundamental-mode

This is the major mode command for Fundamental mode. Unlike other mode commands, it does not run any mode hooks (see section Major Mode Conventions), since you are not supposed to customize this mode.

The easiest way to write a major mode is to use the macro define-derived-mode, which sets up the new mode as a variant of an existing major mode. See section Defining Derived Modes. We recommend using define-derived-mode even if the new mode is not an obvious derivative of another mode, as it automatically enforces many coding conventions for you. See section Basic Major Modes, for common modes to derive from.

The standard GNU Emacs Lisp directory tree contains the code for several major modes, in files such as ‘text-mode.el’, ‘texinfo.el’, ‘lisp-mode.el’, and ‘rmail.el’. You can study these libraries to see how modes are written.

User Option: major-mode

The buffer-local value of this variable holds the symbol for the current major mode. Its default value holds the default major mode for new buffers. The standard default value is fundamental-mode.

If the default value is nil, then whenever Emacs creates a new buffer via a command such as C-x b (switch-to-buffer), the new buffer is put in the major mode of the previously current buffer. As an exception, if the major mode of the previous buffer has a mode-class symbol property with value special, the new buffer is put in Fundamental mode (see section Major Mode Conventions).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.1 Major Mode Conventions

The code for every major mode should follow various coding conventions, including conventions for local keymap and syntax table initialization, function and variable names, and hooks.

If you use the define-derived-mode macro, it will take care of many of these conventions automatically. See section Defining Derived Modes. Note also that Fundamental mode is an exception to many of these conventions, because it represents the default state of Emacs.

The following list of conventions is only partial. Each major mode should aim for consistency in general with other Emacs major modes, as this makes Emacs as a whole more coherent. It is impossible to list here all the possible points where this issue might come up; if the Emacs developers point out an area where your major mode deviates from the usual conventions, please make it compatible.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.2 How Emacs Chooses a Major Mode

When Emacs visits a file, it automatically selects a major mode for the buffer based on information in the file name or in the file itself. It also processes local variables specified in the file text.

Command: normal-mode &optional find-file

This function establishes the proper major mode and buffer-local variable bindings for the current buffer. It calls set-auto-mode (see below). As of Emacs 26.1, it no longer runs hack-local-variables, this now being done in run-mode-hooks at the initialization of major modes (see section Mode Hooks).

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 local variables in the ‘-*-’ line or at the end of the file. The variable enable-local-variables controls whether to do so. See Local Variables in Files in The GNU Emacs Manual, for the syntax of the local variables section of a file.

If you run normal-mode interactively, the argument find-file is normally nil. In this case, normal-mode unconditionally processes any file local variables.

The function calls set-auto-mode to choose and set a major mode. If this does not specify a mode, the buffer stays in the major mode determined by the default value of major-mode (see below).

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

Function: set-auto-mode &optional keep-mode-if-same

This function selects and sets the major mode that is appropriate for the current buffer. It bases its decision (in order of precedence) on the ‘-*-’ line, on any ‘mode:’ local variable near the end of a file, on the ‘#!’ line (using interpreter-mode-alist), on the text at the beginning of the buffer (using magic-mode-alist), and finally on the visited file name (using auto-mode-alist). See How Major Modes are Chosen in The GNU Emacs Manual. If enable-local-variables is nil, set-auto-mode does not check the ‘-*-’ line, or near the end of the file, for any mode tag.

There are some file types where it is not appropriate to scan the file contents for a mode specifier. For example, a tar archive may happen to contain, near the end of the file, a member file that has a local variables section specifying a mode for that particular file. This should not be applied to the containing tar file. Similarly, a tiff image file might just happen to contain a first line that seems to match the ‘-*-’ pattern. For these reasons, both these file extensions are members of the list inhibit-local-variables-regexps. Add patterns to this list to prevent Emacs searching them for local variables of any kind (not just mode specifiers).

If keep-mode-if-same is non-nil, this function does not call the mode command if the buffer is already in the proper major mode. For instance, set-visited-file-name sets this to t to avoid killing buffer local variables that the user may have set.

Function: set-buffer-major-mode buffer

This function sets the major mode of buffer to the default value of major-mode; if that is nil, it uses the current buffer’s major mode (if that is suitable). As an exception, if buffer’s name is ‘*scratch*’, it sets the mode to initial-major-mode.

The low-level primitives for creating buffers do not use this function, but medium-level commands such as switch-to-buffer and find-file-noselect use it whenever they create buffers.

User Option: 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. The default value is lisp-interaction-mode.

Variable: interpreter-mode-alist

This variable specifies major modes to use for scripts that specify a command interpreter in a ‘#!’ line. Its value is an alist with elements of the form (regexp . mode); this says to use mode mode if the file specifies an interpreter which matches \\`regexp\\'. For example, one of the default elements is ("python[0-9.]*" . python-mode).

Variable: magic-mode-alist

This variable’s value is an alist with elements of the form (regexp . function), where regexp is a regular expression and function is a function or nil. After visiting a file, set-auto-mode calls function if the text at the beginning of the buffer matches regexp and function is non-nil; if function is nil, auto-mode-alist gets to decide the mode.

Variable: magic-fallback-mode-alist

This works like magic-mode-alist, except that it is handled only if auto-mode-alist does not specify a mode for this file.

Variable: auto-mode-alist

This variable contains an association list of file name patterns (regular expressions) and corresponding major mode commands. Usually, the file name patterns test for suffixes, such as ‘.el’ and ‘.c’, but this need not be the case. An ordinary 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 (@pxref{File Name Expansion}), with version numbers and backup suffixes removed using file-name-sans-versions (@pxref{File Name Components}), matches a regexp, set-auto-mode calls the corresponding mode-function. This feature enables Emacs to select the proper major mode for most files.

If an element of auto-mode-alist has the form (regexp function t), then after calling function, Emacs searches auto-mode-alist again for a match against the portion of the file name that did not match before. This feature is useful for uncompression packages: an entry of the form ("\\.gz\\'" function t) can uncompress the file and then put the uncompressed file in the proper mode according to the name sans ‘.gz’.

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

(setq auto-mode-alist
  (append
   ;; File name (within directory) starts with a dot.
   '(("/\\.[^/]*\\'" . fundamental-mode)
     ;; File name has no dot.
     ("/[^\\./]*\\'" . fundamental-mode)
     ;; File name ends in ‘.C’.
     ("\\.C\\'" . c++-mode))
   auto-mode-alist))

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.3 Getting Help about a Major Mode

The describe-mode function provides information about major modes. It is normally bound to C-h m. It uses the value of the variable major-mode (see section Major Modes), which is why every major mode command needs to set that variable.

Command: describe-mode &optional buffer

This command displays the documentation of the current buffer’s major mode and minor modes. It uses the documentation function to retrieve the documentation strings of the major and minor mode commands (@pxref{Accessing Documentation}).

If called from Lisp with a non-nil buffer argument, this function displays the documentation for that buffer’s major and minor modes, rather than those of the current buffer.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.4 Defining Derived Modes

The recommended way to define a new major mode is to derive it from an existing one using define-derived-mode. If there is no closely related mode, you should inherit from either text-mode, special-mode, or prog-mode. See section Basic Major Modes. If none of these are suitable, you can inherit from fundamental-mode (see section Major Modes).

Macro: define-derived-mode variant parent name docstring keyword-args… body…

This macro defines variant as a major mode command, using name as the string form of the mode name. variant and parent should be unquoted symbols.

The new command variant is defined to call the function parent, then override certain aspects of that parent mode:

In addition, you can specify how to override other aspects of parent with body. The command variant evaluates the forms in body after setting up all its usual overrides, just before running the mode hooks.

If parent has a non-nil mode-class symbol property, then define-derived-mode sets the mode-class property of variant to the same value. This ensures, for example, that if parent is a special mode, then variant is also a special mode (see section Major Mode Conventions).

You can also specify nil for parent. This gives the new mode no parent. Then define-derived-mode behaves as described above, but, of course, omits all actions connected with parent.

The argument docstring specifies the documentation string for the new mode. define-derived-mode adds some general information about the mode’s hook, followed by the mode’s keymap, at the end of this documentation string. If you omit docstring, define-derived-mode generates a documentation string.

The keyword-args are pairs of keywords and values. The values, except for :after-hook’s, are evaluated. The following keywords are currently supported:

:syntax-table

You can use this to explicitly specify a syntax table for the new mode. If you specify a nil value, the new mode uses the same syntax table as parent, or the standard syntax table if parent is nil. (Note that this does not follow the convention used for non-keyword arguments that a nil value is equivalent with not specifying the argument.)

:abbrev-table

You can use this to explicitly specify an abbrev table for the new mode. If you specify a nil value, the new mode uses the same abbrev table as parent, or fundamental-mode-abbrev-table if parent is nil. (Again, a nil value is not equivalent to not specifying this keyword.)

:group

If this is specified, the value should be the customization group for this mode. (Not all major modes have one.) The command customize-mode uses this. define-derived-mode does not automatically define the specified customization group.

:after-hook

This optional keyword specifies a single Lisp form to evaluate as the final act of the mode function, after the mode hooks have been run. It should not be quoted. Since the form might be evaluated after the mode function has terminated, it should not access any element of the mode function’s local state. An :after-hook form is useful for setting up aspects of the mode which depend on the user’s settings, which in turn may have been changed in a mode hook.

Here is a hypothetical example:

(defvar hypertext-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map [down-mouse-3] 'do-hyper-link)
    map))

(define-derived-mode hypertext-mode
  text-mode "Hypertext"
  "Major mode for hypertext."
  (setq-local case-fold-search nil))

Do not write an interactive spec in the definition; define-derived-mode does that automatically.

Function: derived-mode-p &rest modes

This function returns non-nil if the current major mode is derived from any of the major modes given by the symbols modes.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.5 Basic Major Modes

Apart from Fundamental mode, there are three major modes that other major modes commonly derive from: Text mode, Prog mode, and Special mode. While Text mode is useful in its own right (e.g., for editing files ending in ‘.txt’), Prog mode and Special mode exist mainly to let other modes derive from them.

As far as possible, new major modes should be derived, either directly or indirectly, from one of these three modes. One reason is that this allows users to customize a single mode hook (e.g., prog-mode-hook) for an entire family of relevant modes (e.g., all programming language modes).

Command: text-mode

Text mode is a major mode for editing human languages. It defines the ‘"’ and ‘\’ characters as having punctuation syntax (@pxref{Syntax Class Table}), and binds M-<TAB> to ispell-complete-word (see Spelling in The GNU Emacs Manual).

An example of a major mode derived from Text mode is HTML mode. See SGML and HTML Modes in The GNU Emacs Manual.

Command: prog-mode

Prog mode is a basic major mode for buffers containing programming language source code. Most of the programming language major modes built into Emacs are derived from it.

Prog mode binds parse-sexp-ignore-comments to t (@pxref{Motion via Parsing}) and bidi-paragraph-direction to left-to-right (@pxref{Bidirectional Display}).

Command: special-mode

Special mode is a basic major mode for buffers containing text that is produced specially by Emacs, rather than directly from a file. Major modes derived from Special mode are given a mode-class property of special (see section Major Mode Conventions).

Special mode sets the buffer to read-only. Its keymap defines several common bindings, including q for quit-window and g for revert-buffer (@pxref{Reverting}).

An example of a major mode derived from Special mode is Buffer Menu mode, which is used by the ‘*Buffer List*’ buffer. See Listing Existing Buffers in The GNU Emacs Manual.

In addition, modes for buffers of tabulated data can inherit from Tabulated List mode, which is in turn derived from Special mode. See section Tabulated List mode.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.6 Mode Hooks

Every major mode command should finish by running the mode-independent normal hook change-major-mode-after-body-hook, its mode hook, and the normal hook after-change-major-mode-hook. It does this by calling run-mode-hooks. If the major mode is a derived mode, that is if it calls another major mode (the parent mode) in its body, it should do this inside delay-mode-hooks so that the parent won’t run these hooks itself. Instead, the derived mode’s call to run-mode-hooks runs the parent’s mode hook too. See section Major Mode Conventions.

Emacs versions before Emacs 22 did not have delay-mode-hooks. Versions before 24 did not have change-major-mode-after-body-hook. When user-implemented major modes do not use run-mode-hooks and have not been updated to use these newer features, they won’t entirely follow these conventions: they may run the parent’s mode hook too early, or fail to run after-change-major-mode-hook. If you encounter such a major mode, please correct it to follow these conventions.

When you define a major mode using define-derived-mode, it automatically makes sure these conventions are followed. If you define a major mode “by hand”, not using define-derived-mode, use the following functions to handle these conventions automatically.

Function: run-mode-hooks &rest hookvars

Major modes should run their mode hook using this function. It is similar to run-hooks (see section Hooks), but it also runs change-major-mode-after-body-hook, hack-local-variables (when the buffer is visiting a file) (@pxref{File Local Variables}), and after-change-major-mode-hook. The last thing it does is to evaluate any :after-hook forms declared by parent modes (see section Defining Derived Modes).

When this function is called during the execution of a delay-mode-hooks form, it does not run the hooks or hack-local-variables or evaluate the forms immediately. Instead, it arranges for the next call to run-mode-hooks to run them.

Macro: delay-mode-hooks body…

When one major mode command calls another, it should do so inside of delay-mode-hooks.

This macro executes body, but tells all run-mode-hooks calls during the execution of body to delay running their hooks. The hooks will actually run during the next call to run-mode-hooks after the end of the delay-mode-hooks construct.

Variable: change-major-mode-after-body-hook

This is a normal hook run by run-mode-hooks. It is run before the mode hooks.

Variable: after-change-major-mode-hook

This is a normal hook run by run-mode-hooks. It is run at the very end of every properly-written major mode command.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.7 Tabulated List mode

Tabulated List mode is a major mode for displaying tabulated data, i.e., data consisting of entries, each entry occupying one row of text with its contents divided into columns. Tabulated List mode provides facilities for pretty-printing rows and columns, and sorting the rows according to the values in each column. It is derived from Special mode (see section Basic Major Modes).

Tabulated List mode is intended to be used as a parent mode by a more specialized major mode. Examples include Process Menu mode (@pxref{Process Information}) and Package Menu mode (see Package Menu in The GNU Emacs Manual).

Such a derived mode should use define-derived-mode in the usual way, specifying tabulated-list-mode as the second argument (see section Defining Derived Modes). The body of the define-derived-mode form should specify the format of the tabulated data, by assigning values to the variables documented below; optionally, it can then call the function tabulated-list-init-header, which will populate a header with the names of the columns.

The derived mode should also define a listing command. This, not the mode command, is what the user calls (e.g., M-x list-processes). The listing command should create or switch to a buffer, turn on the derived mode, specify the tabulated data, and finally call tabulated-list-print to populate the buffer.

Variable: tabulated-list-format

This buffer-local variable specifies the format of the Tabulated List data. Its value should be a vector. Each element of the vector represents a data column, and should be a list (name width sort), where

Variable: tabulated-list-entries

This buffer-local variable specifies the entries displayed in the Tabulated List buffer. Its value should be either a list, or a function.

If the value is a list, each list element corresponds to one entry, and should have the form (id contents), where

Otherwise, the value should be a function which returns a list of the above form when called with no arguments.

Variable: tabulated-list-revert-hook

This normal hook is run prior to reverting a Tabulated List buffer. A derived mode can add a function to this hook to recompute tabulated-list-entries.

Variable: tabulated-list-printer

The value of this variable is the function called to insert an entry at point, including its terminating newline. The function should accept two arguments, id and contents, having the same meanings as in tabulated-list-entries. The default value is a function which inserts an entry in a straightforward way; a mode which uses Tabulated List mode in a more complex way can specify another function.

Variable: tabulated-list-sort-key

The value of this variable specifies the current sort key for the Tabulated List buffer. If it is nil, no sorting is done. Otherwise, it should have the form (name . flip), where name is a string matching one of the column names in tabulated-list-format, and flip, if non-nil, means to invert the sort order.

Function: tabulated-list-init-header

This function computes and sets header-line-format for the Tabulated List buffer (see section Window Header Lines), and assigns a keymap to the header line to allow sorting entries by clicking on column headers.

Modes derived from Tabulated List mode should call this after setting the above variables (in particular, only after setting tabulated-list-format).

Function: tabulated-list-print &optional remember-pos update

This function populates the current buffer with entries. It should be called by the listing command. It erases the buffer, sorts the entries specified by tabulated-list-entries according to tabulated-list-sort-key, then calls the function specified by tabulated-list-printer to insert each entry.

If the optional argument remember-pos is non-nil, this function looks for the id element on the current line, if any, and tries to move to that entry after all the entries are (re)inserted.

If the optional argument update is non-nil, this function will only erase or add entries that have changed since the last print. This is several times faster if most entries haven’t changed since the last time this function was called. The only difference in outcome is that tags placed via tabulated-list-put-tag will not be removed from entries that haven’t changed (normally all tags are removed).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.8 Generic Modes

Generic modes are simple major modes with basic support for comment syntax and Font Lock mode. To define a generic mode, use the macro define-generic-mode. See the file ‘generic-x.el’ for some examples of the use of define-generic-mode.

Macro: define-generic-mode mode comment-list keyword-list font-lock-list auto-mode-list function-list &optional docstring

This macro defines a generic mode command named mode (a symbol, not quoted). The optional argument docstring is the documentation for the mode command. If you do not supply it, define-generic-mode generates one by default.

The argument comment-list is a list in which each element is either a character, a string of one or two characters, or a cons cell. A character or a string is set up in the mode’s syntax table as a comment starter. If the entry is a cons cell, the CAR is set up as a comment starter and the CDR as a comment ender. (Use nil for the latter if you want comments to end at the end of the line.) Note that the syntax table mechanism has limitations about what comment starters and enders are actually possible. @xref{Syntax Tables}.

The argument keyword-list is a list of keywords to highlight with font-lock-keyword-face. Each keyword should be a string. Meanwhile, font-lock-list is a list of additional expressions to highlight. Each element of this list should have the same form as an element of font-lock-keywords. See section Search-based Fontification.

The argument auto-mode-list is a list of regular expressions to add to the variable auto-mode-alist. They are added by the execution of the define-generic-mode form, not by expanding the macro call.

Finally, function-list is a list of functions for the mode command to call for additional setup. It calls these functions just before it runs the mode hook variable mode-hook.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.9 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 the syntax table for this mode.
(defvar text-mode-syntax-table
  (let ((st (make-syntax-table)))
    (modify-syntax-entry ?\" ".   " st)
    (modify-syntax-entry ?\\ ".   " st)
    ;; Add 'p' so M-c on 'hello' leads to 'Hello', not 'hello'.
    (modify-syntax-entry ?' "w p" st)
    st)
  "Syntax table used while in `text-mode'.")
;; Create the keymap for this mode.
(defvar text-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\e\t" 'ispell-complete-word)
    map)
  "Keymap for `text-mode'.
Many other modes, such as `mail-mode', `outline-mode' and
`indented-text-mode', inherit all the commands defined in this map.")

Here is how the actual mode command is defined now:

(define-derived-mode text-mode nil "Text"
  "Major mode for editing text written for humans to read.
In this mode, paragraphs are delimited only by blank or white lines.
You can thus get the full benefit of adaptive filling
 (see the variable `adaptive-fill-mode').
\\{text-mode-map}
Turning on Text mode runs the normal hook `text-mode-hook'."
  (set (make-local-variable 'text-mode-variant) t)
  (set (make-local-variable 'require-final-newline)
       mode-require-final-newline)
  (set (make-local-variable 'indent-line-function) 'indent-relative))

(The last line is redundant nowadays, since indent-relative is the default value, and we’ll delete it in a future version.)

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.

Here is how the Lisp mode syntax and abbrev tables are defined:

;; Create mode-specific table variables.
(defvar lisp-mode-abbrev-table nil)
(define-abbrev-table 'lisp-mode-abbrev-table ())

(defvar lisp-mode-syntax-table
  (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
    (modify-syntax-entry ?\[ "_   " table)
    (modify-syntax-entry ?\] "_   " table)
    (modify-syntax-entry ?# "' 14" table)
    (modify-syntax-entry ?| "\" 23bn" table)
    table)
  "Syntax table used in `lisp-mode'.")

The three modes for Lisp share much of their code. For instance, each calls the following function to set various variables:

(defun lisp-mode-variables (&optional syntax keywords-case-insensitive)
  (when syntax
    (set-syntax-table lisp-mode-syntax-table))
  (setq local-abbrev-table lisp-mode-abbrev-table)
  …

Amongst other things, this function sets up the comment-start variable to handle Lisp comments:

  (make-local-variable 'comment-start)
  (setq comment-start ";")
  …

Each of the different Lisp modes has a slightly different keymap. For example, Lisp mode binds C-c C-z to run-lisp, but the other Lisp modes do not. However, all Lisp modes have some commands in common. The following code sets up the common commands:

(defvar lisp-mode-shared-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\e\C-q" 'indent-sexp)
    (define-key map "\177" 'backward-delete-char-untabify)
    map)
  "Keymap for commands shared by all sorts of Lisp modes.")

And here is the code to set up the keymap for Lisp mode:

(defvar lisp-mode-map
  (let ((map (make-sparse-keymap))
	(menu-map (make-sparse-keymap "Lisp")))
    (set-keymap-parent map lisp-mode-shared-map)
    (define-key map "\e\C-x" 'lisp-eval-defun)
    (define-key map "\C-c\C-z" 'run-lisp)
    …
    map)
  "Keymap for ordinary Lisp mode.
All commands in `lisp-mode-shared-map' are inherited by this map.")

Finally, here is the major mode command for Lisp mode:

(define-derived-mode lisp-mode prog-mode "Lisp"
  "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs.  Semicolons start comments.

\\{lisp-mode-map}
Note that `run-lisp' may be used either to start an inferior Lisp job
or to switch back to an existing one.
Entry to this mode calls the value of `lisp-mode-hook'
if that value is non-nil."
  (lisp-mode-variables nil t)
  (set (make-local-variable 'find-tag-default-function)
       'lisp-find-tag-default)
  (set (make-local-variable 'comment-start-skip)
       "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
  (setq imenu-case-fold-search t))

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3 Minor Modes

A minor mode provides optional features that users may enable or disable independently of the choice of major mode. Minor modes can be enabled individually or in combination.

Most minor modes implement features that are independent of the major mode, and can thus be used with most major modes. For example, Auto Fill mode works with any major mode that permits text insertion. A few minor modes, however, are specific to a particular major mode. For example, Diff Auto Refine mode is a minor mode that is intended to be used only with Diff mode.

Ideally, a minor mode should have its desired effect regardless of the other minor modes in effect. It should be possible to activate and deactivate minor modes in any order.

Variable: minor-mode-list

The value of this variable is a list of all minor mode commands.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3.1 Conventions for Writing Minor Modes

There are conventions for writing minor modes just as there are for major modes. These conventions are described below. The easiest way to follow them is to use the macro define-minor-mode. See section Defining Minor Modes.

In addition, several major mode conventions apply to minor modes as well: those regarding the names of global symbols, the use of a hook at the end of the initialization function, and the use of keymaps and other tables.

The minor mode should, if possible, support enabling and disabling via Custom (@pxref{Customization}). To do this, the mode variable should be defined with defcustom, usually with :type 'boolean. If just setting the variable is not sufficient to enable the mode, you should also specify a :set method which enables the mode by invoking the mode command. Note in the variable’s documentation string that setting the variable other than via Custom may not take effect. Also, mark the definition with an autoload cookie (@pxref{autoload cookie}), and specify a :require so that customizing the variable will load the library that defines the mode. For example:

;;;###autoload
(defcustom msb-mode nil
  "Toggle msb-mode.
Setting this variable directly does not take effect;
use either \\[customize] or the function `msb-mode'."
  :set 'custom-set-minor-mode
  :initialize 'custom-initialize-default
  :version "20.4"
  :type    'boolean
  :group   'msb
  :require 'msb)

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3.2 Keymaps and Minor Modes

Each minor mode can have its own keymap, which is active when the mode is enabled. To set up a keymap for a minor mode, add an element to the alist minor-mode-map-alist. @xref{Definition of minor-mode-map-alist}.

One use of minor mode keymaps is to modify the behavior of certain self-inserting characters so that they do something else as well as self-insert. (Another way to customize self-insert-command is through post-self-insert-hook, see @ref{Commands for Insertion}. Apart from this, the facilities for customizing self-insert-command are limited to special cases, designed for abbrevs and Auto Fill mode. Do not try substituting your own definition of self-insert-command for the standard one. The editor command loop handles this function specially.)

Minor modes may bind commands to key sequences consisting of C-c followed by a punctuation character. However, sequences consisting of C-c followed by one of {}<>:;, or a control character or digit, are reserved for major modes. Also, C-c letter is reserved for users. @xref{Key Binding Conventions}.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3.3 Defining Minor Modes

The macro define-minor-mode offers a convenient way of implementing a mode in one self-contained definition.

Macro: define-minor-mode mode doc [init-value [lighter [keymap]]] keyword-args… body…

This macro defines a new minor mode whose name is mode (a symbol). It defines a command named mode to toggle the minor mode, with doc as its documentation string.

The toggle command takes one optional (prefix) argument. If called interactively with no argument it toggles the mode on or off. A positive prefix argument enables the mode, any other prefix argument disables it. From Lisp, an argument of toggle toggles the mode, whereas an omitted or nil argument enables the mode. This makes it easy to enable the minor mode in a major mode hook, for example. If doc is nil, the macro supplies a default documentation string explaining the above.

By default, it also defines a variable named mode, which is set to t or nil by enabling or disabling the mode. The variable is initialized to init-value. Except in unusual circumstances (see below), this value must be nil.

The string lighter says what to display in the mode line when the mode is enabled; if it is nil, the mode is not displayed in the mode line.

The optional argument keymap specifies the keymap for the minor mode. If non-nil, it should be a variable name (whose value is a keymap), a keymap, or an alist of the form

(key-sequence . definition)

where each key-sequence and definition are arguments suitable for passing to define-key (@pxref{Changing Key Bindings}). If keymap is a keymap or an alist, this also defines the variable mode-map.

The above three arguments init-value, lighter, and keymap can be (partially) omitted when keyword-args are used. The keyword-args consist of keywords followed by corresponding values. A few keywords have special meanings:

:group group

Custom group name to use in all generated defcustom forms. Defaults to mode without the possible trailing ‘-mode’. Warning: don’t use this default group name unless you have written a defgroup to define that group properly. @xref{Group Definitions}.

:global global

If non-nil, this specifies that the minor mode should be global rather than buffer-local. It defaults to nil.

One of the effects of making a minor mode global is that the mode variable becomes a customization variable. Toggling it through the Customize interface turns the mode on and off, and its value can be saved for future Emacs sessions (see Saving Customizations in The GNU Emacs Manual. For the saved variable to work, you should ensure that the define-minor-mode form is evaluated each time Emacs starts; for packages that are not part of Emacs, the easiest way to do this is to specify a :require keyword.

:init-value init-value

This is equivalent to specifying init-value positionally.

:lighter lighter

This is equivalent to specifying lighter positionally.

:keymap keymap

This is equivalent to specifying keymap positionally.

:variable place

This replaces the default variable mode, used to store the state of the mode. If you specify this, the mode variable is not defined, and any init-value argument is unused. place can be a different named variable (which you must define yourself), or anything that can be used with the setf function (@pxref{Generalized Variables}). place can also be a cons (get . set), where get is an expression that returns the current state, and set is a function of one argument (a state) that sets it.

:after-hook after-hook

This defines a single Lisp form which is evaluated after the mode hooks have run. It should not be quoted.

Any other keyword arguments are passed directly to the defcustom generated for the variable mode.

The command named mode first performs the standard actions such as setting the variable named mode and then executes the body forms, if any. It then runs the mode hook variable mode-hook and finishes by evaluating any form in :after-hook.

The initial value must be nil except in cases where (1) the mode is preloaded in Emacs, or (2) it is painless for loading to enable the mode even though the user did not request it. For instance, if the mode has no effect unless something else is enabled, and will always be loaded by that time, enabling it by default is harmless. But these are unusual circumstances. Normally, the initial value must be nil.

The name easy-mmode-define-minor-mode is an alias for this macro.

Here is an example of using define-minor-mode:

(define-minor-mode hungry-mode
  "Toggle Hungry mode.
Interactively with no argument, this command toggles the mode.
A positive prefix argument enables the mode, any other prefix
argument disables it.  From Lisp, argument omitted or nil enables
the mode, `toggle' toggles the state.

When Hungry mode is enabled, the control delete key
gobbles all preceding whitespace except the last.
See the command \\[hungry-electric-delete]."
 ;; The initial value.
 nil
 ;; The indicator for the mode line.
 " Hungry"
 ;; The minor mode bindings.
 '(([C-backspace] . hungry-electric-delete))
 :group 'hunger)

This defines a minor mode named “Hungry mode”, a command named hungry-mode to toggle it, a variable named hungry-mode which indicates whether the mode is enabled, and a variable named hungry-mode-map which holds the keymap that is active when the mode is enabled. It initializes the keymap with a key binding for C-<DEL>. It puts the variable hungry-mode into custom group hunger. There are no body forms—many minor modes don’t need any.

Here’s an equivalent way to write it:

(define-minor-mode hungry-mode
  "Toggle Hungry mode.
...rest of documentation as before..."
 ;; The initial value.
 :init-value nil
 ;; The indicator for the mode line.
 :lighter " Hungry"
 ;; The minor mode bindings.
 :keymap
 '(([C-backspace] . hungry-electric-delete)
   ([C-M-backspace]
    . (lambda ()
        (interactive)
        (hungry-electric-delete t))))
 :group 'hunger)
Macro: define-globalized-minor-mode global-mode mode turn-on keyword-args…

This defines a global toggle named global-mode whose meaning is to enable or disable the buffer-local minor mode mode in all buffers. To turn on the minor mode in a buffer, it uses the function turn-on; to turn off the minor mode, it calls mode with -1 as argument.

Globally enabling the mode also affects buffers subsequently created by visiting files, and buffers that use a major mode other than Fundamental mode; but it does not detect the creation of a new buffer in Fundamental mode.

This defines the customization option global-mode (@pxref{Customization}), which can be toggled in the Customize interface to turn the minor mode on and off. As with define-minor-mode, you should ensure that the define-globalized-minor-mode form is evaluated each time Emacs starts, for example by providing a :require keyword.

Use :group group in keyword-args to specify the custom group for the mode variable of the global minor mode.

Generally speaking, when you define a globalized minor mode, you should also define a non-globalized version, so that people can use (or disable) it in individual buffers. This also allows them to disable a globally enabled minor mode in a specific major mode, by using that mode’s hook.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4 Mode Line Format

Each Emacs window (aside from minibuffer windows) typically has a mode line at the bottom, which displays status information about the buffer displayed in the window. The mode line contains information about the buffer, such as its name, associated file, depth of recursive editing, and major and minor modes. A window can also have a header line, which is much like the mode line but appears at the top of the window.

This section describes how to control the contents of the mode line and header line. We include it in this chapter because much of the information displayed in the mode line relates to the enabled major and minor modes.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.1 Mode Line Basics

The contents of each mode line are specified by the buffer-local variable mode-line-format (see section The Top Level of Mode Line Control). This variable holds a mode line construct: a template that controls what is displayed on the buffer’s mode line. The value of header-line-format specifies the buffer’s header line in the same way. All windows for the same buffer use the same mode-line-format and header-line-format unless a mode-line-format or header-line-format parameter has been specified for that window (@pxref{Window Parameters}).

For efficiency, Emacs does not continuously recompute each window’s mode line and header line. It does so when circumstances appear to call for it—for instance, if you change the window configuration, switch buffers, narrow or widen the buffer, scroll, or modify the buffer. If you alter any of the variables referenced by mode-line-format or header-line-format (see section Variables Used in the Mode Line), or any other data structures that affect how text is displayed (@pxref{Display}), you should use the function force-mode-line-update to update the display.

Function: force-mode-line-update &optional all

This function forces Emacs to update the current buffer’s mode line and header line, based on the latest values of all relevant variables, during its next redisplay cycle. If the optional argument all is non-nil, it forces an update for all mode lines and header lines.

This function also forces an update of the menu bar and frame title.

The selected window’s mode line is usually displayed in a different color using the face mode-line. Other windows’ mode lines appear in the face mode-line-inactive instead. @xref{Faces}.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.2 The Data Structure of the Mode Line

The mode line contents are controlled by a data structure called a mode line construct, made up of lists, strings, symbols, and numbers kept in buffer-local variables. Each data type has a specific meaning for the mode line appearance, as described below. The same data structure is used for constructing frame titles (@pxref{Frame Titles}) and header lines (see section Window Header Lines).

A mode line construct may be as simple as a fixed string of text, but it usually specifies how to combine fixed strings with variables’ values to construct the text. Many of these variables are themselves defined to have mode line constructs as their values.

Here are the meanings of various data types as mode line constructs:

string

A string as a mode line construct appears verbatim except for %-constructs in it. These stand for substitution of other data; see %-Constructs in the Mode Line.

If parts of the string have face properties, they control display of the text just as they would text in the buffer. Any characters which have no face properties are displayed, by default, in the face mode-line or mode-line-inactive (see Standard Faces in The GNU Emacs Manual). The help-echo and keymap properties in string have special meanings. See section Properties in the Mode Line.

symbol

A symbol as a mode line construct stands for its value. The value of symbol is used as a mode line construct, in place of symbol. However, the symbols t and nil are ignored, as is any symbol whose value is void.

There is one exception: if the value of symbol is a string, it is displayed verbatim: the %-constructs are not recognized.

Unless symbol is marked as risky (i.e., it has a non-nil risky-local-variable property), all text properties specified in symbol’s value are ignored. This includes the text properties of strings in symbol’s value, as well as all :eval and :propertize forms in it. (The reason for this is security: non-risky variables could be set automatically from file variables without prompting the user.)

(string rest…)
(list rest…)

A list whose first element is a string or list means to process all the elements recursively and concatenate the results. This is the most common form of mode line construct.

(:eval form)

A list whose first element is the symbol :eval says to evaluate form, and use the result as a string to display. Make sure this evaluation cannot load any files, as doing so could cause infinite recursion.

(:propertize elt props…)

A list whose first element is the symbol :propertize says to process the mode line construct elt recursively, then add the text properties specified by props to the result. The argument props should consist of zero or more pairs text-property value.

(symbol then else)

A list whose first element is a symbol that is not a keyword specifies a conditional. Its meaning depends on the value of symbol. If symbol has a non-nil value, the second element, then, is processed recursively as a mode line construct. Otherwise, the third element, else, is processed recursively. You may omit else; then the mode line construct displays nothing if the value of symbol is nil or void.

(width rest…)

A list whose first element is an integer specifies truncation or padding of the results of rest. The remaining elements rest are processed recursively as mode line constructs and concatenated together. When width is positive, the result is space filled on the right if its width is less than width. When width is negative, the result is truncated on the right to -width columns if its width exceeds -width.

For example, the usual way to show what percentage of a buffer is above the top of the window is to use a list like this: (-3 "%p").


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.3 The Top Level of Mode Line Control

The variable in overall control of the mode line is mode-line-format.

User Option: mode-line-format

The value of this variable is a mode line construct that controls the contents of the mode-line. It is always buffer-local in all buffers.

If you set this variable to nil in a buffer, that buffer does not have a mode line. (A window that is just one line tall also does not display a mode line.)

The default value of mode-line-format is designed to use the values of other variables such as mode-line-position and mode-line-modes (which in turn incorporates the values of the variables mode-name and minor-mode-alist). Very few modes need to alter mode-line-format itself. For most purposes, it is sufficient to alter some of the variables that mode-line-format either directly or indirectly refers to.

If you do alter mode-line-format itself, the new value should use the same variables that appear in the default value (see section Variables Used in the Mode Line), rather than duplicating their contents or displaying the information in another fashion. This way, customizations made by the user or by Lisp programs (such as display-time and major modes) via changes to those variables remain effective.

Here is a hypothetical example of a mode-line-format that might be useful for Shell mode (in reality, Shell mode does not set mode-line-format):

(setq mode-line-format
  (list "-"
   'mode-line-mule-info
   'mode-line-modified
   'mode-line-frame-identification
   "%b--"
   ;; Note that this is evaluated while making the list.
   ;; It makes a mode line construct which is just a string.
   (getenv "HOST")
   ":"
   'default-directory
   "   "
   'global-mode-string
   "   %[("
   '(:eval (mode-line-mode-name))
   'mode-line-process
   'minor-mode-alist
   "%n"
   ")%]--"
   '(which-func-mode ("" which-func-format "--"))
   '(line-number-mode "L%l--")
   '(column-number-mode "C%c--")
   '(-3 "%p")))

(The variables line-number-mode, column-number-mode and which-func-mode enable particular minor modes; as usual, these variable names are also the minor mode command names.)


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.4 Variables Used in the Mode Line

This section describes variables incorporated by the standard value of mode-line-format into the text of the mode line. There is nothing inherently special about these variables; any other variables could have the same effects on the mode line if the value of mode-line-format is changed to use them. However, various parts of Emacs set these variables on the understanding that they will control parts of the mode line; therefore, practically speaking, it is essential for the mode line to use them. Also see Optional Mode Line in The GNU Emacs Manual.

Variable: mode-line-mule-info

This variable holds the value of the mode line construct that displays information about the language environment, buffer coding system, and current input method. @xref{Non-ASCII Characters}.

Variable: mode-line-modified

This variable holds the value of the mode line construct that displays whether the current buffer is modified. Its default value displays ‘**’ if the buffer is modified, ‘--’ if the buffer is not modified, ‘%%’ if the buffer is read only, and ‘%*’ if the buffer is read only and modified.

Changing this variable does not force an update of the mode line.

Variable: mode-line-frame-identification

This variable identifies the current frame. Its default value displays " " if you are using a window system which can show multiple frames, or "-%F " on an ordinary terminal which shows only one frame at a time.

Variable: mode-line-buffer-identification

This variable identifies the buffer being displayed in the window. Its default value displays the buffer name, padded with spaces to at least 12 columns.

Variable: mode-line-position

This variable indicates the position in the buffer. Its default value displays the buffer percentage and, optionally, the buffer size, the line number and the column number.

User Option: mode-line-percent-position

This option is used in mode-line-position. Its value specifies both the buffer percentage to display (one of nil, "%o", "%p", "%P" or "%q", see section %-Constructs in the Mode Line) and a width to space-fill or truncate to. You are recommended to set this option with the customize-variable facility.

Variable: vc-mode

The variable vc-mode, buffer-local in each buffer, records whether the buffer’s visited file is maintained with version control, and, if so, which kind. Its value is a string that appears in the mode line, or nil for no version control.

Variable: mode-line-modes

This variable displays the buffer’s major and minor modes. Its default value also displays the recursive editing level, information on the process status, and whether narrowing is in effect.

Variable: mode-line-remote

This variable is used to show whether default-directory for the current buffer is remote.

Variable: mode-line-client

This variable is used to identify emacsclient frames.

The following three variables are used in mode-line-modes:

Variable: mode-name

This buffer-local variable holds the “pretty” name of the current buffer’s major mode. Each major mode should set this variable so that the mode name will appear in the mode line. The value does not have to be a string, but can use any of the data types valid in a mode-line construct (see section The Data Structure of the Mode Line). To compute the string that will identify the mode name in the mode line, use format-mode-line (see section Emulating Mode Line Formatting).

Variable: mode-line-process

This buffer-local variable contains the mode line information on process status in modes used for communicating with subprocesses. It is displayed immediately following the major mode name, with no intervening space. For example, its value in the ‘*shell*’ buffer is (":%s"), which allows the shell to display its status along with the major mode as: ‘(Shell:run)’. Normally this variable is nil.

Variable: mode-line-front-space

This variable is displayed at the front of the mode line. By default, this construct is displayed right at the beginning of the mode line, except that if there is a memory-full message, it is displayed first.

Variable: mode-line-end-spaces

This variable is displayed at the end of the mode line.

Variable: mode-line-misc-info

Mode line construct for miscellaneous information. By default, this shows the information specified by global-mode-string.

Variable: minor-mode-alist

This variable holds an association list whose elements specify how the mode line should indicate that a minor mode is active. Each element of the minor-mode-alist should be a two-element list:

(minor-mode-variable mode-line-string)

More generally, mode-line-string can be any mode line construct. It appears in the mode line when the value of minor-mode-variable is non-nil, and not otherwise. These strings should begin with spaces so that they don’t run together. Conventionally, the minor-mode-variable for a specific mode is set to a non-nil value when that minor mode is activated.

minor-mode-alist itself is not buffer-local. Each variable mentioned in the alist should be buffer-local if its minor mode can be enabled separately in each buffer.

Variable: global-mode-string

This variable holds a mode line construct that, by default, appears in the mode line just after the which-func-mode minor mode if set, else after mode-line-modes. The command display-time sets global-mode-string to refer to the variable display-time-string, which holds a string containing the time and load information.

The ‘%M’ construct substitutes the value of global-mode-string, but that is obsolete, since the variable is included in the mode line from mode-line-format.

Here is a simplified version of the default value of mode-line-format. The real default value also specifies addition of text properties.

("-"
 mode-line-mule-info
 mode-line-modified
 mode-line-frame-identification
 mode-line-buffer-identification
 "   "
 mode-line-position
 (vc-mode vc-mode)
 "   "
 mode-line-modes
 (which-func-mode ("" which-func-format "--"))
 (global-mode-string ("--" global-mode-string))
 "-%-")

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.5 %-Constructs in the Mode Line

Strings used as mode line constructs can use certain %-constructs to substitute various kinds of data. The following is a list of the defined %-constructs, and what they mean.

In any construct except ‘%%’, you can add a decimal integer after the ‘%’ to specify a minimum field width. If the width is less, the field is padded to that width. Purely numeric constructs (‘c’, ‘i’, ‘I’, and ‘l’) are padded by inserting spaces to the left, and others are padded by inserting spaces to the right.

%b

The current buffer name, obtained with the buffer-name function. @xref{Buffer Names}.

%c

The current column number of point, counting from zero starting at the left margin of the window.

%C

The current column number of point, counting from one starting at the left margin of the window.

%e

When Emacs is nearly out of memory for Lisp objects, a brief message saying so. Otherwise, this is empty.

%f

The visited file name, obtained with the buffer-file-name function. @xref{Buffer File Name}.

%F

The title (only on a window system) or the name of the selected frame. @xref{Basic Parameters}.

%i

The size of the accessible part of the current buffer; basically (- (point-max) (point-min)).

%I

Like ‘%i’, but the size is printed in a more readable way by using ‘k’ for 10^3, ‘M’ for 10^6, ‘G’ for 10^9, etc., to abbreviate.

%l

The current line number of point, counting within the accessible portion of the buffer.

%n

Narrow’ when narrowing is in effect; nothing otherwise (see narrow-to-region in @ref{Narrowing}).

%o

The degree of travel of the window through (the visible portion of) the buffer, i.e. the size of the text above the top of the window expressed as a percentage of all the text outside the window, or ‘Top’, ‘Bottom’ or ‘All’.

%p

The percentage of the buffer text above the top of window, or ‘Top’, ‘Bottom’ or ‘All’. Note that the default mode line construct truncates this to three characters.

%P

The percentage of the buffer text that is above the bottom of the window (which includes the text visible in the window, as well as the text above the top), plus ‘Top’ if the top of the buffer is visible on screen; or ‘Bottom’ or ‘All’.

%q

The percentages of text above both the top and the bottom of the window, separated by ‘-’, or ‘All’.

%s

The status of the subprocess belonging to the current buffer, obtained with process-status. @xref{Process Information}.

%z

The mnemonics of keyboard, terminal, and buffer coding systems.

%Z

Like ‘%z’, but including the end-of-line format.

%*

%’ if the buffer is read only (see buffer-read-only);
*’ if the buffer is modified (see buffer-modified-p);
-’ otherwise. @xref{Buffer Modification}.

%+

*’ if the buffer is modified (see buffer-modified-p);
%’ if the buffer is read only (see buffer-read-only);
-’ otherwise. This differs from ‘%*’ only for a modified read-only buffer. @xref{Buffer Modification}.

%&

*’ if the buffer is modified, and ‘-’ otherwise.

%[

An indication of the depth of recursive editing levels (not counting minibuffer levels): one ‘[’ for each editing level. @xref{Recursive Editing}.

%]

One ‘]’ for each recursive editing level (not counting minibuffer levels).

%-

Dashes sufficient to fill the remainder of the mode line.

%%

The character ‘%’—this is how to include a literal ‘%’ in a string in which %-constructs are allowed.

The following two %-constructs are still supported, but they are obsolete, since you can get the same results with the variables mode-name and global-mode-string.

%m

The value of mode-name.

%M

The value of global-mode-string.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.6 Properties in the Mode Line

Certain text properties are meaningful in the mode line. The face property affects the appearance of text; the help-echo property associates help strings with the text, and keymap can make the text mouse-sensitive.

There are four ways to specify text properties for text in the mode line:

  1. Put a string with a text property directly into the mode line data structure.
  2. Put a text property on a mode line %-construct such as ‘%12b’; then the expansion of the %-construct will have that same text property.
  3. Use a (:propertize elt props…) construct to give elt a text property specified by props.
  4. Use a list containing :eval form in the mode line data structure, and make form evaluate to a string that has a text property.

You can use the keymap property to specify a keymap. This keymap only takes real effect for mouse clicks; binding character keys and function keys to it has no effect, since it is impossible to move point into the mode line.

When the mode line refers to a variable which does not have a non-nil risky-local-variable property, any text properties given or specified within that variable’s values are ignored. This is because such properties could otherwise specify functions to be called, and those functions could come from file local variables.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.7 Window Header Lines

A window can have a header line at the top, just as it can have a mode line at the bottom. The header line feature works just like the mode line feature, except that it’s controlled by header-line-format:

Variable: header-line-format

This variable, local in every buffer, specifies how to display the header line, for windows displaying the buffer. The format of the value is the same as for mode-line-format (see section The Data Structure of the Mode Line). It is normally nil, so that ordinary buffers have no header line.

Function: window-header-line-height &optional window

This function returns the height in pixels of window’s header line. window must be a live window, and defaults to the selected window.

A window that is just one line tall never displays a header line. A window that is two lines tall cannot display both a mode line and a header line at once; if it has a mode line, then it does not display a header line.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.8 Emulating Mode Line Formatting

You can use the function format-mode-line to compute the text that would appear in a mode line or header line based on a certain mode line construct.

Function: format-mode-line format &optional face window buffer

This function formats a line of text according to format as if it were generating the mode line for window, but it also returns the text as a string. The argument window defaults to the selected window. If buffer is non-nil, all the information used is taken from buffer; by default, it comes from window’s buffer.

The value string normally has text properties that correspond to the faces, keymaps, etc., that the mode line would have. Any character for which no face property is specified by format gets a default value determined by face. If face is t, that stands for either mode-line if window is selected, otherwise mode-line-inactive. If face is nil or omitted, that stands for the default face. If face is an integer, the value returned by this function will have no text properties.

You can also specify other valid faces as the value of face. If specified, that face provides the face property for characters whose face is not specified by format.

Note that using mode-line, mode-line-inactive, or header-line as face will actually redisplay the mode line or the header line, respectively, using the current definitions of the corresponding face, in addition to returning the formatted string. (Other faces do not cause redisplay.)

For example, (format-mode-line header-line-format) returns the text that would appear in the selected window’s header line ("" if it has no header line). (format-mode-line header-line-format 'header-line) returns the same text, with each character carrying the face that it will have in the header line itself, and also redraws the header line.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.5 Imenu

Imenu is a feature that lets users select a definition or section in the buffer, from a menu which lists all of them, to go directly to that location in the buffer. Imenu works by constructing a buffer index which lists the names and buffer positions of the definitions, or other named portions of the buffer; then the user can choose one of them and move point to it. Major modes can add a menu bar item to use Imenu using imenu-add-to-menubar.

Command: imenu-add-to-menubar name

This function defines a local menu bar item named name to run Imenu.

The user-level commands for using Imenu are described in the Emacs Manual (see Imenu in the Emacs Manual). This section explains how to customize Imenu’s method of finding definitions or buffer portions for a particular major mode.

The usual and simplest way is to set the variable imenu-generic-expression:

Variable: imenu-generic-expression

This variable, if non-nil, is a list that specifies regular expressions for finding definitions for Imenu. Simple elements of imenu-generic-expression look like this:

(menu-title regexp index)

Here, if menu-title is non-nil, it says that the matches for this element should go in a submenu of the buffer index; menu-title itself specifies the name for the submenu. If menu-title is nil, the matches for this element go directly in the top level of the buffer index.

The second item in the list, regexp, is a regular expression (@pxref{Regular Expressions}); anything in the buffer that it matches is considered a definition, something to mention in the buffer index. The third item, index, is a non-negative integer that indicates which subexpression in regexp matches the definition’s name.

An element can also look like this:

(menu-title regexp index function arguments…)

Each match for this element creates an index item, and when the index item is selected by the user, it calls function with arguments consisting of the item name, the buffer position, and arguments.

For Emacs Lisp mode, imenu-generic-expression could look like this:

((nil "^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\
\\s-+\\([-A-Za-z0-9+]+\\)" 2)
 ("*Vars*" "^\\s-*(def\\(var\\|const\\)\
\\s-+\\([-A-Za-z0-9+]+\\)" 2)
 ("*Types*"
  "^\\s-*\
(def\\(type\\|struct\\|class\\|ine-condition\\)\
\\s-+\\([-A-Za-z0-9+]+\\)" 2))

Setting this variable makes it buffer-local in the current buffer.

Variable: imenu-case-fold-search

This variable controls whether matching against the regular expressions in the value of imenu-generic-expression is case-sensitive: t, the default, means matching should ignore case.

Setting this variable makes it buffer-local in the current buffer.

Variable: imenu-syntax-alist

This variable is an alist of syntax table modifiers to use while processing imenu-generic-expression, to override the syntax table of the current buffer. Each element should have this form:

(characters . syntax-description)

The CAR, characters, can be either a character or a string. The element says to give that character or characters the syntax specified by syntax-description, which is passed to modify-syntax-entry (@pxref{Syntax Table Functions}).

This feature is typically used to give word syntax to characters which normally have symbol syntax, and thus to simplify imenu-generic-expression and speed up matching. For example, Fortran mode uses it this way:

(setq imenu-syntax-alist '(("_$" . "w")))

The imenu-generic-expression regular expressions can then use ‘\\sw+’ instead of ‘\\(\\sw\\|\\s_\\)+’. Note that this technique may be inconvenient when the mode needs to limit the initial character of a name to a smaller set of characters than are allowed in the rest of a name.

Setting this variable makes it buffer-local in the current buffer.

Another way to customize Imenu for a major mode is to set the variables imenu-prev-index-position-function and imenu-extract-index-name-function:

Variable: imenu-prev-index-position-function

If this variable is non-nil, its value should be a function that finds the next definition to put in the buffer index, scanning backward in the buffer from point. It should return nil if it doesn’t find another definition before point. Otherwise it should leave point at the place it finds a definition and return any non-nil value.

Setting this variable makes it buffer-local in the current buffer.

Variable: imenu-extract-index-name-function

If this variable is non-nil, its value should be a function to return the name for a definition, assuming point is in that definition as the imenu-prev-index-position-function function would leave it.

Setting this variable makes it buffer-local in the current buffer.

The last way to customize Imenu for a major mode is to set the variable imenu-create-index-function:

Variable: imenu-create-index-function

This variable specifies the function to use for creating a buffer index. The function should take no arguments, and return an index alist for the current buffer. It is called within save-excursion, so where it leaves point makes no difference.

The index alist can have three types of elements. Simple elements look like this:

(index-name . index-position)

Selecting a simple element has the effect of moving to position index-position in the buffer. Special elements look like this:

(index-name index-position function arguments…)

Selecting a special element performs:

(funcall function
         index-name index-position arguments…)

A nested sub-alist element looks like this:

(menu-title . sub-alist)

It creates the submenu menu-title specified by sub-alist.

The default value of imenu-create-index-function is imenu-default-create-index-function. This function calls the value of imenu-prev-index-position-function and the value of imenu-extract-index-name-function to produce the index alist. However, if either of these two variables is nil, the default function uses imenu-generic-expression instead.

Setting this variable makes it buffer-local in the current buffer.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6 Font Lock Mode

Font Lock mode is a buffer-local minor mode that automatically attaches face properties to certain parts of the buffer based on their syntactic role. How it parses the buffer depends on the major mode; most major modes define syntactic criteria for which faces to use in which contexts. This section explains how to customize Font Lock for a particular major mode.

Font Lock mode finds text to highlight in two ways: through syntactic parsing based on the syntax table, and through searching (usually for regular expressions). Syntactic fontification happens first; it finds comments and string constants and highlights them. Search-based fontification happens second.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.1 Font Lock Basics

The Font Lock functionality is based on several basic functions. Each of these calls the function specified by the corresponding variable. This indirection allows major and minor modes to modify the way fontification works in the buffers of that mode, and even use the Font Lock mechanisms for features that have nothing to do with fontification. (This is why the description below says “should” when it describes what the functions do: the mode can customize the values of the corresponding variables to do something entirely different.) The variables mentioned below are described in Other Font Lock Variables.

font-lock-fontify-buffer

This function should fontify the current buffer’s accessible portion, by calling the function specified by font-lock-fontify-buffer-function.

font-lock-unfontify-buffer

Used when turning Font Lock off to remove the fontification. Calls the function specified by font-lock-unfontify-buffer-function.

font-lock-fontify-region beg end &optional loudly

Should fontify the region between beg and end. If loudly is non-nil, should display status messages while fontifying. Calls the function specified by font-lock-fontify-region-function.

font-lock-unfontify-region beg end

Should remove fontification from the region between beg and end. Calls the function specified by font-lock-unfontify-region-function.

font-lock-flush &optional beg end

This function should mark the fontification of the region between beg and end as outdated. If not specified or nil, beg and end default to the beginning and end of the buffer’s accessible portion. Calls the function specified by font-lock-flush-function.

font-lock-ensure &optional beg end

This function should make sure the region between beg and end has been fontified. The optional arguments beg and end default to the beginning and the end of the buffer’s accessible portion. Calls the function specified by font-lock-ensure-function.

There are several variables that control how Font Lock mode highlights text. But major modes should not set any of these variables directly. Instead, they should set font-lock-defaults as a buffer-local variable. The value assigned to this variable is used, if and when Font Lock mode is enabled, to set all the other variables.

Variable: font-lock-defaults

This variable is set by modes to specify how to fontify text in that mode. It automatically becomes buffer-local when set. If its value is nil, Font Lock mode does no highlighting, and you can use the ‘Faces’ menu (under ‘Edit’ and then ‘Text Properties’ in the menu bar) to assign faces explicitly to text in the buffer.

If non-nil, the value should look like this:

(keywords [keywords-only [case-fold
 [syntax-alist other-vars…]]])

The first element, keywords, indirectly specifies the value of font-lock-keywords which directs search-based fontification. It can be a symbol, a variable or a function whose value is the list to use for font-lock-keywords. It can also be a list of several such symbols, one for each possible level of fontification. The first symbol specifies the ‘mode default’ level of fontification, the next symbol level 1 fontification, the next level 2, and so on. The ‘mode default’ level is normally the same as level 1. It is used when font-lock-maximum-decoration has a nil value. See section Levels of Font Lock.

The second element, keywords-only, specifies the value of the variable font-lock-keywords-only. If this is omitted or nil, syntactic fontification (of strings and comments) is also performed. If this is non-nil, syntactic fontification is not performed. See section Syntactic Font Lock.

The third element, case-fold, specifies the value of font-lock-keywords-case-fold-search. If it is non-nil, Font Lock mode ignores case during search-based fontification.

If the fourth element, syntax-alist, is non-nil, it should be a list of cons cells of the form (char-or-string . string). These are used to set up a syntax table for syntactic fontification; the resulting syntax table is stored in font-lock-syntax-table. If syntax-alist is omitted or nil, syntactic fontification uses the syntax table returned by the syntax-table function. @xref{Syntax Table Functions}.

All the remaining elements (if any) are collectively called other-vars. Each of these elements should have the form (variable . value)—which means, make variable buffer-local and then set it to value. You can use these other-vars to set other variables that affect fontification, aside from those you can control with the first five elements. See section Other Font Lock Variables.

If your mode fontifies text explicitly by adding font-lock-face properties, it can specify (nil t) for font-lock-defaults to turn off all automatic fontification. However, this is not required; it is possible to fontify some things using font-lock-face properties and set up automatic fontification for other parts of the text.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.2 Search-based Fontification

The variable which directly controls search-based fontification is font-lock-keywords, which is typically specified via the keywords element in font-lock-defaults.

Variable: font-lock-keywords

The value of this variable is a list of the keywords to highlight. Lisp programs should not set this variable directly. Normally, the value is automatically set by Font Lock mode, using the keywords element in font-lock-defaults. The value can also be altered using the functions font-lock-add-keywords and font-lock-remove-keywords (see section Customizing Search-Based Fontification).

Each element of font-lock-keywords specifies how to find certain cases of text, and how to highlight those cases. Font Lock mode processes the elements of font-lock-keywords one by one, and for each element, it finds and handles all matches. Ordinarily, once part of the text has been fontified already, this cannot be overridden by a subsequent match in the same text; but you can specify different behavior using the override element of a subexp-highlighter.

Each element of font-lock-keywords should have one of these forms:

regexp

Highlight all matches for regexp using font-lock-keyword-face. For example,

;; Highlight occurrences of the word ‘foo
;; using font-lock-keyword-face.
"\\<foo\\>"

Be careful when composing these regular expressions; a poorly written pattern can dramatically slow things down! The function regexp-opt (@pxref{Regexp Functions}) is useful for calculating optimal regular expressions to match several keywords.

function

Find text by calling function, and highlight the matches it finds using font-lock-keyword-face.

When function is called, it receives one argument, the limit of the search; it should begin searching at point, and not search beyond the limit. It should return non-nil if it succeeds, and set the match data to describe the match that was found. Returning nil indicates failure of the search.

Fontification will call function repeatedly with the same limit, and with point where the previous invocation left it, until function fails. On failure, function need not reset point in any particular way.

(matcher . subexp)

In this kind of element, matcher is either a regular expression or a function, as described above. The CDR, subexp, specifies which subexpression of matcher should be highlighted (instead of the entire text that matcher matched).

;; Highlight the ‘bar’ in each occurrence of ‘fubar’,
;; using font-lock-keyword-face.
("fu\\(bar\\)" . 1)

If you use regexp-opt to produce the regular expression matcher, you can use regexp-opt-depth (@pxref{Regexp Functions}) to calculate the value for subexp.

(matcher . facespec)

In this kind of element, facespec is an expression whose value specifies the face to use for highlighting. In the simplest case, facespec is a Lisp variable (a symbol) whose value is a face name.

;; Highlight occurrences of ‘fubar’,
;; using the face which is the value of fubar-face.
("fubar" . fubar-face)

However, facespec can also evaluate to a list of this form:

(face face prop1 val1 prop2 val2…)

to specify the face face and various additional text properties to put on the text that matches. If you do this, be sure to add the other text property names that you set in this way to the value of font-lock-extra-managed-props so that the properties will also be cleared out when they are no longer appropriate. Alternatively, you can set the variable font-lock-unfontify-region-function to a function that clears these properties. See section Other Font Lock Variables.

(matcher . subexp-highlighter)

In this kind of element, subexp-highlighter is a list which specifies how to highlight matches found by matcher. It has the form:

(subexp facespec [override [laxmatch]])

The CAR, subexp, is an integer specifying which subexpression of the match to fontify (0 means the entire matching text). The second subelement, facespec, is an expression whose value specifies the face, as described above.

The last two values in subexp-highlighter, override and laxmatch, are optional flags. If override is t, this element can override existing fontification made by previous elements of font-lock-keywords. If it is keep, then each character is fontified if it has not been fontified already by some other element. If it is prepend, the face specified by facespec is added to the beginning of the font-lock-face property. If it is append, the face is added to the end of the font-lock-face property.

If laxmatch is non-nil, it means there should be no error if there is no subexpression numbered subexp in matcher. Obviously, fontification of the subexpression numbered subexp will not occur. However, fontification of other subexpressions (and other regexps) will continue. If laxmatch is nil, and the specified subexpression is missing, then an error is signaled which terminates search-based fontification.

Here are some examples of elements of this kind, and what they do:

;; Highlight occurrences of either ‘foo’ or ‘bar’, using
;; foo-bar-face, even if they have already been highlighted.
;; foo-bar-face should be a variable whose value is a face.
("foo\\|bar" 0 foo-bar-face t)

;; Highlight the first subexpression within each occurrence
;; that the function fubar-match finds,
;; using the face which is the value of fubar-face.
(fubar-match 1 fubar-face)
(matcher . anchored-highlighter)

In this kind of element, anchored-highlighter specifies how to highlight text that follows a match found by matcher. So a match found by matcher acts as the anchor for further searches specified by anchored-highlighter. anchored-highlighter is a list of the following form:

(anchored-matcher pre-form post-form
                        subexp-highlighters…)

Here, anchored-matcher, like matcher, is either a regular expression or a function. After a match of matcher is found, point is at the end of the match. Now, Font Lock evaluates the form pre-form. Then it searches for matches of anchored-matcher and uses subexp-highlighters to highlight these. A subexp-highlighter is as described above. Finally, Font Lock evaluates post-form.

The forms pre-form and post-form can be used to initialize before, and cleanup after, anchored-matcher is used. Typically, pre-form is used to move point to some position relative to the match of matcher, before starting with anchored-matcher. post-form might be used to move back, before resuming with matcher.

After Font Lock evaluates pre-form, it does not search for anchored-matcher beyond the end of the line. However, if pre-form returns a buffer position that is greater than the position of point after pre-form is evaluated, then the position returned by pre-form is used as the limit of the search instead. It is generally a bad idea to return a position greater than the end of the line; in other words, the anchored-matcher search should not span lines.

For example,

;; Highlight occurrences of the word ‘item’ following
;; an occurrence of the word ‘anchor’ (on the same line)
;; in the value of item-face.
("\\<anchor\\>" "\\<item\\>" nil nil (0 item-face))

Here, pre-form and post-form are nil. Therefore searching for ‘item’ starts at the end of the match of ‘anchor’, and searching for subsequent instances of ‘anchor’ resumes from where searching for ‘item’ concluded.

(matcher highlighters…)

This sort of element specifies several highlighter lists for a single matcher. A highlighter list can be of the type subexp-highlighter or anchored-highlighter as described above.

For example,

;; Highlight occurrences of the word ‘anchor’ in the value
;; of anchor-face, and subsequent occurrences of the word
;; item’ (on the same line) in the value of item-face.
("\\<anchor\\>" (0 anchor-face)
                ("\\<item\\>" nil nil (0 item-face)))
(eval . form)

Here form is an expression to be evaluated the first time this value of font-lock-keywords is used in a buffer. Its value should have one of the forms described in this table.

Warning: Do not design an element of font-lock-keywords to match text which spans lines; this does not work reliably. For details, see See section Multiline Font Lock Constructs.

You can use case-fold in font-lock-defaults to specify the value of font-lock-keywords-case-fold-search which says whether search-based fontification should be case-insensitive.

Variable: font-lock-keywords-case-fold-search

Non-nil means that regular expression matching for the sake of font-lock-keywords should be case-insensitive.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.3 Customizing Search-Based Fontification

You can use font-lock-add-keywords to add additional search-based fontification rules to a major mode, and font-lock-remove-keywords to remove rules.

Function: font-lock-add-keywords mode keywords &optional how

This function adds highlighting keywords, for the current buffer or for major mode mode. The argument keywords should be a list with the same format as the variable font-lock-keywords.

If mode is a symbol which is a major mode command name, such as c-mode, the effect is that enabling Font Lock mode in mode will add keywords to font-lock-keywords. Calling with a non-nil value of mode is correct only in your ‘~/.emacs’ file.

If mode is nil, this function adds keywords to font-lock-keywords in the current buffer. This way of calling font-lock-add-keywords is usually used in mode hook functions.

By default, keywords are added at the beginning of font-lock-keywords. If the optional argument how is set, they are used to replace the value of font-lock-keywords. If how is any other non-nil value, they are added at the end of font-lock-keywords.

Some modes provide specialized support you can use in additional highlighting patterns. See the variables c-font-lock-extra-types, c++-font-lock-extra-types, and java-font-lock-extra-types, for example.

Warning: Major mode commands must not call font-lock-add-keywords under any circumstances, either directly or indirectly, except through their mode hooks. (Doing so would lead to incorrect behavior for some minor modes.) They should set up their rules for search-based fontification by setting font-lock-keywords.

Function: font-lock-remove-keywords mode keywords

This function removes keywords from font-lock-keywords for the current buffer or for major mode mode. As in font-lock-add-keywords, mode should be a major mode command name or nil. All the caveats and requirements for font-lock-add-keywords apply here too. The argument keywords must exactly match the one used by the corresponding font-lock-add-keywords.

For example, the following code adds two fontification patterns for C mode: one to fontify the word ‘FIXME’, even in comments, and another to fontify the words ‘and’, ‘or’ and ‘not’ as keywords.

(font-lock-add-keywords 'c-mode
 '(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
   ("\\<\\(and\\|or\\|not\\)\\>" . font-lock-keyword-face)))

This example affects only C mode proper. To add the same patterns to C mode and all modes derived from it, do this instead:

(add-hook 'c-mode-hook
 (lambda ()
  (font-lock-add-keywords nil
   '(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
     ("\\<\\(and\\|or\\|not\\)\\>" .
      font-lock-keyword-face)))))

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.4 Other Font Lock Variables

This section describes additional variables that a major mode can set by means of other-vars in font-lock-defaults (see section Font Lock Basics).

Variable: font-lock-mark-block-function

If this variable is non-nil, it should be a function that is called with no arguments, to choose an enclosing range of text for refontification for the command M-o M-o (font-lock-fontify-block).

The function should report its choice by placing the region around it. A good choice is a range of text large enough to give proper results, but not too large so that refontification becomes slow. Typical values are mark-defun for programming modes or mark-paragraph for textual modes.

Variable: font-lock-extra-managed-props

This variable specifies additional properties (other than font-lock-face) that are being managed by Font Lock mode. It is used by font-lock-default-unfontify-region, which normally only manages the font-lock-face property. If you want Font Lock to manage other properties as well, you must specify them in a facespec in font-lock-keywords as well as add them to this list. See section Search-based Fontification.

Variable: font-lock-fontify-buffer-function

Function to use for fontifying the buffer. The default value is font-lock-default-fontify-buffer.

Variable: font-lock-unfontify-buffer-function

Function to use for unfontifying the buffer. This is used when turning off Font Lock mode. The default value is font-lock-default-unfontify-buffer.

Variable: font-lock-fontify-region-function

Function to use for fontifying a region. It should take two arguments, the beginning and end of the region, and an optional third argument verbose. If verbose is non-nil, the function should print status messages. The default value is font-lock-default-fontify-region.

Variable: font-lock-unfontify-region-function

Function to use for unfontifying a region. It should take two arguments, the beginning and end of the region. The default value is font-lock-default-unfontify-region.

Variable: font-lock-flush-function

Function to use for declaring that a region’s fontification is out of date. It takes two arguments, the beginning and end of the region. The default value of this variable is font-lock-after-change-function.

Variable: font-lock-ensure-function

Function to use for making sure a region of the current buffer has been fontified. It is called with two arguments, the beginning and end of the region. The default value of this variable is a function that calls font-lock-default-fontify-buffer if the buffer is not fontified; the effect is to make sure the entire accessible portion of the buffer is fontified.

Function: jit-lock-register function &optional contextual

This function tells Font Lock mode to run the Lisp function function any time it has to fontify or refontify part of the current buffer. It calls function before calling the default fontification functions, and gives it two arguments, start and end, which specify the region to be fontified or refontified.

The optional argument contextual, if non-nil, forces Font Lock mode to always refontify a syntactically relevant part of the buffer, and not just the modified lines. This argument can usually be omitted.

Function: jit-lock-unregister function

If function was previously registered as a fontification function using jit-lock-register, this function unregisters it.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.5 Levels of Font Lock

Some major modes offer three different levels of fontification. You can define multiple levels by using a list of symbols for keywords in font-lock-defaults. Each symbol specifies one level of fontification; it is up to the user to choose one of these levels, normally by setting font-lock-maximum-decoration (see Font Lock in the GNU Emacs Manual). The chosen level’s symbol value is used to initialize font-lock-keywords.

Here are the conventions for how to define the levels of fontification:


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.6 Precalculated Fontification

Some major modes such as list-buffers and occur construct the buffer text programmatically. The easiest way for them to support Font Lock mode is to specify the faces of text when they insert the text in the buffer.

The way to do this is to specify the faces in the text with the special text property font-lock-face (@pxref{Special Properties}). When Font Lock mode is enabled, this property controls the display, just like the face property. When Font Lock mode is disabled, font-lock-face has no effect on the display.

It is ok for a mode to use font-lock-face for some text and also use the normal Font Lock machinery. But if the mode does not use the normal Font Lock machinery, it should not set the variable font-lock-defaults.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.7 Faces for Font Lock

Font Lock mode can highlight using any face, but Emacs defines several faces specifically for Font Lock to use to highlight text. These Font Lock faces are listed below. They can also be used by major modes for syntactic highlighting outside of Font Lock mode (see section Major Mode Conventions).

Each of these symbols is both a face name, and a variable whose default value is the symbol itself. Thus, the default value of font-lock-comment-face is font-lock-comment-face.

The faces are listed with descriptions of their typical usage, and in order of greater to lesser prominence. If a mode’s syntactic categories do not fit well with the usage descriptions, the faces can be assigned using the ordering as a guide.

font-lock-warning-face

for a construct that is peculiar, or that greatly changes the meaning of other text, like ‘;;;###autoload’ in Emacs Lisp and ‘#error’ in C.

font-lock-function-name-face

for the name of a function being defined or declared.

font-lock-variable-name-face

for the name of a variable being defined or declared.

font-lock-keyword-face

for a keyword with special syntactic significance, like ‘for’ and ‘if’ in C.

font-lock-comment-face

for comments.

font-lock-comment-delimiter-face

for comments delimiters, like ‘/*’ and ‘*/’ in C. On most terminals, this inherits from font-lock-comment-face.

font-lock-type-face

for the names of user-defined data types.

font-lock-constant-face

for the names of constants, like ‘NULL’ in C.

font-lock-builtin-face

for the names of built-in functions.

font-lock-preprocessor-face

for preprocessor commands. This inherits, by default, from font-lock-builtin-face.

font-lock-string-face

for string constants.

font-lock-doc-face

for documentation strings in the code. This inherits, by default, from font-lock-string-face.

font-lock-negation-char-face

for easily-overlooked negation characters.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.8 Syntactic Font Lock

Syntactic fontification uses a syntax table (@pxref{Syntax Tables}) to find and highlight syntactically relevant text. If enabled, it runs prior to search-based fontification. The variable font-lock-syntactic-face-function, documented below, determines which syntactic constructs to highlight. There are several variables that affect syntactic fontification; you should set them by means of font-lock-defaults (see section Font Lock Basics).

Whenever Font Lock mode performs syntactic fontification on a stretch of text, it first calls the function specified by syntax-propertize-function. Major modes can use this to apply syntax-table text properties to override the buffer’s syntax table in special cases. @xref{Syntax Properties}.

Variable: font-lock-keywords-only

If the value of this variable is non-nil, Font Lock does not do syntactic fontification, only search-based fontification based on font-lock-keywords. It is normally set by Font Lock mode based on the keywords-only element in font-lock-defaults.

Variable: font-lock-syntax-table

This variable holds the syntax table to use for fontification of comments and strings. It is normally set by Font Lock mode based on the syntax-alist element in font-lock-defaults. If this value is nil, syntactic fontification uses the buffer’s syntax table (the value returned by the function syntax-table; @pxref{Syntax Table Functions}).

Variable: font-lock-syntactic-face-function

If this variable is non-nil, it should be a function to determine which face to use for a given syntactic element (a string or a comment). The value is normally set through an other-vars element in font-lock-defaults.

The function is called with one argument, the parse state at point returned by parse-partial-sexp, and should return a face. The default value returns font-lock-comment-face for comments and font-lock-string-face for strings (see section Faces for Font Lock).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.9 Multiline Font Lock Constructs

Normally, elements of font-lock-keywords should not match across multiple lines; that doesn’t work reliably, because Font Lock usually scans just part of the buffer, and it can miss a multi-line construct that crosses the line boundary where the scan starts. (The scan normally starts at the beginning of a line.)

Making elements that match multiline constructs work properly has two aspects: correct identification and correct rehighlighting. The first means that Font Lock finds all multiline constructs. The second means that Font Lock will correctly rehighlight all the relevant text when a multiline construct is changed—for example, if some of the text that was previously part of a multiline construct ceases to be part of it. The two aspects are closely related, and often getting one of them to work will appear to make the other also work. However, for reliable results you must attend explicitly to both aspects.

There are three ways to ensure correct identification of multiline constructs:

There are three ways to do rehighlighting of multiline constructs:


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.9.1 Font Lock Multiline

One way to ensure reliable rehighlighting of multiline Font Lock constructs is to put on them the text property font-lock-multiline. It should be present and non-nil for text that is part of a multiline construct.

When Font Lock is about to highlight a range of text, it first extends the boundaries of the range as necessary so that they do not fall within text marked with the font-lock-multiline property. Then it removes any font-lock-multiline properties from the range, and highlights it. The highlighting specification (mostly font-lock-keywords) must reinstall this property each time, whenever it is appropriate.

Warning: don’t use the font-lock-multiline property on large ranges of text, because that will make rehighlighting slow.

Variable: font-lock-multiline

If the font-lock-multiline variable is set to t, Font Lock will try to add the font-lock-multiline property automatically on multiline constructs. This is not a universal solution, however, since it slows down Font Lock somewhat. It can miss some multiline constructs, or make the property larger or smaller than necessary.

For elements whose matcher is a function, the function should ensure that submatch 0 covers the whole relevant multiline construct, even if only a small subpart will be highlighted. It is often just as easy to add the font-lock-multiline property by hand.

The font-lock-multiline property is meant to ensure proper refontification; it does not automatically identify new multiline constructs. Identifying them requires that Font Lock mode operate on large enough chunks at a time. This will happen by accident on many cases, which may give the impression that multiline constructs magically work. If you set the font-lock-multiline variable non-nil, this impression will be even stronger, since the highlighting of those constructs which are found will be properly updated from then on. But that does not work reliably.

To find multiline constructs reliably, you must either manually place the font-lock-multiline property on the text before Font Lock mode looks at it, or use font-lock-fontify-region-function.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6.9.2 Region to Fontify after a Buffer Change

When a buffer is changed, the region that Font Lock refontifies is by default the smallest sequence of whole lines that spans the change. While this works well most of the time, sometimes it doesn’t—for example, when a change alters the syntactic meaning of text on an earlier line.

You can enlarge (or even reduce) the region to refontify by setting the following variable:

Variable: font-lock-extend-after-change-region-function

This buffer-local variable is either nil or a function for Font Lock mode to call to determine the region to scan and fontify.

The function is given three parameters, the standard beg, end, and old-len from after-change-functions (@pxref{Change Hooks}). It should return either a cons of the beginning and end buffer positions (in that order) of the region to fontify, or nil (which means choose the region in the standard way). This function needs to preserve point, the match-data, and the current restriction. The region it returns may start or end in the middle of a line.

Since this function is called after every buffer change, it should be reasonably fast.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7 Automatic Indentation of code

For programming languages, an important feature of a major mode is to provide automatic indentation. There are two parts: one is to decide what is the right indentation of a line, and the other is to decide when to reindent a line. By default, Emacs reindents a line whenever you type a character in electric-indent-chars, which by default only includes Newline. Major modes can add chars to electric-indent-chars according to the syntax of the language.

Deciding what is the right indentation is controlled in Emacs by indent-line-function (@pxref{Mode-Specific Indent}). For some modes, the right indentation cannot be known reliably, typically because indentation is significant so several indentations are valid but with different meanings. In that case, the mode should set electric-indent-inhibit to make sure the line is not constantly re-indented against the user’s wishes.

Writing a good indentation function can be difficult and to a large extent it is still a black art. Many major mode authors will start by writing a simple indentation function that works for simple cases, for example by comparing with the indentation of the previous text line. For most programming languages that are not really line-based, this tends to scale very poorly: improving such a function to let it handle more diverse situations tends to become more and more difficult, resulting in the end with a large, complex, unmaintainable indentation function which nobody dares to touch.

A good indentation function will usually need to actually parse the text, according to the syntax of the language. Luckily, it is not necessary to parse the text in as much detail as would be needed for a compiler, but on the other hand, the parser embedded in the indentation code will want to be somewhat friendly to syntactically incorrect code.

Good maintainable indentation functions usually fall into two categories: either parsing forward from some safe starting point until the position of interest, or parsing backward from the position of interest. Neither of the two is a clearly better choice than the other: parsing backward is often more difficult than parsing forward because programming languages are designed to be parsed forward, but for the purpose of indentation it has the advantage of not needing to guess a safe starting point, and it generally enjoys the property that only a minimum of text will be analyzed to decide the indentation of a line, so indentation will tend to be less affected by syntax errors in some earlier unrelated piece of code. Parsing forward on the other hand is usually easier and has the advantage of making it possible to reindent efficiently a whole region at a time, with a single parse.

Rather than write your own indentation function from scratch, it is often preferable to try and reuse some existing ones or to rely on a generic indentation engine. There are sadly few such engines. The CC-mode indentation code (used with C, C++, Java, Awk and a few other such modes) has been made more generic over the years, so if your language seems somewhat similar to one of those languages, you might try to use that engine. Another one is SMIE which takes an approach in the spirit of Lisp sexps and adapts it to non-Lisp languages.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1 Simple Minded Indentation Engine

SMIE is a package that provides a generic navigation and indentation engine. Based on a very simple parser using an operator precedence grammar, it lets major modes extend the sexp-based navigation of Lisp to non-Lisp languages as well as provide a simple to use but reliable auto-indentation.

Operator precedence grammar is a very primitive technology for parsing compared to some of the more common techniques used in compilers. It has the following characteristics: its parsing power is very limited, and it is largely unable to detect syntax errors, but it has the advantage of being algorithmically efficient and able to parse forward just as well as backward. In practice that means that SMIE can use it for indentation based on backward parsing, that it can provide both forward-sexp and backward-sexp functionality, and that it will naturally work on syntactically incorrect code without any extra effort. The downside is that it also means that most programming languages cannot be parsed correctly using SMIE, at least not without resorting to some special tricks (see section Living With a Weak Parser).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1.1 SMIE Setup and Features

SMIE is meant to be a one-stop shop for structural navigation and various other features which rely on the syntactic structure of code, in particular automatic indentation. The main entry point is smie-setup which is a function typically called while setting up a major mode.

Function: smie-setup grammar rules-function &rest keywords

Setup SMIE navigation and indentation. grammar is a grammar table generated by smie-prec2->grammar. rules-function is a set of indentation rules for use on smie-rules-function. keywords are additional arguments, which can include the following keywords:

Calling this function is sufficient to make commands such as forward-sexp, backward-sexp, and transpose-sexps be able to properly handle structural elements other than just the paired parentheses already handled by syntax tables. For example, if the provided grammar is precise enough, transpose-sexps can correctly transpose the two arguments of a + operator, taking into account the precedence rules of the language.

Calling smie-setup is also sufficient to make <TAB> indentation work in the expected way, extends blink-matching-paren to apply to elements like begin...end, and provides some commands that you can bind in the major mode keymap.

Command: smie-close-block

This command closes the most recently opened (and not yet closed) block.

Command: smie-down-list &optional arg

This command is like down-list but it also pays attention to nesting of tokens other than parentheses, such as begin...end.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1.2 Operator Precedence Grammars

SMIE’s precedence grammars simply give to each token a pair of precedences: the left-precedence and the right-precedence. We say T1 < T2 if the right-precedence of token T1 is less than the left-precedence of token T2. A good way to read this < is as a kind of parenthesis: if we find ... T1 something T2 ... then that should be parsed as ... T1 (something T2 ... rather than as ... T1 something) T2 .... The latter interpretation would be the case if we had T1 > T2. If we have T1 = T2, it means that token T2 follows token T1 in the same syntactic construction, so typically we have "begin" = "end". Such pairs of precedences are sufficient to express left-associativity or right-associativity of infix operators, nesting of tokens like parentheses and many other cases.

Function: smie-prec2->grammar table

This function takes a prec2 grammar table and returns an alist suitable for use in smie-setup. The prec2 table is itself meant to be built by one of the functions below.

Function: smie-merge-prec2s &rest tables

This function takes several prec2 tables and merges them into a new prec2 table.

Function: smie-precs->prec2 precs

This function builds a prec2 table from a table of precedences precs. precs should be a list, sorted by precedence (for example "+" will come before "*"), of elements of the form (assoc op ...), where each op is a token that acts as an operator; assoc is their associativity, which can be either left, right, assoc, or nonassoc. All operators in a given element share the same precedence level and associativity.

Function: smie-bnf->prec2 bnf &rest resolvers

This function lets you specify the grammar using a BNF notation. It accepts a bnf description of the grammar along with a set of conflict resolution rules resolvers, and returns a prec2 table.

bnf is a list of nonterminal definitions of the form (nonterm rhs1 rhs2 ...) where each rhs is a (non-empty) list of terminals (aka tokens) or non-terminals.

Not all grammars are accepted:

Additionally, conflicts can occur:

Precedence conflicts can be resolved via resolvers, which is a list of precs tables (see smie-precs->prec2): for each precedence conflict, if those precs tables specify a particular constraint, then the conflict is resolved by using this constraint instead, else a conflict is reported and one of the conflicting constraints is picked arbitrarily and the others are simply ignored.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1.3 Defining the Grammar of a Language

The usual way to define the SMIE grammar of a language is by defining a new global variable that holds the precedence table by giving a set of BNF rules. For example, the grammar definition for a small Pascal-like language could look like:

(require 'smie)
(defvar sample-smie-grammar
  (smie-prec2->grammar
   (smie-bnf->prec2
    '((id)
      (inst ("begin" insts "end")
            ("if" exp "then" inst "else" inst)
            (id ":=" exp)
            (exp))
      (insts (insts ";" insts) (inst))
      (exp (exp "+" exp)
           (exp "*" exp)
           ("(" exps ")"))
      (exps (exps "," exps) (exp)))
    '((assoc ";"))
    '((assoc ","))
    '((assoc "+") (assoc "*")))))

A few things to note:


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1.4 Defining Tokens

SMIE comes with a predefined lexical analyzer which uses syntax tables in the following way: any sequence of characters that have word or symbol syntax is considered a token, and so is any sequence of characters that have punctuation syntax. This default lexer is often a good starting point but is rarely actually correct for any given language. For example, it will consider "2,+3" to be composed of 3 tokens: "2", ",+", and "3".

To describe the lexing rules of your language to SMIE, you need 2 functions, one to fetch the next token, and another to fetch the previous token. Those functions will usually first skip whitespace and comments and then look at the next chunk of text to see if it is a special token. If so it should skip the token and return a description of this token. Usually this is simply the string extracted from the buffer, but it can be anything you want. For example:

(defvar sample-keywords-regexp
  (regexp-opt '("+" "*" "," ";" ">" ">=" "<" "<=" ":=" "=")))
(defun sample-smie-forward-token ()
  (forward-comment (point-max))
  (cond
   ((looking-at sample-keywords-regexp)
    (goto-char (match-end 0))
    (match-string-no-properties 0))
   (t (buffer-substring-no-properties
       (point)
       (progn (skip-syntax-forward "w_")
              (point))))))
(defun sample-smie-backward-token ()
  (forward-comment (- (point)))
  (cond
   ((looking-back sample-keywords-regexp (- (point) 2) t)
    (goto-char (match-beginning 0))
    (match-string-no-properties 0))
   (t (buffer-substring-no-properties
       (point)
       (progn (skip-syntax-backward "w_")
              (point))))))

Notice how those lexers return the empty string when in front of parentheses. This is because SMIE automatically takes care of the parentheses defined in the syntax table. More specifically if the lexer returns nil or an empty string, SMIE tries to handle the corresponding text as a sexp according to syntax tables.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1.5 Living With a Weak Parser

The parsing technique used by SMIE does not allow tokens to behave differently in different contexts. For most programming languages, this manifests itself by precedence conflicts when converting the BNF grammar.

Sometimes, those conflicts can be worked around by expressing the grammar slightly differently. For example, for Modula-2 it might seem natural to have a BNF grammar that looks like this:

  ...
  (inst ("IF" exp "THEN" insts "ELSE" insts "END")
        ("CASE" exp "OF" cases "END")
        ...)
  (cases (cases "|" cases)
         (caselabel ":" insts)
         ("ELSE" insts))
  ...

But this will create conflicts for "ELSE": on the one hand, the IF rule implies (among many other things) that "ELSE" = "END"; but on the other hand, since "ELSE" appears within cases, which appears left of "END", we also have "ELSE" > "END". We can solve the conflict either by using:

  ...
  (inst ("IF" exp "THEN" insts "ELSE" insts "END")
        ("CASE" exp "OF" cases "END")
        ("CASE" exp "OF" cases "ELSE" insts "END")
        ...)
  (cases (cases "|" cases) (caselabel ":" insts))
  ...

or

  ...
  (inst ("IF" exp "THEN" else "END")
        ("CASE" exp "OF" cases "END")
        ...)
  (else (insts "ELSE" insts))
  (cases (cases "|" cases) (caselabel ":" insts) (else))
  ...

Reworking the grammar to try and solve conflicts has its downsides, tho, because SMIE assumes that the grammar reflects the logical structure of the code, so it is preferable to keep the BNF closer to the intended abstract syntax tree.

Other times, after careful consideration you may conclude that those conflicts are not serious and simply resolve them via the resolvers argument of smie-bnf->prec2. Usually this is because the grammar is simply ambiguous: the conflict does not affect the set of programs described by the grammar, but only the way those programs are parsed. This is typically the case for separators and associative infix operators, where you want to add a resolver like '((assoc "|")). Another case where this can happen is for the classic dangling else problem, where you will use '((assoc "else" "then")). It can also happen for cases where the conflict is real and cannot really be resolved, but it is unlikely to pose a problem in practice.

Finally, in many cases some conflicts will remain despite all efforts to restructure the grammar. Do not despair: while the parser cannot be made more clever, you can make the lexer as smart as you want. So, the solution is then to look at the tokens involved in the conflict and to split one of those tokens into 2 (or more) different tokens. E.g., if the grammar needs to distinguish between two incompatible uses of the token "begin", make the lexer return different tokens (say "begin-fun" and "begin-plain") depending on which kind of "begin" it finds. This pushes the work of distinguishing the different cases to the lexer, which will thus have to look at the surrounding text to find ad-hoc clues.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1.6 Specifying Indentation Rules

Based on the provided grammar, SMIE will be able to provide automatic indentation without any extra effort. But in practice, this default indentation style will probably not be good enough. You will want to tweak it in many different cases.

SMIE indentation is based on the idea that indentation rules should be as local as possible. To this end, it relies on the idea of virtual indentation, which is the indentation that a particular program point would have if it were at the beginning of a line. Of course, if that program point is indeed at the beginning of a line, its virtual indentation is its current indentation. But if not, then SMIE uses the indentation algorithm to compute the virtual indentation of that point. Now in practice, the virtual indentation of a program point does not have to be identical to the indentation it would have if we inserted a newline before it. To see how this works, the SMIE rule for indentation after a { in C does not care whether the { is standing on a line of its own or is at the end of the preceding line. Instead, these different cases are handled in the indentation rule that decides how to indent before a {.

Another important concept is the notion of parent: The parent of a token, is the head token of the nearest enclosing syntactic construct. For example, the parent of an else is the if to which it belongs, and the parent of an if, in turn, is the lead token of the surrounding construct. The command backward-sexp jumps from a token to its parent, but there are some caveats: for openers (tokens which start a construct, like if), you need to start with point before the token, while for others you need to start with point after the token. backward-sexp stops with point before the parent token if that is the opener of the token of interest, and otherwise it stops with point after the parent token.

SMIE indentation rules are specified using a function that takes two arguments method and arg where the meaning of arg and the expected return value depend on method.

method can be:

When arg is a token, the function is called with point just before that token. A return value of nil always means to fallback on the default behavior, so the function should return nil for arguments it does not expect.

offset can be:


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1.7 Helper Functions for Indentation Rules

SMIE provides various functions designed specifically for use in the indentation rules function (several of those functions break if used in another context). These functions all start with the prefix smie-rule-.

Function: smie-rule-bolp

Return non-nil if the current token is the first on the line.

Function: smie-rule-hanging-p

Return non-nil if the current token is hanging. A token is hanging if it is the last token on the line and if it is preceded by other tokens: a lone token on a line is not hanging.

Function: smie-rule-next-p &rest tokens

Return non-nil if the next token is among tokens.

Function: smie-rule-prev-p &rest tokens

Return non-nil if the previous token is among tokens.

Function: smie-rule-parent-p &rest parents

Return non-nil if the current token’s parent is among parents.

Function: smie-rule-sibling-p

Return non-nil if the current token’s parent is actually a sibling. This is the case for example when the parent of a "," is just the previous ",".

Function: smie-rule-parent &optional offset

Return the proper offset to align the current token with the parent. If non-nil, offset should be an integer giving an additional offset to apply.

Function: smie-rule-separator method

Indent current token as a separator.

By separator, we mean here a token whose sole purpose is to separate various elements within some enclosing syntactic construct, and which does not have any semantic significance in itself (i.e., it would typically not exist as a node in an abstract syntax tree).

Such a token is expected to have an associative syntax and be closely tied to its syntactic parent. Typical examples are "," in lists of arguments (enclosed inside parentheses), or ";" in sequences of instructions (enclosed in a {...} or begin...end block).

method should be the method name that was passed to smie-rules-function.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1.8 Sample Indentation Rules

Here is an example of an indentation function:

(defun sample-smie-rules (kind token)
  (pcase (cons kind token)
    (`(:elem . basic) sample-indent-basic)
    (`(,_ . ",") (smie-rule-separator kind))
    (`(:after . ":=") sample-indent-basic)
    (`(:before . ,(or `"begin" `"(" `"{")))
     (if (smie-rule-hanging-p) (smie-rule-parent)))
    (`(:before . "if")
     (and (not (smie-rule-bolp)) (smie-rule-prev-p "else")
          (smie-rule-parent)))))

A few things to note:


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1.9 Customizing Indentation

If you are using a mode whose indentation is provided by SMIE, you can customize the indentation to suit your preferences. You can do this on a per-mode basis (using the option smie-config), or a per-file basis (using the function smie-config-local in a file-local variable specification).

User Option: smie-config

This option lets you customize indentation on a per-mode basis. It is an alist with elements of the form (mode . rules). For the precise form of rules, see the variable’s documentation; but you may find it easier to use the command smie-config-guess.

Command: smie-config-guess

This command tries to work out appropriate settings to produce your preferred style of indentation. Simply call the command while visiting a file that is indented with your style.

Command: smie-config-save

Call this command after using smie-config-guess, to save your settings for future sessions.

Command: smie-config-show-indent &optional move

This command displays the rules that are used to indent the current line.

Command: smie-config-set-indent

This command adds a local rule to adjust the indentation of the current line.

Function: smie-config-local rules

This function adds rules as indentation rules for the current buffer. These add to any mode-specific rules defined by the smie-config option. To specify custom indentation rules for a specific file, add an entry to the file’s local variables of the form: eval: (smie-config-local '(rules)).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.8 Desktop Save Mode

Desktop Save Mode is a feature to save the state of Emacs from one session to another. The user-level commands for using Desktop Save Mode are described in the GNU Emacs Manual (see Saving Emacs Sessions in the GNU Emacs Manual). Modes whose buffers visit a file, don’t have to do anything to use this feature.

For buffers not visiting a file to have their state saved, the major mode must bind the buffer local variable desktop-save-buffer to a non-nil value.

Variable: desktop-save-buffer

If this buffer-local variable is non-nil, the buffer will have its state saved in the desktop file at desktop save. If the value is a function, it is called at desktop save with argument desktop-dirname, and its value is saved in the desktop file along with the state of the buffer for which it was called. When file names are returned as part of the auxiliary information, they should be formatted using the call

(desktop-file-name file-name desktop-dirname)

For buffers not visiting a file to be restored, the major mode must define a function to do the job, and that function must be listed in the alist desktop-buffer-mode-handlers.

Variable: desktop-buffer-mode-handlers

Alist with elements

(major-mode . restore-buffer-function)

The function restore-buffer-function will be called with argument list

(buffer-file-name buffer-name desktop-buffer-misc)

and it should return the restored buffer. Here desktop-buffer-misc is the value returned by the function optionally bound to desktop-save-buffer.


[Top] [Contents] [Index] [ ? ]

About This Document

This document was generated on May 29, 2018 using texi2html.

The buttons in the navigation panels have the following meaning:

Button Name Go to From 1.2.3 go to
[ << ] FastBack Beginning of this chapter or previous chapter 1
[ < ] Back Previous section in reading order 1.2.2
[ Up ] Up Up section 1.2
[ > ] Forward Next section in reading order 1.2.4
[ >> ] FastForward Next chapter 2
[Top] Top Cover (top) of document  
[Contents] Contents Table of contents  
[Index] Index Index  
[ ? ] About About (help)  

where the Example assumes that the current position is at Subsubsection One-Two-Three of a document of the following structure:


This document was generated on May 29, 2018 using texi2html.